three.cjs 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '174';
  8. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  9. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  10. const CullFaceNone = 0;
  11. const CullFaceBack = 1;
  12. const CullFaceFront = 2;
  13. const CullFaceFrontBack = 3;
  14. const BasicShadowMap = 0;
  15. const PCFShadowMap = 1;
  16. const PCFSoftShadowMap = 2;
  17. const VSMShadowMap = 3;
  18. const FrontSide = 0;
  19. const BackSide = 1;
  20. const DoubleSide = 2;
  21. const NoBlending = 0;
  22. const NormalBlending = 1;
  23. const AdditiveBlending = 2;
  24. const SubtractiveBlending = 3;
  25. const MultiplyBlending = 4;
  26. const CustomBlending = 5;
  27. const AddEquation = 100;
  28. const SubtractEquation = 101;
  29. const ReverseSubtractEquation = 102;
  30. const MinEquation = 103;
  31. const MaxEquation = 104;
  32. const ZeroFactor = 200;
  33. const OneFactor = 201;
  34. const SrcColorFactor = 202;
  35. const OneMinusSrcColorFactor = 203;
  36. const SrcAlphaFactor = 204;
  37. const OneMinusSrcAlphaFactor = 205;
  38. const DstAlphaFactor = 206;
  39. const OneMinusDstAlphaFactor = 207;
  40. const DstColorFactor = 208;
  41. const OneMinusDstColorFactor = 209;
  42. const SrcAlphaSaturateFactor = 210;
  43. const ConstantColorFactor = 211;
  44. const OneMinusConstantColorFactor = 212;
  45. const ConstantAlphaFactor = 213;
  46. const OneMinusConstantAlphaFactor = 214;
  47. const NeverDepth = 0;
  48. const AlwaysDepth = 1;
  49. const LessDepth = 2;
  50. const LessEqualDepth = 3;
  51. const EqualDepth = 4;
  52. const GreaterEqualDepth = 5;
  53. const GreaterDepth = 6;
  54. const NotEqualDepth = 7;
  55. const MultiplyOperation = 0;
  56. const MixOperation = 1;
  57. const AddOperation = 2;
  58. const NoToneMapping = 0;
  59. const LinearToneMapping = 1;
  60. const ReinhardToneMapping = 2;
  61. const CineonToneMapping = 3;
  62. const ACESFilmicToneMapping = 4;
  63. const CustomToneMapping = 5;
  64. const AgXToneMapping = 6;
  65. const NeutralToneMapping = 7;
  66. const AttachedBindMode = 'attached';
  67. const DetachedBindMode = 'detached';
  68. const UVMapping = 300;
  69. const CubeReflectionMapping = 301;
  70. const CubeRefractionMapping = 302;
  71. const EquirectangularReflectionMapping = 303;
  72. const EquirectangularRefractionMapping = 304;
  73. const CubeUVReflectionMapping = 306;
  74. const RepeatWrapping = 1000;
  75. const ClampToEdgeWrapping = 1001;
  76. const MirroredRepeatWrapping = 1002;
  77. const NearestFilter = 1003;
  78. const NearestMipmapNearestFilter = 1004;
  79. const NearestMipMapNearestFilter = 1004;
  80. const NearestMipmapLinearFilter = 1005;
  81. const NearestMipMapLinearFilter = 1005;
  82. const LinearFilter = 1006;
  83. const LinearMipmapNearestFilter = 1007;
  84. const LinearMipMapNearestFilter = 1007;
  85. const LinearMipmapLinearFilter = 1008;
  86. const LinearMipMapLinearFilter = 1008;
  87. const UnsignedByteType = 1009;
  88. const ByteType = 1010;
  89. const ShortType = 1011;
  90. const UnsignedShortType = 1012;
  91. const IntType = 1013;
  92. const UnsignedIntType = 1014;
  93. const FloatType = 1015;
  94. const HalfFloatType = 1016;
  95. const UnsignedShort4444Type = 1017;
  96. const UnsignedShort5551Type = 1018;
  97. const UnsignedInt248Type = 1020;
  98. const UnsignedInt5999Type = 35902;
  99. const AlphaFormat = 1021;
  100. const RGBFormat = 1022;
  101. const RGBAFormat = 1023;
  102. const LuminanceFormat = 1024;
  103. const LuminanceAlphaFormat = 1025;
  104. const DepthFormat = 1026;
  105. const DepthStencilFormat = 1027;
  106. const RedFormat = 1028;
  107. const RedIntegerFormat = 1029;
  108. const RGFormat = 1030;
  109. const RGIntegerFormat = 1031;
  110. const RGBIntegerFormat = 1032;
  111. const RGBAIntegerFormat = 1033;
  112. const RGB_S3TC_DXT1_Format = 33776;
  113. const RGBA_S3TC_DXT1_Format = 33777;
  114. const RGBA_S3TC_DXT3_Format = 33778;
  115. const RGBA_S3TC_DXT5_Format = 33779;
  116. const RGB_PVRTC_4BPPV1_Format = 35840;
  117. const RGB_PVRTC_2BPPV1_Format = 35841;
  118. const RGBA_PVRTC_4BPPV1_Format = 35842;
  119. const RGBA_PVRTC_2BPPV1_Format = 35843;
  120. const RGB_ETC1_Format = 36196;
  121. const RGB_ETC2_Format = 37492;
  122. const RGBA_ETC2_EAC_Format = 37496;
  123. const RGBA_ASTC_4x4_Format = 37808;
  124. const RGBA_ASTC_5x4_Format = 37809;
  125. const RGBA_ASTC_5x5_Format = 37810;
  126. const RGBA_ASTC_6x5_Format = 37811;
  127. const RGBA_ASTC_6x6_Format = 37812;
  128. const RGBA_ASTC_8x5_Format = 37813;
  129. const RGBA_ASTC_8x6_Format = 37814;
  130. const RGBA_ASTC_8x8_Format = 37815;
  131. const RGBA_ASTC_10x5_Format = 37816;
  132. const RGBA_ASTC_10x6_Format = 37817;
  133. const RGBA_ASTC_10x8_Format = 37818;
  134. const RGBA_ASTC_10x10_Format = 37819;
  135. const RGBA_ASTC_12x10_Format = 37820;
  136. const RGBA_ASTC_12x12_Format = 37821;
  137. const RGBA_BPTC_Format = 36492;
  138. const RGB_BPTC_SIGNED_Format = 36494;
  139. const RGB_BPTC_UNSIGNED_Format = 36495;
  140. const RED_RGTC1_Format = 36283;
  141. const SIGNED_RED_RGTC1_Format = 36284;
  142. const RED_GREEN_RGTC2_Format = 36285;
  143. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  144. const LoopOnce = 2200;
  145. const LoopRepeat = 2201;
  146. const LoopPingPong = 2202;
  147. const InterpolateDiscrete = 2300;
  148. const InterpolateLinear = 2301;
  149. const InterpolateSmooth = 2302;
  150. const ZeroCurvatureEnding = 2400;
  151. const ZeroSlopeEnding = 2401;
  152. const WrapAroundEnding = 2402;
  153. const NormalAnimationBlendMode = 2500;
  154. const AdditiveAnimationBlendMode = 2501;
  155. const TrianglesDrawMode = 0;
  156. const TriangleStripDrawMode = 1;
  157. const TriangleFanDrawMode = 2;
  158. const BasicDepthPacking = 3200;
  159. const RGBADepthPacking = 3201;
  160. const RGBDepthPacking = 3202;
  161. const RGDepthPacking = 3203;
  162. const TangentSpaceNormalMap = 0;
  163. const ObjectSpaceNormalMap = 1;
  164. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  165. const NoColorSpace = '';
  166. const SRGBColorSpace = 'srgb';
  167. const LinearSRGBColorSpace = 'srgb-linear';
  168. const LinearTransfer = 'linear';
  169. const SRGBTransfer = 'srgb';
  170. const ZeroStencilOp = 0;
  171. const KeepStencilOp = 7680;
  172. const ReplaceStencilOp = 7681;
  173. const IncrementStencilOp = 7682;
  174. const DecrementStencilOp = 7683;
  175. const IncrementWrapStencilOp = 34055;
  176. const DecrementWrapStencilOp = 34056;
  177. const InvertStencilOp = 5386;
  178. const NeverStencilFunc = 512;
  179. const LessStencilFunc = 513;
  180. const EqualStencilFunc = 514;
  181. const LessEqualStencilFunc = 515;
  182. const GreaterStencilFunc = 516;
  183. const NotEqualStencilFunc = 517;
  184. const GreaterEqualStencilFunc = 518;
  185. const AlwaysStencilFunc = 519;
  186. const NeverCompare = 512;
  187. const LessCompare = 513;
  188. const EqualCompare = 514;
  189. const LessEqualCompare = 515;
  190. const GreaterCompare = 516;
  191. const NotEqualCompare = 517;
  192. const GreaterEqualCompare = 518;
  193. const AlwaysCompare = 519;
  194. const StaticDrawUsage = 35044;
  195. const DynamicDrawUsage = 35048;
  196. const StreamDrawUsage = 35040;
  197. const StaticReadUsage = 35045;
  198. const DynamicReadUsage = 35049;
  199. const StreamReadUsage = 35041;
  200. const StaticCopyUsage = 35046;
  201. const DynamicCopyUsage = 35050;
  202. const StreamCopyUsage = 35042;
  203. const GLSL1 = '100';
  204. const GLSL3 = '300 es';
  205. const WebGLCoordinateSystem = 2000;
  206. const WebGPUCoordinateSystem = 2001;
  207. const TimestampQuery = {
  208. COMPUTE: 'compute',
  209. RENDER: 'render'
  210. };
  211. /**
  212. * This modules allows to dispatch event objects on custom JavaScript objects.
  213. *
  214. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  215. *
  216. * Code Example:
  217. * ```js
  218. * class Car extends EventDispatcher {
  219. * start() {
  220. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  221. * }
  222. *};
  223. *
  224. * // Using events with the custom object
  225. * const car = new Car();
  226. * car.addEventListener( 'start', function ( event ) {
  227. * alert( event.message );
  228. * } );
  229. *
  230. * car.start();
  231. * ```
  232. */
  233. class EventDispatcher {
  234. /**
  235. * Adds the given event listener to the given event type.
  236. *
  237. * @param {string} type - The type of event to listen to.
  238. * @param {Function} listener - The function that gets called when the event is fired.
  239. */
  240. addEventListener( type, listener ) {
  241. if ( this._listeners === undefined ) this._listeners = {};
  242. const listeners = this._listeners;
  243. if ( listeners[ type ] === undefined ) {
  244. listeners[ type ] = [];
  245. }
  246. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  247. listeners[ type ].push( listener );
  248. }
  249. }
  250. /**
  251. * Returns `true` if the given event listener has been added to the given event type.
  252. *
  253. * @param {string} type - The type of event.
  254. * @param {Function} listener - The listener to check.
  255. * @return {boolean} Whether the given event listener has been added to the given event type.
  256. */
  257. hasEventListener( type, listener ) {
  258. const listeners = this._listeners;
  259. if ( listeners === undefined ) return false;
  260. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  261. }
  262. /**
  263. * Removes the given event listener from the given event type.
  264. *
  265. * @param {string} type - The type of event.
  266. * @param {Function} listener - The listener to remove.
  267. */
  268. removeEventListener( type, listener ) {
  269. const listeners = this._listeners;
  270. if ( listeners === undefined ) return;
  271. const listenerArray = listeners[ type ];
  272. if ( listenerArray !== undefined ) {
  273. const index = listenerArray.indexOf( listener );
  274. if ( index !== -1 ) {
  275. listenerArray.splice( index, 1 );
  276. }
  277. }
  278. }
  279. /**
  280. * Dispatches an event object.
  281. *
  282. * @param {Object} event - The event that gets fired.
  283. */
  284. dispatchEvent( event ) {
  285. const listeners = this._listeners;
  286. if ( listeners === undefined ) return;
  287. const listenerArray = listeners[ event.type ];
  288. if ( listenerArray !== undefined ) {
  289. event.target = this;
  290. // Make a copy, in case listeners are removed while iterating.
  291. const array = listenerArray.slice( 0 );
  292. for ( let i = 0, l = array.length; i < l; i ++ ) {
  293. array[ i ].call( this, event );
  294. }
  295. event.target = null;
  296. }
  297. }
  298. }
  299. 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' ];
  300. let _seed = 1234567;
  301. const DEG2RAD = Math.PI / 180;
  302. const RAD2DEG = 180 / Math.PI;
  303. /**
  304. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  305. * (universally unique identifier).
  306. *
  307. * @return {string} The UUID.
  308. */
  309. function generateUUID() {
  310. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  311. const d0 = Math.random() * 0xffffffff | 0;
  312. const d1 = Math.random() * 0xffffffff | 0;
  313. const d2 = Math.random() * 0xffffffff | 0;
  314. const d3 = Math.random() * 0xffffffff | 0;
  315. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  316. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  317. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  318. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  319. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  320. return uuid.toLowerCase();
  321. }
  322. /**
  323. * Clamps the given value between min and max.
  324. *
  325. * @param {number} value - The value to clamp.
  326. * @param {number} min - The min value.
  327. * @param {number} max - The max value.
  328. * @return {number} The clamped value.
  329. */
  330. function clamp( value, min, max ) {
  331. return Math.max( min, Math.min( max, value ) );
  332. }
  333. /**
  334. * Computes the Euclidean modulo of the given parameters that
  335. * is `( ( n % m ) + m ) % m`.
  336. *
  337. * @param {number} n - The first parameter.
  338. * @param {number} m - The second parameter.
  339. * @return {number} The Euclidean modulo.
  340. */
  341. function euclideanModulo( n, m ) {
  342. // https://en.wikipedia.org/wiki/Modulo_operation
  343. return ( ( n % m ) + m ) % m;
  344. }
  345. /**
  346. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  347. * for the given value.
  348. *
  349. * @param {number} x - The value to be mapped.
  350. * @param {number} a1 - Minimum value for range A.
  351. * @param {number} a2 - Maximum value for range A.
  352. * @param {number} b1 - Minimum value for range B.
  353. * @param {number} b2 - Maximum value for range B.
  354. * @return {number} The mapped value.
  355. */
  356. function mapLinear( x, a1, a2, b1, b2 ) {
  357. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  358. }
  359. /**
  360. * Returns the percentage in the closed interval `[0, 1]` of the given value
  361. * between the start and end point.
  362. *
  363. * @param {number} x - The start point
  364. * @param {number} y - The end point.
  365. * @param {number} value - A value between start and end.
  366. * @return {number} The interpolation factor.
  367. */
  368. function inverseLerp( x, y, value ) {
  369. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  370. if ( x !== y ) {
  371. return ( value - x ) / ( y - x );
  372. } else {
  373. return 0;
  374. }
  375. }
  376. /**
  377. * Returns a value linearly interpolated from two known points based on the given interval -
  378. * `t = 0` will return `x` and `t = 1` will return `y`.
  379. *
  380. * @param {number} x - The start point
  381. * @param {number} y - The end point.
  382. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  383. * @return {number} The interpolated value.
  384. */
  385. function lerp( x, y, t ) {
  386. return ( 1 - t ) * x + t * y;
  387. }
  388. /**
  389. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  390. * time to maintain frame rate independent movement. For details, see
  391. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  392. *
  393. * @param {number} x - The current point.
  394. * @param {number} y - The target point.
  395. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  396. * and a lower value will make the movement more gradual.
  397. * @param {number} dt - Delta time in seconds.
  398. * @return {number} The interpolated value.
  399. */
  400. function damp( x, y, lambda, dt ) {
  401. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  402. }
  403. /**
  404. * Returns a value that alternates between `0` and the given `length` parameter.
  405. *
  406. * @param {number} x - The value to pingpong.
  407. * @param {number} [length=1] - The positive value the function will pingpong to.
  408. * @return {number} The alternated value.
  409. */
  410. function pingpong( x, length = 1 ) {
  411. // https://www.desmos.com/calculator/vcsjnyz7x4
  412. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  413. }
  414. /**
  415. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  416. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  417. * the `min` and `max`.
  418. *
  419. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  420. *
  421. * @param {number} x - The value to evaluate based on its position between min and max.
  422. * @param {number} min - The min value. Any x value below min will be `0`.
  423. * @param {number} max - The max value. Any x value above max will be `1`.
  424. * @return {number} The alternated value.
  425. */
  426. function smoothstep( x, min, max ) {
  427. if ( x <= min ) return 0;
  428. if ( x >= max ) return 1;
  429. x = ( x - min ) / ( max - min );
  430. return x * x * ( 3 - 2 * x );
  431. }
  432. /**
  433. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  434. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  435. *
  436. * @param {number} x - The value to evaluate based on its position between min and max.
  437. * @param {number} min - The min value. Any x value below min will be `0`.
  438. * @param {number} max - The max value. Any x value above max will be `1`.
  439. * @return {number} The alternated value.
  440. */
  441. function smootherstep( x, min, max ) {
  442. if ( x <= min ) return 0;
  443. if ( x >= max ) return 1;
  444. x = ( x - min ) / ( max - min );
  445. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  446. }
  447. /**
  448. * Returns a random integer from `<low, high>` interval.
  449. *
  450. * @param {number} low - The lower value boundary.
  451. * @param {number} high - The upper value boundary
  452. * @return {number} A random integer.
  453. */
  454. function randInt( low, high ) {
  455. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  456. }
  457. /**
  458. * Returns a random float from `<low, high>` interval.
  459. *
  460. * @param {number} low - The lower value boundary.
  461. * @param {number} high - The upper value boundary
  462. * @return {number} A random float.
  463. */
  464. function randFloat( low, high ) {
  465. return low + Math.random() * ( high - low );
  466. }
  467. /**
  468. * Returns a random integer from `<-range/2, range/2>` interval.
  469. *
  470. * @param {number} range - Defines the value range.
  471. * @return {number} A random float.
  472. */
  473. function randFloatSpread( range ) {
  474. return range * ( 0.5 - Math.random() );
  475. }
  476. /**
  477. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  478. *
  479. * @param {number} [s] - The integer seed.
  480. * @return {number} A random float.
  481. */
  482. function seededRandom( s ) {
  483. if ( s !== undefined ) _seed = s;
  484. // Mulberry32 generator
  485. let t = _seed += 0x6D2B79F5;
  486. t = Math.imul( t ^ t >>> 15, t | 1 );
  487. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  488. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  489. }
  490. /**
  491. * Converts degrees to radians.
  492. *
  493. * @param {number} degrees - A value in degrees.
  494. * @return {number} The converted value in radians.
  495. */
  496. function degToRad( degrees ) {
  497. return degrees * DEG2RAD;
  498. }
  499. /**
  500. * Converts radians to degrees.
  501. *
  502. * @param {number} radians - A value in radians.
  503. * @return {number} The converted value in degrees.
  504. */
  505. function radToDeg( radians ) {
  506. return radians * RAD2DEG;
  507. }
  508. /**
  509. * Returns `true` if the given number is a power of two.
  510. *
  511. * @param {number} value - The value to check.
  512. * @return {boolean} Whether the given number is a power of two or not.
  513. */
  514. function isPowerOfTwo( value ) {
  515. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  516. }
  517. /**
  518. * Returns the smallest power of two that is greater than or equal to the given number.
  519. *
  520. * @param {number} value - The value to find a POT for.
  521. * @return {number} The smallest power of two that is greater than or equal to the given number.
  522. */
  523. function ceilPowerOfTwo( value ) {
  524. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  525. }
  526. /**
  527. * Returns the largest power of two that is less than or equal to the given number.
  528. *
  529. * @param {number} value - The value to find a POT for.
  530. * @return {number} The largest power of two that is less than or equal to the given number.
  531. */
  532. function floorPowerOfTwo( value ) {
  533. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  534. }
  535. /**
  536. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  537. * defined by the given angles and order.
  538. *
  539. * Rotations are applied to the axes in the order specified by order:
  540. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  541. *
  542. * @param {Quaternion} q - The quaternion to set.
  543. * @param {number} a - The rotation applied to the first axis, in radians.
  544. * @param {number} b - The rotation applied to the second axis, in radians.
  545. * @param {number} c - The rotation applied to the third axis, in radians.
  546. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  547. */
  548. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  549. const cos = Math.cos;
  550. const sin = Math.sin;
  551. const c2 = cos( b / 2 );
  552. const s2 = sin( b / 2 );
  553. const c13 = cos( ( a + c ) / 2 );
  554. const s13 = sin( ( a + c ) / 2 );
  555. const c1_3 = cos( ( a - c ) / 2 );
  556. const s1_3 = sin( ( a - c ) / 2 );
  557. const c3_1 = cos( ( c - a ) / 2 );
  558. const s3_1 = sin( ( c - a ) / 2 );
  559. switch ( order ) {
  560. case 'XYX':
  561. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  562. break;
  563. case 'YZY':
  564. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  565. break;
  566. case 'ZXZ':
  567. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  568. break;
  569. case 'XZX':
  570. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  571. break;
  572. case 'YXY':
  573. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  574. break;
  575. case 'ZYZ':
  576. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  577. break;
  578. default:
  579. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  580. }
  581. }
  582. /**
  583. * Denormalizes the given value according to the given typed array.
  584. *
  585. * @param {number} value - The value to denormalize.
  586. * @param {TypedArray} array - The typed array that defines the data type of the value.
  587. * @return {number} The denormalize (float) value in the range `[0,1]`.
  588. */
  589. function denormalize( value, array ) {
  590. switch ( array.constructor ) {
  591. case Float32Array:
  592. return value;
  593. case Uint32Array:
  594. return value / 4294967295.0;
  595. case Uint16Array:
  596. return value / 65535.0;
  597. case Uint8Array:
  598. return value / 255.0;
  599. case Int32Array:
  600. return Math.max( value / 2147483647.0, -1 );
  601. case Int16Array:
  602. return Math.max( value / 32767.0, -1 );
  603. case Int8Array:
  604. return Math.max( value / 127.0, -1 );
  605. default:
  606. throw new Error( 'Invalid component type.' );
  607. }
  608. }
  609. /**
  610. * Normalizes the given value according to the given typed array.
  611. *
  612. * @param {number} value - The float value in the range `[0,1]` to normalize.
  613. * @param {TypedArray} array - The typed array that defines the data type of the value.
  614. * @return {number} The normalize value.
  615. */
  616. function normalize( value, array ) {
  617. switch ( array.constructor ) {
  618. case Float32Array:
  619. return value;
  620. case Uint32Array:
  621. return Math.round( value * 4294967295.0 );
  622. case Uint16Array:
  623. return Math.round( value * 65535.0 );
  624. case Uint8Array:
  625. return Math.round( value * 255.0 );
  626. case Int32Array:
  627. return Math.round( value * 2147483647.0 );
  628. case Int16Array:
  629. return Math.round( value * 32767.0 );
  630. case Int8Array:
  631. return Math.round( value * 127.0 );
  632. default:
  633. throw new Error( 'Invalid component type.' );
  634. }
  635. }
  636. const MathUtils = {
  637. DEG2RAD: DEG2RAD,
  638. RAD2DEG: RAD2DEG,
  639. generateUUID: generateUUID,
  640. clamp: clamp,
  641. euclideanModulo: euclideanModulo,
  642. mapLinear: mapLinear,
  643. inverseLerp: inverseLerp,
  644. lerp: lerp,
  645. damp: damp,
  646. pingpong: pingpong,
  647. smoothstep: smoothstep,
  648. smootherstep: smootherstep,
  649. randInt: randInt,
  650. randFloat: randFloat,
  651. randFloatSpread: randFloatSpread,
  652. seededRandom: seededRandom,
  653. degToRad: degToRad,
  654. radToDeg: radToDeg,
  655. isPowerOfTwo: isPowerOfTwo,
  656. ceilPowerOfTwo: ceilPowerOfTwo,
  657. floorPowerOfTwo: floorPowerOfTwo,
  658. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  659. normalize: normalize,
  660. denormalize: denormalize
  661. };
  662. /**
  663. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  664. * (labeled x and y), which can be used to represent a number of things, such as:
  665. *
  666. * - A point in 2D space (i.e. a position on a plane).
  667. * - A direction and length across a plane. In three.js the length will
  668. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  669. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  670. * - Any arbitrary ordered pair of numbers.
  671. *
  672. * There are other things a 2D vector can be used to represent, such as
  673. * momentum vectors, complex numbers and so on, however these are the most
  674. * common uses in three.js.
  675. *
  676. * Iterating through a vector instance will yield its components `(x, y)` in
  677. * the corresponding order.
  678. * ```js
  679. * const a = new THREE.Vector2( 0, 1 );
  680. *
  681. * //no arguments; will be initialised to (0, 0)
  682. * const b = new THREE.Vector2( );
  683. *
  684. * const d = a.distanceTo( b );
  685. * ```
  686. */
  687. class Vector2 {
  688. /**
  689. * Constructs a new 2D vector.
  690. *
  691. * @param {number} [x=0] - The x value of this vector.
  692. * @param {number} [y=0] - The y value of this vector.
  693. */
  694. constructor( x = 0, y = 0 ) {
  695. /**
  696. * This flag can be used for type testing.
  697. *
  698. * @type {boolean}
  699. * @readonly
  700. * @default true
  701. */
  702. Vector2.prototype.isVector2 = true;
  703. /**
  704. * The x value of this vector.
  705. *
  706. * @type {number}
  707. */
  708. this.x = x;
  709. /**
  710. * The y value of this vector.
  711. *
  712. * @type {number}
  713. */
  714. this.y = y;
  715. }
  716. /**
  717. * Alias for {@link Vector2#x}.
  718. *
  719. * @type {number}
  720. */
  721. get width() {
  722. return this.x;
  723. }
  724. set width( value ) {
  725. this.x = value;
  726. }
  727. /**
  728. * Alias for {@link Vector2#y}.
  729. *
  730. * @type {number}
  731. */
  732. get height() {
  733. return this.y;
  734. }
  735. set height( value ) {
  736. this.y = value;
  737. }
  738. /**
  739. * Sets the vector components.
  740. *
  741. * @param {number} x - The value of the x component.
  742. * @param {number} y - The value of the y component.
  743. * @return {Vector2} A reference to this vector.
  744. */
  745. set( x, y ) {
  746. this.x = x;
  747. this.y = y;
  748. return this;
  749. }
  750. /**
  751. * Sets the vector components to the same value.
  752. *
  753. * @param {number} scalar - The value to set for all vector components.
  754. * @return {Vector2} A reference to this vector.
  755. */
  756. setScalar( scalar ) {
  757. this.x = scalar;
  758. this.y = scalar;
  759. return this;
  760. }
  761. /**
  762. * Sets the vector's x component to the given value
  763. *
  764. * @param {number} x - The value to set.
  765. * @return {Vector2} A reference to this vector.
  766. */
  767. setX( x ) {
  768. this.x = x;
  769. return this;
  770. }
  771. /**
  772. * Sets the vector's y component to the given value
  773. *
  774. * @param {number} y - The value to set.
  775. * @return {Vector2} A reference to this vector.
  776. */
  777. setY( y ) {
  778. this.y = y;
  779. return this;
  780. }
  781. /**
  782. * Allows to set a vector component with an index.
  783. *
  784. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  785. * @param {number} value - The value to set.
  786. * @return {Vector2} A reference to this vector.
  787. */
  788. setComponent( index, value ) {
  789. switch ( index ) {
  790. case 0: this.x = value; break;
  791. case 1: this.y = value; break;
  792. default: throw new Error( 'index is out of range: ' + index );
  793. }
  794. return this;
  795. }
  796. /**
  797. * Returns the value of the vector component which matches the given index.
  798. *
  799. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  800. * @return {number} A vector component value.
  801. */
  802. getComponent( index ) {
  803. switch ( index ) {
  804. case 0: return this.x;
  805. case 1: return this.y;
  806. default: throw new Error( 'index is out of range: ' + index );
  807. }
  808. }
  809. /**
  810. * Returns a new vector with copied values from this instance.
  811. *
  812. * @return {Vector2} A clone of this instance.
  813. */
  814. clone() {
  815. return new this.constructor( this.x, this.y );
  816. }
  817. /**
  818. * Copies the values of the given vector to this instance.
  819. *
  820. * @param {Vector2} v - The vector to copy.
  821. * @return {Vector2} A reference to this vector.
  822. */
  823. copy( v ) {
  824. this.x = v.x;
  825. this.y = v.y;
  826. return this;
  827. }
  828. /**
  829. * Adds the given vector to this instance.
  830. *
  831. * @param {Vector2} v - The vector to add.
  832. * @return {Vector2} A reference to this vector.
  833. */
  834. add( v ) {
  835. this.x += v.x;
  836. this.y += v.y;
  837. return this;
  838. }
  839. /**
  840. * Adds the given scalar value to all components of this instance.
  841. *
  842. * @param {number} s - The scalar to add.
  843. * @return {Vector2} A reference to this vector.
  844. */
  845. addScalar( s ) {
  846. this.x += s;
  847. this.y += s;
  848. return this;
  849. }
  850. /**
  851. * Adds the given vectors and stores the result in this instance.
  852. *
  853. * @param {Vector2} a - The first vector.
  854. * @param {Vector2} b - The second vector.
  855. * @return {Vector2} A reference to this vector.
  856. */
  857. addVectors( a, b ) {
  858. this.x = a.x + b.x;
  859. this.y = a.y + b.y;
  860. return this;
  861. }
  862. /**
  863. * Adds the given vector scaled by the given factor to this instance.
  864. *
  865. * @param {Vector2} v - The vector.
  866. * @param {number} s - The factor that scales `v`.
  867. * @return {Vector2} A reference to this vector.
  868. */
  869. addScaledVector( v, s ) {
  870. this.x += v.x * s;
  871. this.y += v.y * s;
  872. return this;
  873. }
  874. /**
  875. * Subtracts the given vector from this instance.
  876. *
  877. * @param {Vector2} v - The vector to subtract.
  878. * @return {Vector2} A reference to this vector.
  879. */
  880. sub( v ) {
  881. this.x -= v.x;
  882. this.y -= v.y;
  883. return this;
  884. }
  885. /**
  886. * Subtracts the given scalar value from all components of this instance.
  887. *
  888. * @param {number} s - The scalar to subtract.
  889. * @return {Vector2} A reference to this vector.
  890. */
  891. subScalar( s ) {
  892. this.x -= s;
  893. this.y -= s;
  894. return this;
  895. }
  896. /**
  897. * Subtracts the given vectors and stores the result in this instance.
  898. *
  899. * @param {Vector2} a - The first vector.
  900. * @param {Vector2} b - The second vector.
  901. * @return {Vector2} A reference to this vector.
  902. */
  903. subVectors( a, b ) {
  904. this.x = a.x - b.x;
  905. this.y = a.y - b.y;
  906. return this;
  907. }
  908. /**
  909. * Multiplies the given vector with this instance.
  910. *
  911. * @param {Vector2} v - The vector to multiply.
  912. * @return {Vector2} A reference to this vector.
  913. */
  914. multiply( v ) {
  915. this.x *= v.x;
  916. this.y *= v.y;
  917. return this;
  918. }
  919. /**
  920. * Multiplies the given scalar value with all components of this instance.
  921. *
  922. * @param {number} scalar - The scalar to multiply.
  923. * @return {Vector2} A reference to this vector.
  924. */
  925. multiplyScalar( scalar ) {
  926. this.x *= scalar;
  927. this.y *= scalar;
  928. return this;
  929. }
  930. /**
  931. * Divides this instance by the given vector.
  932. *
  933. * @param {Vector2} v - The vector to divide.
  934. * @return {Vector2} A reference to this vector.
  935. */
  936. divide( v ) {
  937. this.x /= v.x;
  938. this.y /= v.y;
  939. return this;
  940. }
  941. /**
  942. * Divides this vector by the given scalar.
  943. *
  944. * @param {number} scalar - The scalar to divide.
  945. * @return {Vector2} A reference to this vector.
  946. */
  947. divideScalar( scalar ) {
  948. return this.multiplyScalar( 1 / scalar );
  949. }
  950. /**
  951. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  952. * the given 3x3 matrix.
  953. *
  954. * @param {Matrix3} m - The matrix to apply.
  955. * @return {Vector2} A reference to this vector.
  956. */
  957. applyMatrix3( m ) {
  958. const x = this.x, y = this.y;
  959. const e = m.elements;
  960. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  961. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  962. return this;
  963. }
  964. /**
  965. * If this vector's x or y value is greater than the given vector's x or y
  966. * value, replace that value with the corresponding min value.
  967. *
  968. * @param {Vector2} v - The vector.
  969. * @return {Vector2} A reference to this vector.
  970. */
  971. min( v ) {
  972. this.x = Math.min( this.x, v.x );
  973. this.y = Math.min( this.y, v.y );
  974. return this;
  975. }
  976. /**
  977. * If this vector's x or y value is less than the given vector's x or y
  978. * value, replace that value with the corresponding max value.
  979. *
  980. * @param {Vector2} v - The vector.
  981. * @return {Vector2} A reference to this vector.
  982. */
  983. max( v ) {
  984. this.x = Math.max( this.x, v.x );
  985. this.y = Math.max( this.y, v.y );
  986. return this;
  987. }
  988. /**
  989. * If this vector's x or y value is greater than the max vector's x or y
  990. * value, it is replaced by the corresponding value.
  991. * If this vector's x or y value is less than the min vector's x or y value,
  992. * it is replaced by the corresponding value.
  993. *
  994. * @param {Vector2} min - The minimum x and y values.
  995. * @param {Vector2} max - The maximum x and y values in the desired range.
  996. * @return {Vector2} A reference to this vector.
  997. */
  998. clamp( min, max ) {
  999. // assumes min < max, componentwise
  1000. this.x = clamp( this.x, min.x, max.x );
  1001. this.y = clamp( this.y, min.y, max.y );
  1002. return this;
  1003. }
  1004. /**
  1005. * If this vector's x or y values are greater than the max value, they are
  1006. * replaced by the max value.
  1007. * If this vector's x or y values are less than the min value, they are
  1008. * replaced by the min value.
  1009. *
  1010. * @param {number} minVal - The minimum value the components will be clamped to.
  1011. * @param {number} maxVal - The maximum value the components will be clamped to.
  1012. * @return {Vector2} A reference to this vector.
  1013. */
  1014. clampScalar( minVal, maxVal ) {
  1015. this.x = clamp( this.x, minVal, maxVal );
  1016. this.y = clamp( this.y, minVal, maxVal );
  1017. return this;
  1018. }
  1019. /**
  1020. * If this vector's length is greater than the max value, it is replaced by
  1021. * the max value.
  1022. * If this vector's length is less than the min value, it is replaced by the
  1023. * min value.
  1024. *
  1025. * @param {number} min - The minimum value the vector length will be clamped to.
  1026. * @param {number} max - The maximum value the vector length will be clamped to.
  1027. * @return {Vector2} A reference to this vector.
  1028. */
  1029. clampLength( min, max ) {
  1030. const length = this.length();
  1031. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  1032. }
  1033. /**
  1034. * The components of this vector are rounded down to the nearest integer value.
  1035. *
  1036. * @return {Vector2} A reference to this vector.
  1037. */
  1038. floor() {
  1039. this.x = Math.floor( this.x );
  1040. this.y = Math.floor( this.y );
  1041. return this;
  1042. }
  1043. /**
  1044. * The components of this vector are rounded up to the nearest integer value.
  1045. *
  1046. * @return {Vector2} A reference to this vector.
  1047. */
  1048. ceil() {
  1049. this.x = Math.ceil( this.x );
  1050. this.y = Math.ceil( this.y );
  1051. return this;
  1052. }
  1053. /**
  1054. * The components of this vector are rounded to the nearest integer value
  1055. *
  1056. * @return {Vector2} A reference to this vector.
  1057. */
  1058. round() {
  1059. this.x = Math.round( this.x );
  1060. this.y = Math.round( this.y );
  1061. return this;
  1062. }
  1063. /**
  1064. * The components of this vector are rounded towards zero (up if negative,
  1065. * down if positive) to an integer value.
  1066. *
  1067. * @return {Vector2} A reference to this vector.
  1068. */
  1069. roundToZero() {
  1070. this.x = Math.trunc( this.x );
  1071. this.y = Math.trunc( this.y );
  1072. return this;
  1073. }
  1074. /**
  1075. * Inverts this vector - i.e. sets x = -x and y = -y.
  1076. *
  1077. * @return {Vector2} A reference to this vector.
  1078. */
  1079. negate() {
  1080. this.x = - this.x;
  1081. this.y = - this.y;
  1082. return this;
  1083. }
  1084. /**
  1085. * Calculates the dot product of the given vector with this instance.
  1086. *
  1087. * @param {Vector2} v - The vector to compute the dot product with.
  1088. * @return {number} The result of the dot product.
  1089. */
  1090. dot( v ) {
  1091. return this.x * v.x + this.y * v.y;
  1092. }
  1093. /**
  1094. * Calculates the cross product of the given vector with this instance.
  1095. *
  1096. * @param {Vector2} v - The vector to compute the cross product with.
  1097. * @return {number} The result of the cross product.
  1098. */
  1099. cross( v ) {
  1100. return this.x * v.y - this.y * v.x;
  1101. }
  1102. /**
  1103. * Computes the square of the Euclidean length (straight-line length) from
  1104. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  1105. * compare the length squared instead as it is slightly more efficient to calculate.
  1106. *
  1107. * @return {number} The square length of this vector.
  1108. */
  1109. lengthSq() {
  1110. return this.x * this.x + this.y * this.y;
  1111. }
  1112. /**
  1113. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  1114. *
  1115. * @return {number} The length of this vector.
  1116. */
  1117. length() {
  1118. return Math.sqrt( this.x * this.x + this.y * this.y );
  1119. }
  1120. /**
  1121. * Computes the Manhattan length of this vector.
  1122. *
  1123. * @return {number} The length of this vector.
  1124. */
  1125. manhattanLength() {
  1126. return Math.abs( this.x ) + Math.abs( this.y );
  1127. }
  1128. /**
  1129. * Converts this vector to a unit vector - that is, sets it equal to a vector
  1130. * with the same direction as this one, but with a vector length of `1`.
  1131. *
  1132. * @return {Vector2} A reference to this vector.
  1133. */
  1134. normalize() {
  1135. return this.divideScalar( this.length() || 1 );
  1136. }
  1137. /**
  1138. * Computes the angle in radians of this vector with respect to the positive x-axis.
  1139. *
  1140. * @return {number} The angle in radians.
  1141. */
  1142. angle() {
  1143. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  1144. return angle;
  1145. }
  1146. /**
  1147. * Returns the angle between the given vector and this instance in radians.
  1148. *
  1149. * @param {Vector2} v - The vector to compute the angle with.
  1150. * @return {number} The angle in radians.
  1151. */
  1152. angleTo( v ) {
  1153. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  1154. if ( denominator === 0 ) return Math.PI / 2;
  1155. const theta = this.dot( v ) / denominator;
  1156. // clamp, to handle numerical problems
  1157. return Math.acos( clamp( theta, -1, 1 ) );
  1158. }
  1159. /**
  1160. * Computes the distance from the given vector to this instance.
  1161. *
  1162. * @param {Vector2} v - The vector to compute the distance to.
  1163. * @return {number} The distance.
  1164. */
  1165. distanceTo( v ) {
  1166. return Math.sqrt( this.distanceToSquared( v ) );
  1167. }
  1168. /**
  1169. * Computes the squared distance from the given vector to this instance.
  1170. * If you are just comparing the distance with another distance, you should compare
  1171. * the distance squared instead as it is slightly more efficient to calculate.
  1172. *
  1173. * @param {Vector2} v - The vector to compute the squared distance to.
  1174. * @return {number} The squared distance.
  1175. */
  1176. distanceToSquared( v ) {
  1177. const dx = this.x - v.x, dy = this.y - v.y;
  1178. return dx * dx + dy * dy;
  1179. }
  1180. /**
  1181. * Computes the Manhattan distance from the given vector to this instance.
  1182. *
  1183. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  1184. * @return {number} The Manhattan distance.
  1185. */
  1186. manhattanDistanceTo( v ) {
  1187. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  1188. }
  1189. /**
  1190. * Sets this vector to a vector with the same direction as this one, but
  1191. * with the specified length.
  1192. *
  1193. * @param {number} length - The new length of this vector.
  1194. * @return {Vector2} A reference to this vector.
  1195. */
  1196. setLength( length ) {
  1197. return this.normalize().multiplyScalar( length );
  1198. }
  1199. /**
  1200. * Linearly interpolates between the given vector and this instance, where
  1201. * alpha is the percent distance along the line - alpha = 0 will be this
  1202. * vector, and alpha = 1 will be the given one.
  1203. *
  1204. * @param {Vector2} v - The vector to interpolate towards.
  1205. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  1206. * @return {Vector2} A reference to this vector.
  1207. */
  1208. lerp( v, alpha ) {
  1209. this.x += ( v.x - this.x ) * alpha;
  1210. this.y += ( v.y - this.y ) * alpha;
  1211. return this;
  1212. }
  1213. /**
  1214. * Linearly interpolates between the given vectors, where alpha is the percent
  1215. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  1216. * be the second one. The result is stored in this instance.
  1217. *
  1218. * @param {Vector2} v1 - The first vector.
  1219. * @param {Vector2} v2 - The second vector.
  1220. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  1221. * @return {Vector2} A reference to this vector.
  1222. */
  1223. lerpVectors( v1, v2, alpha ) {
  1224. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1225. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1226. return this;
  1227. }
  1228. /**
  1229. * Returns `true` if this vector is equal with the given one.
  1230. *
  1231. * @param {Vector2} v - The vector to test for equality.
  1232. * @return {boolean} Whether this vector is equal with the given one.
  1233. */
  1234. equals( v ) {
  1235. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1236. }
  1237. /**
  1238. * Sets this vector's x value to be `array[ offset ]` and y
  1239. * value to be `array[ offset + 1 ]`.
  1240. *
  1241. * @param {Array<number>} array - An array holding the vector component values.
  1242. * @param {number} [offset=0] - The offset into the array.
  1243. * @return {Vector2} A reference to this vector.
  1244. */
  1245. fromArray( array, offset = 0 ) {
  1246. this.x = array[ offset ];
  1247. this.y = array[ offset + 1 ];
  1248. return this;
  1249. }
  1250. /**
  1251. * Writes the components of this vector to the given array. If no array is provided,
  1252. * the method returns a new instance.
  1253. *
  1254. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  1255. * @param {number} [offset=0] - Index of the first element in the array.
  1256. * @return {Array<number>} The vector components.
  1257. */
  1258. toArray( array = [], offset = 0 ) {
  1259. array[ offset ] = this.x;
  1260. array[ offset + 1 ] = this.y;
  1261. return array;
  1262. }
  1263. /**
  1264. * Sets the components of this vector from the given buffer attribute.
  1265. *
  1266. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  1267. * @param {number} index - The index into the attribute.
  1268. * @return {Vector2} A reference to this vector.
  1269. */
  1270. fromBufferAttribute( attribute, index ) {
  1271. this.x = attribute.getX( index );
  1272. this.y = attribute.getY( index );
  1273. return this;
  1274. }
  1275. /**
  1276. * Rotates this vector around the given center by the given angle.
  1277. *
  1278. * @param {Vector2} center - The point around which to rotate.
  1279. * @param {number} angle - The angle to rotate, in radians.
  1280. * @return {Vector2} A reference to this vector.
  1281. */
  1282. rotateAround( center, angle ) {
  1283. const c = Math.cos( angle ), s = Math.sin( angle );
  1284. const x = this.x - center.x;
  1285. const y = this.y - center.y;
  1286. this.x = x * c - y * s + center.x;
  1287. this.y = x * s + y * c + center.y;
  1288. return this;
  1289. }
  1290. /**
  1291. * Sets each component of this vector to a pseudo-random value between `0` and
  1292. * `1`, excluding `1`.
  1293. *
  1294. * @return {Vector2} A reference to this vector.
  1295. */
  1296. random() {
  1297. this.x = Math.random();
  1298. this.y = Math.random();
  1299. return this;
  1300. }
  1301. *[ Symbol.iterator ]() {
  1302. yield this.x;
  1303. yield this.y;
  1304. }
  1305. }
  1306. /**
  1307. * Represents a 3x3 matrix.
  1308. *
  1309. * A Note on Row-Major and Column-Major Ordering:
  1310. *
  1311. * The constructor and {@link Matrix3#set} method take arguments in
  1312. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  1313. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  1314. * This means that calling:
  1315. * ```js
  1316. * const m = new THREE.Matrix();
  1317. * m.set( 11, 12, 13,
  1318. * 21, 22, 23,
  1319. * 31, 32, 33 );
  1320. * ```
  1321. * will result in the elements array containing:
  1322. * ```js
  1323. * m.elements = [ 11, 21, 31,
  1324. * 12, 22, 32,
  1325. * 13, 23, 33 ];
  1326. * ```
  1327. * and internally all calculations are performed using column-major ordering.
  1328. * However, as the actual ordering makes no difference mathematically and
  1329. * most people are used to thinking about matrices in row-major order, the
  1330. * three.js documentation shows matrices in row-major order. Just bear in
  1331. * mind that if you are reading the source code, you'll have to take the
  1332. * transpose of any matrices outlined here to make sense of the calculations.
  1333. */
  1334. class Matrix3 {
  1335. /**
  1336. * Constructs a new 3x3 matrix. The arguments are supposed to be
  1337. * in row-major order. If no arguments are provided, the constructor
  1338. * initializes the matrix as an identity matrix.
  1339. *
  1340. * @param {number} [n11] - 1-1 matrix element.
  1341. * @param {number} [n12] - 1-2 matrix element.
  1342. * @param {number} [n13] - 1-3 matrix element.
  1343. * @param {number} [n21] - 2-1 matrix element.
  1344. * @param {number} [n22] - 2-2 matrix element.
  1345. * @param {number} [n23] - 2-3 matrix element.
  1346. * @param {number} [n31] - 3-1 matrix element.
  1347. * @param {number} [n32] - 3-2 matrix element.
  1348. * @param {number} [n33] - 3-3 matrix element.
  1349. */
  1350. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1351. /**
  1352. * This flag can be used for type testing.
  1353. *
  1354. * @type {boolean}
  1355. * @readonly
  1356. * @default true
  1357. */
  1358. Matrix3.prototype.isMatrix3 = true;
  1359. /**
  1360. * A column-major list of matrix values.
  1361. *
  1362. * @type {Array<number>}
  1363. */
  1364. this.elements = [
  1365. 1, 0, 0,
  1366. 0, 1, 0,
  1367. 0, 0, 1
  1368. ];
  1369. if ( n11 !== undefined ) {
  1370. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  1371. }
  1372. }
  1373. /**
  1374. * Sets the elements of the matrix.The arguments are supposed to be
  1375. * in row-major order.
  1376. *
  1377. * @param {number} [n11] - 1-1 matrix element.
  1378. * @param {number} [n12] - 1-2 matrix element.
  1379. * @param {number} [n13] - 1-3 matrix element.
  1380. * @param {number} [n21] - 2-1 matrix element.
  1381. * @param {number} [n22] - 2-2 matrix element.
  1382. * @param {number} [n23] - 2-3 matrix element.
  1383. * @param {number} [n31] - 3-1 matrix element.
  1384. * @param {number} [n32] - 3-2 matrix element.
  1385. * @param {number} [n33] - 3-3 matrix element.
  1386. * @return {Matrix3} A reference to this matrix.
  1387. */
  1388. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1389. const te = this.elements;
  1390. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  1391. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  1392. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  1393. return this;
  1394. }
  1395. /**
  1396. * Sets this matrix to the 3x3 identity matrix.
  1397. *
  1398. * @return {Matrix3} A reference to this matrix.
  1399. */
  1400. identity() {
  1401. this.set(
  1402. 1, 0, 0,
  1403. 0, 1, 0,
  1404. 0, 0, 1
  1405. );
  1406. return this;
  1407. }
  1408. /**
  1409. * Copies the values of the given matrix to this instance.
  1410. *
  1411. * @param {Matrix3} m - The matrix to copy.
  1412. * @return {Matrix3} A reference to this matrix.
  1413. */
  1414. copy( m ) {
  1415. const te = this.elements;
  1416. const me = m.elements;
  1417. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  1418. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  1419. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  1420. return this;
  1421. }
  1422. /**
  1423. * Extracts the basis of this matrix into the three axis vectors provided.
  1424. *
  1425. * @param {Vector3} xAxis - The basis's x axis.
  1426. * @param {Vector3} yAxis - The basis's y axis.
  1427. * @param {Vector3} zAxis - The basis's z axis.
  1428. * @return {Matrix3} A reference to this matrix.
  1429. */
  1430. extractBasis( xAxis, yAxis, zAxis ) {
  1431. xAxis.setFromMatrix3Column( this, 0 );
  1432. yAxis.setFromMatrix3Column( this, 1 );
  1433. zAxis.setFromMatrix3Column( this, 2 );
  1434. return this;
  1435. }
  1436. /**
  1437. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  1438. *
  1439. * @param {Matrix4} m - The 4x4 matrix.
  1440. * @return {Matrix3} A reference to this matrix.
  1441. */
  1442. setFromMatrix4( m ) {
  1443. const me = m.elements;
  1444. this.set(
  1445. me[ 0 ], me[ 4 ], me[ 8 ],
  1446. me[ 1 ], me[ 5 ], me[ 9 ],
  1447. me[ 2 ], me[ 6 ], me[ 10 ]
  1448. );
  1449. return this;
  1450. }
  1451. /**
  1452. * Post-multiplies this matrix by the given 3x3 matrix.
  1453. *
  1454. * @param {Matrix3} m - The matrix to multiply with.
  1455. * @return {Matrix3} A reference to this matrix.
  1456. */
  1457. multiply( m ) {
  1458. return this.multiplyMatrices( this, m );
  1459. }
  1460. /**
  1461. * Pre-multiplies this matrix by the given 3x3 matrix.
  1462. *
  1463. * @param {Matrix3} m - The matrix to multiply with.
  1464. * @return {Matrix3} A reference to this matrix.
  1465. */
  1466. premultiply( m ) {
  1467. return this.multiplyMatrices( m, this );
  1468. }
  1469. /**
  1470. * Multiples the given 3x3 matrices and stores the result
  1471. * in this matrix.
  1472. *
  1473. * @param {Matrix3} a - The first matrix.
  1474. * @param {Matrix3} b - The second matrix.
  1475. * @return {Matrix3} A reference to this matrix.
  1476. */
  1477. multiplyMatrices( a, b ) {
  1478. const ae = a.elements;
  1479. const be = b.elements;
  1480. const te = this.elements;
  1481. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  1482. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  1483. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  1484. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  1485. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  1486. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  1487. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  1488. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  1489. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  1490. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  1491. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  1492. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  1493. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  1494. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  1495. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  1496. return this;
  1497. }
  1498. /**
  1499. * Multiplies every component of the matrix by the given scalar.
  1500. *
  1501. * @param {number} s - The scalar.
  1502. * @return {Matrix3} A reference to this matrix.
  1503. */
  1504. multiplyScalar( s ) {
  1505. const te = this.elements;
  1506. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  1507. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  1508. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  1509. return this;
  1510. }
  1511. /**
  1512. * Computes and returns the determinant of this matrix.
  1513. *
  1514. * @return {number} The determinant.
  1515. */
  1516. determinant() {
  1517. const te = this.elements;
  1518. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  1519. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  1520. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  1521. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1522. }
  1523. /**
  1524. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  1525. * You can not invert with a determinant of zero. If you attempt this, the method produces
  1526. * a zero matrix instead.
  1527. *
  1528. * @return {Matrix3} A reference to this matrix.
  1529. */
  1530. invert() {
  1531. const te = this.elements,
  1532. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  1533. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  1534. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  1535. t11 = n33 * n22 - n32 * n23,
  1536. t12 = n32 * n13 - n33 * n12,
  1537. t13 = n23 * n12 - n22 * n13,
  1538. det = n11 * t11 + n21 * t12 + n31 * t13;
  1539. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  1540. const detInv = 1 / det;
  1541. te[ 0 ] = t11 * detInv;
  1542. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  1543. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  1544. te[ 3 ] = t12 * detInv;
  1545. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  1546. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  1547. te[ 6 ] = t13 * detInv;
  1548. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  1549. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  1550. return this;
  1551. }
  1552. /**
  1553. * Transposes this matrix in place.
  1554. *
  1555. * @return {Matrix3} A reference to this matrix.
  1556. */
  1557. transpose() {
  1558. let tmp;
  1559. const m = this.elements;
  1560. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  1561. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  1562. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  1563. return this;
  1564. }
  1565. /**
  1566. * Computes the normal matrix which is the inverse transpose of the upper
  1567. * left 3x3 portion of the given 4x4 matrix.
  1568. *
  1569. * @param {Matrix4} matrix4 - The 4x4 matrix.
  1570. * @return {Matrix3} A reference to this matrix.
  1571. */
  1572. getNormalMatrix( matrix4 ) {
  1573. return this.setFromMatrix4( matrix4 ).invert().transpose();
  1574. }
  1575. /**
  1576. * Transposes this matrix into the supplied array, and returns itself unchanged.
  1577. *
  1578. * @param {Array<number>} r - An array to store the transposed matrix elements.
  1579. * @return {Matrix3} A reference to this matrix.
  1580. */
  1581. transposeIntoArray( r ) {
  1582. const m = this.elements;
  1583. r[ 0 ] = m[ 0 ];
  1584. r[ 1 ] = m[ 3 ];
  1585. r[ 2 ] = m[ 6 ];
  1586. r[ 3 ] = m[ 1 ];
  1587. r[ 4 ] = m[ 4 ];
  1588. r[ 5 ] = m[ 7 ];
  1589. r[ 6 ] = m[ 2 ];
  1590. r[ 7 ] = m[ 5 ];
  1591. r[ 8 ] = m[ 8 ];
  1592. return this;
  1593. }
  1594. /**
  1595. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  1596. *
  1597. * @param {number} tx - Offset x.
  1598. * @param {number} ty - Offset y.
  1599. * @param {number} sx - Repeat x.
  1600. * @param {number} sy - Repeat y.
  1601. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  1602. * @param {number} cx - Center x of rotation.
  1603. * @param {number} cy - Center y of rotation
  1604. * @return {Matrix3} A reference to this matrix.
  1605. */
  1606. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  1607. const c = Math.cos( rotation );
  1608. const s = Math.sin( rotation );
  1609. this.set(
  1610. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  1611. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  1612. 0, 0, 1
  1613. );
  1614. return this;
  1615. }
  1616. /**
  1617. * Scales this matrix with the given scalar values.
  1618. *
  1619. * @param {number} sx - The amount to scale in the X axis.
  1620. * @param {number} sy - The amount to scale in the Y axis.
  1621. * @return {Matrix3} A reference to this matrix.
  1622. */
  1623. scale( sx, sy ) {
  1624. this.premultiply( _m3.makeScale( sx, sy ) );
  1625. return this;
  1626. }
  1627. /**
  1628. * Rotates this matrix by the given angle.
  1629. *
  1630. * @param {number} theta - The rotation in radians.
  1631. * @return {Matrix3} A reference to this matrix.
  1632. */
  1633. rotate( theta ) {
  1634. this.premultiply( _m3.makeRotation( - theta ) );
  1635. return this;
  1636. }
  1637. /**
  1638. * Translates this matrix by the given scalar values.
  1639. *
  1640. * @param {number} tx - The amount to translate in the X axis.
  1641. * @param {number} ty - The amount to translate in the Y axis.
  1642. * @return {Matrix3} A reference to this matrix.
  1643. */
  1644. translate( tx, ty ) {
  1645. this.premultiply( _m3.makeTranslation( tx, ty ) );
  1646. return this;
  1647. }
  1648. // for 2D Transforms
  1649. /**
  1650. * Sets this matrix as a 2D translation transform.
  1651. *
  1652. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  1653. * @param {number} y - The amount to translate in the Y axis.
  1654. * @return {Matrix3} A reference to this matrix.
  1655. */
  1656. makeTranslation( x, y ) {
  1657. if ( x.isVector2 ) {
  1658. this.set(
  1659. 1, 0, x.x,
  1660. 0, 1, x.y,
  1661. 0, 0, 1
  1662. );
  1663. } else {
  1664. this.set(
  1665. 1, 0, x,
  1666. 0, 1, y,
  1667. 0, 0, 1
  1668. );
  1669. }
  1670. return this;
  1671. }
  1672. /**
  1673. * Sets this matrix as a 2D rotational transformation.
  1674. *
  1675. * @param {number} theta - The rotation in radians.
  1676. * @return {Matrix3} A reference to this matrix.
  1677. */
  1678. makeRotation( theta ) {
  1679. // counterclockwise
  1680. const c = Math.cos( theta );
  1681. const s = Math.sin( theta );
  1682. this.set(
  1683. c, - s, 0,
  1684. s, c, 0,
  1685. 0, 0, 1
  1686. );
  1687. return this;
  1688. }
  1689. /**
  1690. * Sets this matrix as a 2D scale transform.
  1691. *
  1692. * @param {number} x - The amount to scale in the X axis.
  1693. * @param {number} y - The amount to scale in the Y axis.
  1694. * @return {Matrix3} A reference to this matrix.
  1695. */
  1696. makeScale( x, y ) {
  1697. this.set(
  1698. x, 0, 0,
  1699. 0, y, 0,
  1700. 0, 0, 1
  1701. );
  1702. return this;
  1703. }
  1704. /**
  1705. * Returns `true` if this matrix is equal with the given one.
  1706. *
  1707. * @param {Matrix3} matrix - The matrix to test for equality.
  1708. * @return {boolean} Whether this matrix is equal with the given one.
  1709. */
  1710. equals( matrix ) {
  1711. const te = this.elements;
  1712. const me = matrix.elements;
  1713. for ( let i = 0; i < 9; i ++ ) {
  1714. if ( te[ i ] !== me[ i ] ) return false;
  1715. }
  1716. return true;
  1717. }
  1718. /**
  1719. * Sets the elements of the matrix from the given array.
  1720. *
  1721. * @param {Array<number>} array - The matrix elements in column-major order.
  1722. * @param {number} [offset=0] - Index of the first element in the array.
  1723. * @return {Matrix3} A reference to this matrix.
  1724. */
  1725. fromArray( array, offset = 0 ) {
  1726. for ( let i = 0; i < 9; i ++ ) {
  1727. this.elements[ i ] = array[ i + offset ];
  1728. }
  1729. return this;
  1730. }
  1731. /**
  1732. * Writes the elements of this matrix to the given array. If no array is provided,
  1733. * the method returns a new instance.
  1734. *
  1735. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  1736. * @param {number} [offset=0] - Index of the first element in the array.
  1737. * @return {Array<number>} The matrix elements in column-major order.
  1738. */
  1739. toArray( array = [], offset = 0 ) {
  1740. const te = this.elements;
  1741. array[ offset ] = te[ 0 ];
  1742. array[ offset + 1 ] = te[ 1 ];
  1743. array[ offset + 2 ] = te[ 2 ];
  1744. array[ offset + 3 ] = te[ 3 ];
  1745. array[ offset + 4 ] = te[ 4 ];
  1746. array[ offset + 5 ] = te[ 5 ];
  1747. array[ offset + 6 ] = te[ 6 ];
  1748. array[ offset + 7 ] = te[ 7 ];
  1749. array[ offset + 8 ] = te[ 8 ];
  1750. return array;
  1751. }
  1752. /**
  1753. * Returns a matrix with copied values from this instance.
  1754. *
  1755. * @return {Matrix3} A clone of this instance.
  1756. */
  1757. clone() {
  1758. return new this.constructor().fromArray( this.elements );
  1759. }
  1760. }
  1761. const _m3 = /*@__PURE__*/ new Matrix3();
  1762. function arrayNeedsUint32( array ) {
  1763. // assumes larger values usually on last
  1764. for ( let i = array.length - 1; i >= 0; -- i ) {
  1765. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1766. }
  1767. return false;
  1768. }
  1769. const TYPED_ARRAYS = {
  1770. Int8Array: Int8Array,
  1771. Uint8Array: Uint8Array,
  1772. Uint8ClampedArray: Uint8ClampedArray,
  1773. Int16Array: Int16Array,
  1774. Uint16Array: Uint16Array,
  1775. Int32Array: Int32Array,
  1776. Uint32Array: Uint32Array,
  1777. Float32Array: Float32Array,
  1778. Float64Array: Float64Array
  1779. };
  1780. function getTypedArray( type, buffer ) {
  1781. return new TYPED_ARRAYS[ type ]( buffer );
  1782. }
  1783. function createElementNS( name ) {
  1784. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1785. }
  1786. function createCanvasElement() {
  1787. const canvas = createElementNS( 'canvas' );
  1788. canvas.style.display = 'block';
  1789. return canvas;
  1790. }
  1791. const _cache = {};
  1792. function warnOnce( message ) {
  1793. if ( message in _cache ) return;
  1794. _cache[ message ] = true;
  1795. console.warn( message );
  1796. }
  1797. function probeAsync( gl, sync, interval ) {
  1798. return new Promise( function ( resolve, reject ) {
  1799. function probe() {
  1800. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1801. case gl.WAIT_FAILED:
  1802. reject();
  1803. break;
  1804. case gl.TIMEOUT_EXPIRED:
  1805. setTimeout( probe, interval );
  1806. break;
  1807. default:
  1808. resolve();
  1809. }
  1810. }
  1811. setTimeout( probe, interval );
  1812. } );
  1813. }
  1814. function toNormalizedProjectionMatrix( projectionMatrix ) {
  1815. const m = projectionMatrix.elements;
  1816. // Convert [-1, 1] to [0, 1] projection matrix
  1817. m[ 2 ] = 0.5 * m[ 2 ] + 0.5 * m[ 3 ];
  1818. m[ 6 ] = 0.5 * m[ 6 ] + 0.5 * m[ 7 ];
  1819. m[ 10 ] = 0.5 * m[ 10 ] + 0.5 * m[ 11 ];
  1820. m[ 14 ] = 0.5 * m[ 14 ] + 0.5 * m[ 15 ];
  1821. }
  1822. function toReversedProjectionMatrix( projectionMatrix ) {
  1823. const m = projectionMatrix.elements;
  1824. const isPerspectiveMatrix = m[ 11 ] === -1;
  1825. // Reverse [0, 1] projection matrix
  1826. if ( isPerspectiveMatrix ) {
  1827. m[ 10 ] = - m[ 10 ] - 1;
  1828. m[ 14 ] = - m[ 14 ];
  1829. } else {
  1830. m[ 10 ] = - m[ 10 ];
  1831. m[ 14 ] = - m[ 14 ] + 1;
  1832. }
  1833. }
  1834. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  1835. 0.4123908, 0.3575843, 0.1804808,
  1836. 0.2126390, 0.7151687, 0.0721923,
  1837. 0.0193308, 0.1191948, 0.9505322
  1838. );
  1839. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  1840. 3.2409699, -1.5373832, -0.4986108,
  1841. -0.9692436, 1.8759675, 0.0415551,
  1842. 0.0556301, -0.203977, 1.0569715
  1843. );
  1844. function createColorManagement() {
  1845. const ColorManagement = {
  1846. enabled: true,
  1847. workingColorSpace: LinearSRGBColorSpace,
  1848. /**
  1849. * Implementations of supported color spaces.
  1850. *
  1851. * Required:
  1852. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  1853. * - whitePoint: reference white [ x y ]
  1854. * - transfer: transfer function (pre-defined)
  1855. * - toXYZ: Matrix3 RGB to XYZ transform
  1856. * - fromXYZ: Matrix3 XYZ to RGB transform
  1857. * - luminanceCoefficients: RGB luminance coefficients
  1858. *
  1859. * Optional:
  1860. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  1861. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  1862. *
  1863. * Reference:
  1864. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  1865. */
  1866. spaces: {},
  1867. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1868. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1869. return color;
  1870. }
  1871. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  1872. color.r = SRGBToLinear( color.r );
  1873. color.g = SRGBToLinear( color.g );
  1874. color.b = SRGBToLinear( color.b );
  1875. }
  1876. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  1877. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  1878. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  1879. }
  1880. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  1881. color.r = LinearToSRGB( color.r );
  1882. color.g = LinearToSRGB( color.g );
  1883. color.b = LinearToSRGB( color.b );
  1884. }
  1885. return color;
  1886. },
  1887. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1888. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1889. },
  1890. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1891. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1892. },
  1893. getPrimaries: function ( colorSpace ) {
  1894. return this.spaces[ colorSpace ].primaries;
  1895. },
  1896. getTransfer: function ( colorSpace ) {
  1897. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1898. return this.spaces[ colorSpace ].transfer;
  1899. },
  1900. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  1901. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  1902. },
  1903. define: function ( colorSpaces ) {
  1904. Object.assign( this.spaces, colorSpaces );
  1905. },
  1906. // Internal APIs
  1907. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  1908. return targetMatrix
  1909. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  1910. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  1911. },
  1912. _getDrawingBufferColorSpace: function ( colorSpace ) {
  1913. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  1914. },
  1915. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  1916. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  1917. }
  1918. };
  1919. /******************************************************************************
  1920. * sRGB definitions
  1921. */
  1922. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  1923. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  1924. const D65 = [ 0.3127, 0.3290 ];
  1925. ColorManagement.define( {
  1926. [ LinearSRGBColorSpace ]: {
  1927. primaries: REC709_PRIMARIES,
  1928. whitePoint: D65,
  1929. transfer: LinearTransfer,
  1930. toXYZ: LINEAR_REC709_TO_XYZ,
  1931. fromXYZ: XYZ_TO_LINEAR_REC709,
  1932. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1933. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  1934. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1935. },
  1936. [ SRGBColorSpace ]: {
  1937. primaries: REC709_PRIMARIES,
  1938. whitePoint: D65,
  1939. transfer: SRGBTransfer,
  1940. toXYZ: LINEAR_REC709_TO_XYZ,
  1941. fromXYZ: XYZ_TO_LINEAR_REC709,
  1942. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1943. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1944. },
  1945. } );
  1946. return ColorManagement;
  1947. }
  1948. const ColorManagement = /*@__PURE__*/ createColorManagement();
  1949. function SRGBToLinear( c ) {
  1950. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1951. }
  1952. function LinearToSRGB( c ) {
  1953. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1954. }
  1955. let _canvas;
  1956. /**
  1957. * A class containing utility functions for images.
  1958. *
  1959. * @hideconstructor
  1960. */
  1961. class ImageUtils {
  1962. /**
  1963. * Returns a data URI containing a representation of the given image.
  1964. *
  1965. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  1966. * @return {string} The data URI.
  1967. */
  1968. static getDataURL( image ) {
  1969. if ( /^data:/i.test( image.src ) ) {
  1970. return image.src;
  1971. }
  1972. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1973. return image.src;
  1974. }
  1975. let canvas;
  1976. if ( image instanceof HTMLCanvasElement ) {
  1977. canvas = image;
  1978. } else {
  1979. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1980. _canvas.width = image.width;
  1981. _canvas.height = image.height;
  1982. const context = _canvas.getContext( '2d' );
  1983. if ( image instanceof ImageData ) {
  1984. context.putImageData( image, 0, 0 );
  1985. } else {
  1986. context.drawImage( image, 0, 0, image.width, image.height );
  1987. }
  1988. canvas = _canvas;
  1989. }
  1990. return canvas.toDataURL( 'image/png' );
  1991. }
  1992. /**
  1993. * Converts the given sRGB image data to linear color space.
  1994. *
  1995. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  1996. * @return {HTMLCanvasElement|Object} The converted image.
  1997. */
  1998. static sRGBToLinear( image ) {
  1999. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  2000. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  2001. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  2002. const canvas = createElementNS( 'canvas' );
  2003. canvas.width = image.width;
  2004. canvas.height = image.height;
  2005. const context = canvas.getContext( '2d' );
  2006. context.drawImage( image, 0, 0, image.width, image.height );
  2007. const imageData = context.getImageData( 0, 0, image.width, image.height );
  2008. const data = imageData.data;
  2009. for ( let i = 0; i < data.length; i ++ ) {
  2010. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  2011. }
  2012. context.putImageData( imageData, 0, 0 );
  2013. return canvas;
  2014. } else if ( image.data ) {
  2015. const data = image.data.slice( 0 );
  2016. for ( let i = 0; i < data.length; i ++ ) {
  2017. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  2018. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  2019. } else {
  2020. // assuming float
  2021. data[ i ] = SRGBToLinear( data[ i ] );
  2022. }
  2023. }
  2024. return {
  2025. data: data,
  2026. width: image.width,
  2027. height: image.height
  2028. };
  2029. } else {
  2030. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  2031. return image;
  2032. }
  2033. }
  2034. }
  2035. let _sourceId = 0;
  2036. class Source {
  2037. constructor( data = null ) {
  2038. this.isSource = true;
  2039. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  2040. this.uuid = generateUUID();
  2041. this.data = data;
  2042. this.dataReady = true;
  2043. this.version = 0;
  2044. }
  2045. set needsUpdate( value ) {
  2046. if ( value === true ) this.version ++;
  2047. }
  2048. toJSON( meta ) {
  2049. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2050. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  2051. return meta.images[ this.uuid ];
  2052. }
  2053. const output = {
  2054. uuid: this.uuid,
  2055. url: ''
  2056. };
  2057. const data = this.data;
  2058. if ( data !== null ) {
  2059. let url;
  2060. if ( Array.isArray( data ) ) {
  2061. // cube texture
  2062. url = [];
  2063. for ( let i = 0, l = data.length; i < l; i ++ ) {
  2064. if ( data[ i ].isDataTexture ) {
  2065. url.push( serializeImage( data[ i ].image ) );
  2066. } else {
  2067. url.push( serializeImage( data[ i ] ) );
  2068. }
  2069. }
  2070. } else {
  2071. // texture
  2072. url = serializeImage( data );
  2073. }
  2074. output.url = url;
  2075. }
  2076. if ( ! isRootObject ) {
  2077. meta.images[ this.uuid ] = output;
  2078. }
  2079. return output;
  2080. }
  2081. }
  2082. function serializeImage( image ) {
  2083. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  2084. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  2085. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  2086. // default images
  2087. return ImageUtils.getDataURL( image );
  2088. } else {
  2089. if ( image.data ) {
  2090. // images of DataTexture
  2091. return {
  2092. data: Array.from( image.data ),
  2093. width: image.width,
  2094. height: image.height,
  2095. type: image.data.constructor.name
  2096. };
  2097. } else {
  2098. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  2099. return {};
  2100. }
  2101. }
  2102. }
  2103. let _textureId = 0;
  2104. /**
  2105. * Base class for all textures.
  2106. *
  2107. * Note: After the initial use of a texture, its dimensions, format, and type
  2108. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  2109. *
  2110. * @augments EventDispatcher
  2111. */
  2112. class Texture extends EventDispatcher {
  2113. /**
  2114. * Constructs a new texture.
  2115. *
  2116. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  2117. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  2118. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  2119. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  2120. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  2121. * @param {number} [minFilter=LinearFilter] - The min filter value.
  2122. * @param {number} [format=RGBAFormat] - The min filter value.
  2123. * @param {number} [type=UnsignedByteType] - The min filter value.
  2124. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The min filter value.
  2125. * @param {string} [colorSpace=NoColorSpace] - The min filter value.
  2126. */
  2127. 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 ) {
  2128. super();
  2129. /**
  2130. * This flag can be used for type testing.
  2131. *
  2132. * @type {boolean}
  2133. * @readonly
  2134. * @default true
  2135. */
  2136. this.isTexture = true;
  2137. /**
  2138. * The ID of the texture.
  2139. *
  2140. * @name Texture#id
  2141. * @type {number}
  2142. * @readonly
  2143. */
  2144. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  2145. /**
  2146. * The UUID of the material.
  2147. *
  2148. * @type {string}
  2149. * @readonly
  2150. */
  2151. this.uuid = generateUUID();
  2152. /**
  2153. * The name of the material.
  2154. *
  2155. * @type {string}
  2156. */
  2157. this.name = '';
  2158. /**
  2159. * The data definition of a texture. A reference to the data source can be
  2160. * shared across textures. This is often useful in context of spritesheets
  2161. * where multiple textures render the same data but with different texture
  2162. * transformations.
  2163. *
  2164. * @type {Source}
  2165. */
  2166. this.source = new Source( image );
  2167. /**
  2168. * An array holding user-defined mipmaps.
  2169. *
  2170. * @type {Array<Object>}
  2171. */
  2172. this.mipmaps = [];
  2173. /**
  2174. * How the texture is applied to the object. The value `UVMapping`
  2175. * is the default, where texture or uv coordinates are used to apply the map.
  2176. *
  2177. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  2178. * @default UVMapping
  2179. */
  2180. this.mapping = mapping;
  2181. /**
  2182. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  2183. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  2184. *
  2185. * @type {number}
  2186. * @default 0
  2187. */
  2188. this.channel = 0;
  2189. /**
  2190. * This defines how the texture is wrapped horizontally and corresponds to
  2191. * *U* in UV mapping.
  2192. *
  2193. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  2194. * @default ClampToEdgeWrapping
  2195. */
  2196. this.wrapS = wrapS;
  2197. /**
  2198. * This defines how the texture is wrapped horizontally and corresponds to
  2199. * *V* in UV mapping.
  2200. *
  2201. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  2202. * @default ClampToEdgeWrapping
  2203. */
  2204. this.wrapT = wrapT;
  2205. /**
  2206. * How the texture is sampled when a texel covers more than one pixel.
  2207. *
  2208. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  2209. * @default LinearFilter
  2210. */
  2211. this.magFilter = magFilter;
  2212. /**
  2213. * How the texture is sampled when a texel covers less than one pixel.
  2214. *
  2215. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  2216. * @default LinearMipmapLinearFilter
  2217. */
  2218. this.minFilter = minFilter;
  2219. /**
  2220. * The number of samples taken along the axis through the pixel that has the
  2221. * highest density of texels. By default, this value is `1`. A higher value
  2222. * gives a less blurry result than a basic mipmap, at the cost of more
  2223. * texture samples being used.
  2224. *
  2225. * @type {number}
  2226. * @default 0
  2227. */
  2228. this.anisotropy = anisotropy;
  2229. /**
  2230. * The format of the texture.
  2231. *
  2232. * @type {number}
  2233. * @default RGBAFormat
  2234. */
  2235. this.format = format;
  2236. /**
  2237. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  2238. * defines how the texture data is going to be stored on the GPU.
  2239. *
  2240. * This property allows to overwrite the default format.
  2241. *
  2242. * @type {?string}
  2243. * @default null
  2244. */
  2245. this.internalFormat = null;
  2246. /**
  2247. * The data type of the texture.
  2248. *
  2249. * @type {number}
  2250. * @default UnsignedByteType
  2251. */
  2252. this.type = type;
  2253. /**
  2254. * How much a single repetition of the texture is offset from the beginning,
  2255. * in each direction U and V. Typical range is `0.0` to `1.0`.
  2256. *
  2257. * @type {Vector2}
  2258. * @default (0,0)
  2259. */
  2260. this.offset = new Vector2( 0, 0 );
  2261. /**
  2262. * How many times the texture is repeated across the surface, in each
  2263. * direction U and V. If repeat is set greater than `1` in either direction,
  2264. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  2265. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  2266. *
  2267. * @type {Vector2}
  2268. * @default (1,1)
  2269. */
  2270. this.repeat = new Vector2( 1, 1 );
  2271. /**
  2272. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  2273. * to the center of the texture. Default is `(0, 0)`, the lower left.
  2274. *
  2275. * @type {Vector2}
  2276. * @default (0,0)
  2277. */
  2278. this.center = new Vector2( 0, 0 );
  2279. /**
  2280. * How much the texture is rotated around the center point, in radians.
  2281. * Positive values are counter-clockwise.
  2282. *
  2283. * @type {number}
  2284. * @default 0
  2285. */
  2286. this.rotation = 0;
  2287. /**
  2288. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  2289. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  2290. * {@link Texture#rotation}, and {@link Texture#center}.
  2291. *
  2292. * Set this to `false` if you are specifying the uv-transform matrix directly.
  2293. *
  2294. * @type {boolean}
  2295. * @default true
  2296. */
  2297. this.matrixAutoUpdate = true;
  2298. /**
  2299. * The uv-transformation matrix of the texture.
  2300. *
  2301. * @type {Matrix3}
  2302. */
  2303. this.matrix = new Matrix3();
  2304. /**
  2305. * Whether to generate mipmaps (if possible) for a texture.
  2306. *
  2307. * Set this to `false` if you are creating mipmaps manually.
  2308. *
  2309. * @type {boolean}
  2310. * @default true
  2311. */
  2312. this.generateMipmaps = true;
  2313. /**
  2314. * If set to `true`, the alpha channel, if present, is multiplied into the
  2315. * color channels when the texture is uploaded to the GPU.
  2316. *
  2317. * Note that this property has no effect when using `ImageBitmap`. You need to
  2318. * configure premultiply alpha on bitmap creation instead.
  2319. *
  2320. * @type {boolean}
  2321. * @default false
  2322. */
  2323. this.premultiplyAlpha = false;
  2324. /**
  2325. * If set to `true`, the texture is flipped along the vertical axis when
  2326. * uploaded to the GPU.
  2327. *
  2328. * Note that this property has no effect when using `ImageBitmap`. You need to
  2329. * configure the flip on bitmap creation instead.
  2330. *
  2331. * @type {boolean}
  2332. * @default true
  2333. */
  2334. this.flipY = true;
  2335. /**
  2336. * Specifies the alignment requirements for the start of each pixel row in memory.
  2337. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  2338. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  2339. *
  2340. * @type {number}
  2341. * @default 4
  2342. */
  2343. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  2344. /**
  2345. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  2346. *
  2347. * @type {string}
  2348. * @default NoColorSpace
  2349. */
  2350. this.colorSpace = colorSpace;
  2351. /**
  2352. * An object that can be used to store custom data about the texture. It
  2353. * should not hold references to functions as these will not be cloned.
  2354. *
  2355. * @type {Object}
  2356. */
  2357. this.userData = {};
  2358. /**
  2359. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  2360. *
  2361. * @type {number}
  2362. * @readonly
  2363. * @default 0
  2364. */
  2365. this.version = 0;
  2366. /**
  2367. * A callback function, called when the texture is updated (e.g., when
  2368. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  2369. *
  2370. * @type {?Function}
  2371. * @default null
  2372. */
  2373. this.onUpdate = null;
  2374. /**
  2375. * An optional back reference to the textures render target.
  2376. *
  2377. * @type {?(RenderTarget|WebGLRenderTarget)}
  2378. * @default null
  2379. */
  2380. this.renderTarget = null;
  2381. /**
  2382. * Indicates whether a texture belongs to a render target or not.
  2383. *
  2384. * @type {boolean}
  2385. * @readonly
  2386. * @default false
  2387. */
  2388. this.isRenderTargetTexture = false;
  2389. /**
  2390. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  2391. * (only relevant for render target textures).
  2392. *
  2393. * @type {number}
  2394. * @readonly
  2395. * @default 0
  2396. */
  2397. this.pmremVersion = 0;
  2398. }
  2399. /**
  2400. * The image object holding the texture data.
  2401. *
  2402. * @type {?Object}
  2403. */
  2404. get image() {
  2405. return this.source.data;
  2406. }
  2407. set image( value = null ) {
  2408. this.source.data = value;
  2409. }
  2410. /**
  2411. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  2412. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  2413. */
  2414. updateMatrix() {
  2415. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  2416. }
  2417. /**
  2418. * Returns a new texture with copied values from this instance.
  2419. *
  2420. * @return {Texture} A clone of this instance.
  2421. */
  2422. clone() {
  2423. return new this.constructor().copy( this );
  2424. }
  2425. /**
  2426. * Copies the values of the given texture to this instance.
  2427. *
  2428. * @param {Texture} source - The texture to copy.
  2429. * @return {Texture} A reference to this instance.
  2430. */
  2431. copy( source ) {
  2432. this.name = source.name;
  2433. this.source = source.source;
  2434. this.mipmaps = source.mipmaps.slice( 0 );
  2435. this.mapping = source.mapping;
  2436. this.channel = source.channel;
  2437. this.wrapS = source.wrapS;
  2438. this.wrapT = source.wrapT;
  2439. this.magFilter = source.magFilter;
  2440. this.minFilter = source.minFilter;
  2441. this.anisotropy = source.anisotropy;
  2442. this.format = source.format;
  2443. this.internalFormat = source.internalFormat;
  2444. this.type = source.type;
  2445. this.offset.copy( source.offset );
  2446. this.repeat.copy( source.repeat );
  2447. this.center.copy( source.center );
  2448. this.rotation = source.rotation;
  2449. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2450. this.matrix.copy( source.matrix );
  2451. this.generateMipmaps = source.generateMipmaps;
  2452. this.premultiplyAlpha = source.premultiplyAlpha;
  2453. this.flipY = source.flipY;
  2454. this.unpackAlignment = source.unpackAlignment;
  2455. this.colorSpace = source.colorSpace;
  2456. this.renderTarget = source.renderTarget;
  2457. this.isRenderTargetTexture = source.isRenderTargetTexture;
  2458. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  2459. this.needsUpdate = true;
  2460. return this;
  2461. }
  2462. /**
  2463. * Serializes the texture into JSON.
  2464. *
  2465. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  2466. * @return {Object} A JSON object representing the serialized texture.
  2467. * @see {@link ObjectLoader#parse}
  2468. */
  2469. toJSON( meta ) {
  2470. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2471. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  2472. return meta.textures[ this.uuid ];
  2473. }
  2474. const output = {
  2475. metadata: {
  2476. version: 4.6,
  2477. type: 'Texture',
  2478. generator: 'Texture.toJSON'
  2479. },
  2480. uuid: this.uuid,
  2481. name: this.name,
  2482. image: this.source.toJSON( meta ).uuid,
  2483. mapping: this.mapping,
  2484. channel: this.channel,
  2485. repeat: [ this.repeat.x, this.repeat.y ],
  2486. offset: [ this.offset.x, this.offset.y ],
  2487. center: [ this.center.x, this.center.y ],
  2488. rotation: this.rotation,
  2489. wrap: [ this.wrapS, this.wrapT ],
  2490. format: this.format,
  2491. internalFormat: this.internalFormat,
  2492. type: this.type,
  2493. colorSpace: this.colorSpace,
  2494. minFilter: this.minFilter,
  2495. magFilter: this.magFilter,
  2496. anisotropy: this.anisotropy,
  2497. flipY: this.flipY,
  2498. generateMipmaps: this.generateMipmaps,
  2499. premultiplyAlpha: this.premultiplyAlpha,
  2500. unpackAlignment: this.unpackAlignment
  2501. };
  2502. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  2503. if ( ! isRootObject ) {
  2504. meta.textures[ this.uuid ] = output;
  2505. }
  2506. return output;
  2507. }
  2508. /**
  2509. * Frees the GPU-related resources allocated by this instance. Call this
  2510. * method whenever this instance is no longer used in your app.
  2511. *
  2512. * @fires Texture#dispose
  2513. */
  2514. dispose() {
  2515. /**
  2516. * Fires when the texture has been disposed of.
  2517. *
  2518. * @event Texture#dispose
  2519. * @type {Object}
  2520. */
  2521. this.dispatchEvent( { type: 'dispose' } );
  2522. }
  2523. /**
  2524. * Transforms the given uv vector with the textures uv transformation matrix.
  2525. *
  2526. * @param {Vector2} uv - The uv vector.
  2527. * @return {Vector2} The transformed uv vector.
  2528. */
  2529. transformUv( uv ) {
  2530. if ( this.mapping !== UVMapping ) return uv;
  2531. uv.applyMatrix3( this.matrix );
  2532. if ( uv.x < 0 || uv.x > 1 ) {
  2533. switch ( this.wrapS ) {
  2534. case RepeatWrapping:
  2535. uv.x = uv.x - Math.floor( uv.x );
  2536. break;
  2537. case ClampToEdgeWrapping:
  2538. uv.x = uv.x < 0 ? 0 : 1;
  2539. break;
  2540. case MirroredRepeatWrapping:
  2541. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  2542. uv.x = Math.ceil( uv.x ) - uv.x;
  2543. } else {
  2544. uv.x = uv.x - Math.floor( uv.x );
  2545. }
  2546. break;
  2547. }
  2548. }
  2549. if ( uv.y < 0 || uv.y > 1 ) {
  2550. switch ( this.wrapT ) {
  2551. case RepeatWrapping:
  2552. uv.y = uv.y - Math.floor( uv.y );
  2553. break;
  2554. case ClampToEdgeWrapping:
  2555. uv.y = uv.y < 0 ? 0 : 1;
  2556. break;
  2557. case MirroredRepeatWrapping:
  2558. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  2559. uv.y = Math.ceil( uv.y ) - uv.y;
  2560. } else {
  2561. uv.y = uv.y - Math.floor( uv.y );
  2562. }
  2563. break;
  2564. }
  2565. }
  2566. if ( this.flipY ) {
  2567. uv.y = 1 - uv.y;
  2568. }
  2569. return uv;
  2570. }
  2571. /**
  2572. * Setting this property to `true` indicates the engine the texture
  2573. * must be updated in the next render. This triggers a texture upload
  2574. * to the GPU and ensures correct texture parameter configuration.
  2575. *
  2576. * @type {boolean}
  2577. * @default false
  2578. * @param {boolean} value
  2579. */
  2580. set needsUpdate( value ) {
  2581. if ( value === true ) {
  2582. this.version ++;
  2583. this.source.needsUpdate = true;
  2584. }
  2585. }
  2586. /**
  2587. * Setting this property to `true` indicates the engine the PMREM
  2588. * must be regenerated.
  2589. *
  2590. * @type {boolean}
  2591. * @default false
  2592. * @param {boolean} value
  2593. */
  2594. set needsPMREMUpdate( value ) {
  2595. if ( value === true ) {
  2596. this.pmremVersion ++;
  2597. }
  2598. }
  2599. }
  2600. /**
  2601. * The default image for all textures.
  2602. *
  2603. * @static
  2604. * @type {?Image}
  2605. * @default null
  2606. */
  2607. Texture.DEFAULT_IMAGE = null;
  2608. /**
  2609. * The default mapping for all textures.
  2610. *
  2611. * @static
  2612. * @type {number}
  2613. * @default UVMapping
  2614. */
  2615. Texture.DEFAULT_MAPPING = UVMapping;
  2616. /**
  2617. * The default anisotropy value for all textures.
  2618. *
  2619. * @static
  2620. * @type {number}
  2621. * @default 1
  2622. */
  2623. Texture.DEFAULT_ANISOTROPY = 1;
  2624. /**
  2625. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  2626. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  2627. *
  2628. * - A point in 4D space.
  2629. * - A direction and length in 4D space. In three.js the length will
  2630. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  2631. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  2632. * - Any arbitrary ordered quadruplet of numbers.
  2633. *
  2634. * There are other things a 4D vector can be used to represent, however these
  2635. * are the most common uses in *three.js*.
  2636. *
  2637. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2638. * the corresponding order.
  2639. * ```js
  2640. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  2641. *
  2642. * //no arguments; will be initialised to (0, 0, 0, 1)
  2643. * const b = new THREE.Vector4( );
  2644. *
  2645. * const d = a.dot( b );
  2646. * ```
  2647. */
  2648. class Vector4 {
  2649. /**
  2650. * Constructs a new 4D vector.
  2651. *
  2652. * @param {number} [x=0] - The x value of this vector.
  2653. * @param {number} [y=0] - The y value of this vector.
  2654. * @param {number} [z=0] - The z value of this vector.
  2655. * @param {number} [w=1] - The w value of this vector.
  2656. */
  2657. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2658. /**
  2659. * This flag can be used for type testing.
  2660. *
  2661. * @type {boolean}
  2662. * @readonly
  2663. * @default true
  2664. */
  2665. Vector4.prototype.isVector4 = true;
  2666. /**
  2667. * The x value of this vector.
  2668. *
  2669. * @type {number}
  2670. */
  2671. this.x = x;
  2672. /**
  2673. * The y value of this vector.
  2674. *
  2675. * @type {number}
  2676. */
  2677. this.y = y;
  2678. /**
  2679. * The z value of this vector.
  2680. *
  2681. * @type {number}
  2682. */
  2683. this.z = z;
  2684. /**
  2685. * The w value of this vector.
  2686. *
  2687. * @type {number}
  2688. */
  2689. this.w = w;
  2690. }
  2691. /**
  2692. * Alias for {@link Vector4#z}.
  2693. *
  2694. * @type {number}
  2695. */
  2696. get width() {
  2697. return this.z;
  2698. }
  2699. set width( value ) {
  2700. this.z = value;
  2701. }
  2702. /**
  2703. * Alias for {@link Vector4#w}.
  2704. *
  2705. * @type {number}
  2706. */
  2707. get height() {
  2708. return this.w;
  2709. }
  2710. set height( value ) {
  2711. this.w = value;
  2712. }
  2713. /**
  2714. * Sets the vector components.
  2715. *
  2716. * @param {number} x - The value of the x component.
  2717. * @param {number} y - The value of the y component.
  2718. * @param {number} z - The value of the z component.
  2719. * @param {number} w - The value of the w component.
  2720. * @return {Vector4} A reference to this vector.
  2721. */
  2722. set( x, y, z, w ) {
  2723. this.x = x;
  2724. this.y = y;
  2725. this.z = z;
  2726. this.w = w;
  2727. return this;
  2728. }
  2729. /**
  2730. * Sets the vector components to the same value.
  2731. *
  2732. * @param {number} scalar - The value to set for all vector components.
  2733. * @return {Vector4} A reference to this vector.
  2734. */
  2735. setScalar( scalar ) {
  2736. this.x = scalar;
  2737. this.y = scalar;
  2738. this.z = scalar;
  2739. this.w = scalar;
  2740. return this;
  2741. }
  2742. /**
  2743. * Sets the vector's x component to the given value
  2744. *
  2745. * @param {number} x - The value to set.
  2746. * @return {Vector4} A reference to this vector.
  2747. */
  2748. setX( x ) {
  2749. this.x = x;
  2750. return this;
  2751. }
  2752. /**
  2753. * Sets the vector's y component to the given value
  2754. *
  2755. * @param {number} y - The value to set.
  2756. * @return {Vector4} A reference to this vector.
  2757. */
  2758. setY( y ) {
  2759. this.y = y;
  2760. return this;
  2761. }
  2762. /**
  2763. * Sets the vector's z component to the given value
  2764. *
  2765. * @param {number} z - The value to set.
  2766. * @return {Vector4} A reference to this vector.
  2767. */
  2768. setZ( z ) {
  2769. this.z = z;
  2770. return this;
  2771. }
  2772. /**
  2773. * Sets the vector's w component to the given value
  2774. *
  2775. * @param {number} w - The value to set.
  2776. * @return {Vector4} A reference to this vector.
  2777. */
  2778. setW( w ) {
  2779. this.w = w;
  2780. return this;
  2781. }
  2782. /**
  2783. * Allows to set a vector component with an index.
  2784. *
  2785. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  2786. * `2` equals to z, `3` equals to w.
  2787. * @param {number} value - The value to set.
  2788. * @return {Vector4} A reference to this vector.
  2789. */
  2790. setComponent( index, value ) {
  2791. switch ( index ) {
  2792. case 0: this.x = value; break;
  2793. case 1: this.y = value; break;
  2794. case 2: this.z = value; break;
  2795. case 3: this.w = value; break;
  2796. default: throw new Error( 'index is out of range: ' + index );
  2797. }
  2798. return this;
  2799. }
  2800. /**
  2801. * Returns the value of the vector component which matches the given index.
  2802. *
  2803. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  2804. * `2` equals to z, `3` equals to w.
  2805. * @return {number} A vector component value.
  2806. */
  2807. getComponent( index ) {
  2808. switch ( index ) {
  2809. case 0: return this.x;
  2810. case 1: return this.y;
  2811. case 2: return this.z;
  2812. case 3: return this.w;
  2813. default: throw new Error( 'index is out of range: ' + index );
  2814. }
  2815. }
  2816. /**
  2817. * Returns a new vector with copied values from this instance.
  2818. *
  2819. * @return {Vector4} A clone of this instance.
  2820. */
  2821. clone() {
  2822. return new this.constructor( this.x, this.y, this.z, this.w );
  2823. }
  2824. /**
  2825. * Copies the values of the given vector to this instance.
  2826. *
  2827. * @param {Vector3|Vector4} v - The vector to copy.
  2828. * @return {Vector4} A reference to this vector.
  2829. */
  2830. copy( v ) {
  2831. this.x = v.x;
  2832. this.y = v.y;
  2833. this.z = v.z;
  2834. this.w = ( v.w !== undefined ) ? v.w : 1;
  2835. return this;
  2836. }
  2837. /**
  2838. * Adds the given vector to this instance.
  2839. *
  2840. * @param {Vector4} v - The vector to add.
  2841. * @return {Vector4} A reference to this vector.
  2842. */
  2843. add( v ) {
  2844. this.x += v.x;
  2845. this.y += v.y;
  2846. this.z += v.z;
  2847. this.w += v.w;
  2848. return this;
  2849. }
  2850. /**
  2851. * Adds the given scalar value to all components of this instance.
  2852. *
  2853. * @param {number} s - The scalar to add.
  2854. * @return {Vector4} A reference to this vector.
  2855. */
  2856. addScalar( s ) {
  2857. this.x += s;
  2858. this.y += s;
  2859. this.z += s;
  2860. this.w += s;
  2861. return this;
  2862. }
  2863. /**
  2864. * Adds the given vectors and stores the result in this instance.
  2865. *
  2866. * @param {Vector4} a - The first vector.
  2867. * @param {Vector4} b - The second vector.
  2868. * @return {Vector4} A reference to this vector.
  2869. */
  2870. addVectors( a, b ) {
  2871. this.x = a.x + b.x;
  2872. this.y = a.y + b.y;
  2873. this.z = a.z + b.z;
  2874. this.w = a.w + b.w;
  2875. return this;
  2876. }
  2877. /**
  2878. * Adds the given vector scaled by the given factor to this instance.
  2879. *
  2880. * @param {Vector4} v - The vector.
  2881. * @param {number} s - The factor that scales `v`.
  2882. * @return {Vector4} A reference to this vector.
  2883. */
  2884. addScaledVector( v, s ) {
  2885. this.x += v.x * s;
  2886. this.y += v.y * s;
  2887. this.z += v.z * s;
  2888. this.w += v.w * s;
  2889. return this;
  2890. }
  2891. /**
  2892. * Subtracts the given vector from this instance.
  2893. *
  2894. * @param {Vector4} v - The vector to subtract.
  2895. * @return {Vector4} A reference to this vector.
  2896. */
  2897. sub( v ) {
  2898. this.x -= v.x;
  2899. this.y -= v.y;
  2900. this.z -= v.z;
  2901. this.w -= v.w;
  2902. return this;
  2903. }
  2904. /**
  2905. * Subtracts the given scalar value from all components of this instance.
  2906. *
  2907. * @param {number} s - The scalar to subtract.
  2908. * @return {Vector4} A reference to this vector.
  2909. */
  2910. subScalar( s ) {
  2911. this.x -= s;
  2912. this.y -= s;
  2913. this.z -= s;
  2914. this.w -= s;
  2915. return this;
  2916. }
  2917. /**
  2918. * Subtracts the given vectors and stores the result in this instance.
  2919. *
  2920. * @param {Vector4} a - The first vector.
  2921. * @param {Vector4} b - The second vector.
  2922. * @return {Vector4} A reference to this vector.
  2923. */
  2924. subVectors( a, b ) {
  2925. this.x = a.x - b.x;
  2926. this.y = a.y - b.y;
  2927. this.z = a.z - b.z;
  2928. this.w = a.w - b.w;
  2929. return this;
  2930. }
  2931. /**
  2932. * Multiplies the given vector with this instance.
  2933. *
  2934. * @param {Vector4} v - The vector to multiply.
  2935. * @return {Vector4} A reference to this vector.
  2936. */
  2937. multiply( v ) {
  2938. this.x *= v.x;
  2939. this.y *= v.y;
  2940. this.z *= v.z;
  2941. this.w *= v.w;
  2942. return this;
  2943. }
  2944. /**
  2945. * Multiplies the given scalar value with all components of this instance.
  2946. *
  2947. * @param {number} scalar - The scalar to multiply.
  2948. * @return {Vector4} A reference to this vector.
  2949. */
  2950. multiplyScalar( scalar ) {
  2951. this.x *= scalar;
  2952. this.y *= scalar;
  2953. this.z *= scalar;
  2954. this.w *= scalar;
  2955. return this;
  2956. }
  2957. /**
  2958. * Multiplies this vector with the given 4x4 matrix.
  2959. *
  2960. * @param {Matrix4} m - The 4x4 matrix.
  2961. * @return {Vector4} A reference to this vector.
  2962. */
  2963. applyMatrix4( m ) {
  2964. const x = this.x, y = this.y, z = this.z, w = this.w;
  2965. const e = m.elements;
  2966. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  2967. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  2968. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  2969. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  2970. return this;
  2971. }
  2972. /**
  2973. * Divides this instance by the given vector.
  2974. *
  2975. * @param {Vector4} v - The vector to divide.
  2976. * @return {Vector4} A reference to this vector.
  2977. */
  2978. divide( v ) {
  2979. this.x /= v.x;
  2980. this.y /= v.y;
  2981. this.z /= v.z;
  2982. this.w /= v.w;
  2983. return this;
  2984. }
  2985. /**
  2986. * Divides this vector by the given scalar.
  2987. *
  2988. * @param {number} scalar - The scalar to divide.
  2989. * @return {Vector4} A reference to this vector.
  2990. */
  2991. divideScalar( scalar ) {
  2992. return this.multiplyScalar( 1 / scalar );
  2993. }
  2994. /**
  2995. * Sets the x, y and z components of this
  2996. * vector to the quaternion's axis and w to the angle.
  2997. *
  2998. * @param {Quaternion} q - The Quaternion to set.
  2999. * @return {Vector4} A reference to this vector.
  3000. */
  3001. setAxisAngleFromQuaternion( q ) {
  3002. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3003. // q is assumed to be normalized
  3004. this.w = 2 * Math.acos( q.w );
  3005. const s = Math.sqrt( 1 - q.w * q.w );
  3006. if ( s < 0.0001 ) {
  3007. this.x = 1;
  3008. this.y = 0;
  3009. this.z = 0;
  3010. } else {
  3011. this.x = q.x / s;
  3012. this.y = q.y / s;
  3013. this.z = q.z / s;
  3014. }
  3015. return this;
  3016. }
  3017. /**
  3018. * Sets the x, y and z components of this
  3019. * vector to the axis of rotation and w to the angle.
  3020. *
  3021. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  3022. * @return {Vector4} A reference to this vector.
  3023. */
  3024. setAxisAngleFromRotationMatrix( m ) {
  3025. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3026. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3027. let angle, x, y, z; // variables for result
  3028. const epsilon = 0.01, // margin to allow for rounding errors
  3029. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  3030. te = m.elements,
  3031. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3032. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3033. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3034. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  3035. ( Math.abs( m13 - m31 ) < epsilon ) &&
  3036. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  3037. // singularity found
  3038. // first check for identity matrix which must have +1 for all terms
  3039. // in leading diagonal and zero in other terms
  3040. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  3041. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  3042. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  3043. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  3044. // this singularity is identity matrix so angle = 0
  3045. this.set( 1, 0, 0, 0 );
  3046. return this; // zero angle, arbitrary axis
  3047. }
  3048. // otherwise this singularity is angle = 180
  3049. angle = Math.PI;
  3050. const xx = ( m11 + 1 ) / 2;
  3051. const yy = ( m22 + 1 ) / 2;
  3052. const zz = ( m33 + 1 ) / 2;
  3053. const xy = ( m12 + m21 ) / 4;
  3054. const xz = ( m13 + m31 ) / 4;
  3055. const yz = ( m23 + m32 ) / 4;
  3056. if ( ( xx > yy ) && ( xx > zz ) ) {
  3057. // m11 is the largest diagonal term
  3058. if ( xx < epsilon ) {
  3059. x = 0;
  3060. y = 0.707106781;
  3061. z = 0.707106781;
  3062. } else {
  3063. x = Math.sqrt( xx );
  3064. y = xy / x;
  3065. z = xz / x;
  3066. }
  3067. } else if ( yy > zz ) {
  3068. // m22 is the largest diagonal term
  3069. if ( yy < epsilon ) {
  3070. x = 0.707106781;
  3071. y = 0;
  3072. z = 0.707106781;
  3073. } else {
  3074. y = Math.sqrt( yy );
  3075. x = xy / y;
  3076. z = yz / y;
  3077. }
  3078. } else {
  3079. // m33 is the largest diagonal term so base result on this
  3080. if ( zz < epsilon ) {
  3081. x = 0.707106781;
  3082. y = 0.707106781;
  3083. z = 0;
  3084. } else {
  3085. z = Math.sqrt( zz );
  3086. x = xz / z;
  3087. y = yz / z;
  3088. }
  3089. }
  3090. this.set( x, y, z, angle );
  3091. return this; // return 180 deg rotation
  3092. }
  3093. // as we have reached here there are no singularities so we can handle normally
  3094. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  3095. ( m13 - m31 ) * ( m13 - m31 ) +
  3096. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  3097. if ( Math.abs( s ) < 0.001 ) s = 1;
  3098. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3099. // caught by singularity test above, but I've left it in just in case
  3100. this.x = ( m32 - m23 ) / s;
  3101. this.y = ( m13 - m31 ) / s;
  3102. this.z = ( m21 - m12 ) / s;
  3103. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  3104. return this;
  3105. }
  3106. /**
  3107. * Sets the vector components to the position elements of the
  3108. * given transformation matrix.
  3109. *
  3110. * @param {Matrix4} m - The 4x4 matrix.
  3111. * @return {Vector4} A reference to this vector.
  3112. */
  3113. setFromMatrixPosition( m ) {
  3114. const e = m.elements;
  3115. this.x = e[ 12 ];
  3116. this.y = e[ 13 ];
  3117. this.z = e[ 14 ];
  3118. this.w = e[ 15 ];
  3119. return this;
  3120. }
  3121. /**
  3122. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  3123. * value, replace that value with the corresponding min value.
  3124. *
  3125. * @param {Vector4} v - The vector.
  3126. * @return {Vector4} A reference to this vector.
  3127. */
  3128. min( v ) {
  3129. this.x = Math.min( this.x, v.x );
  3130. this.y = Math.min( this.y, v.y );
  3131. this.z = Math.min( this.z, v.z );
  3132. this.w = Math.min( this.w, v.w );
  3133. return this;
  3134. }
  3135. /**
  3136. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  3137. * value, replace that value with the corresponding max value.
  3138. *
  3139. * @param {Vector4} v - The vector.
  3140. * @return {Vector4} A reference to this vector.
  3141. */
  3142. max( v ) {
  3143. this.x = Math.max( this.x, v.x );
  3144. this.y = Math.max( this.y, v.y );
  3145. this.z = Math.max( this.z, v.z );
  3146. this.w = Math.max( this.w, v.w );
  3147. return this;
  3148. }
  3149. /**
  3150. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  3151. * value, it is replaced by the corresponding value.
  3152. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  3153. * it is replaced by the corresponding value.
  3154. *
  3155. * @param {Vector4} min - The minimum x, y and z values.
  3156. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  3157. * @return {Vector4} A reference to this vector.
  3158. */
  3159. clamp( min, max ) {
  3160. // assumes min < max, componentwise
  3161. this.x = clamp( this.x, min.x, max.x );
  3162. this.y = clamp( this.y, min.y, max.y );
  3163. this.z = clamp( this.z, min.z, max.z );
  3164. this.w = clamp( this.w, min.w, max.w );
  3165. return this;
  3166. }
  3167. /**
  3168. * If this vector's x, y, z or w values are greater than the max value, they are
  3169. * replaced by the max value.
  3170. * If this vector's x, y, z or w values are less than the min value, they are
  3171. * replaced by the min value.
  3172. *
  3173. * @param {number} minVal - The minimum value the components will be clamped to.
  3174. * @param {number} maxVal - The maximum value the components will be clamped to.
  3175. * @return {Vector4} A reference to this vector.
  3176. */
  3177. clampScalar( minVal, maxVal ) {
  3178. this.x = clamp( this.x, minVal, maxVal );
  3179. this.y = clamp( this.y, minVal, maxVal );
  3180. this.z = clamp( this.z, minVal, maxVal );
  3181. this.w = clamp( this.w, minVal, maxVal );
  3182. return this;
  3183. }
  3184. /**
  3185. * If this vector's length is greater than the max value, it is replaced by
  3186. * the max value.
  3187. * If this vector's length is less than the min value, it is replaced by the
  3188. * min value.
  3189. *
  3190. * @param {number} min - The minimum value the vector length will be clamped to.
  3191. * @param {number} max - The maximum value the vector length will be clamped to.
  3192. * @return {Vector4} A reference to this vector.
  3193. */
  3194. clampLength( min, max ) {
  3195. const length = this.length();
  3196. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3197. }
  3198. /**
  3199. * The components of this vector are rounded down to the nearest integer value.
  3200. *
  3201. * @return {Vector4} A reference to this vector.
  3202. */
  3203. floor() {
  3204. this.x = Math.floor( this.x );
  3205. this.y = Math.floor( this.y );
  3206. this.z = Math.floor( this.z );
  3207. this.w = Math.floor( this.w );
  3208. return this;
  3209. }
  3210. /**
  3211. * The components of this vector are rounded up to the nearest integer value.
  3212. *
  3213. * @return {Vector4} A reference to this vector.
  3214. */
  3215. ceil() {
  3216. this.x = Math.ceil( this.x );
  3217. this.y = Math.ceil( this.y );
  3218. this.z = Math.ceil( this.z );
  3219. this.w = Math.ceil( this.w );
  3220. return this;
  3221. }
  3222. /**
  3223. * The components of this vector are rounded to the nearest integer value
  3224. *
  3225. * @return {Vector4} A reference to this vector.
  3226. */
  3227. round() {
  3228. this.x = Math.round( this.x );
  3229. this.y = Math.round( this.y );
  3230. this.z = Math.round( this.z );
  3231. this.w = Math.round( this.w );
  3232. return this;
  3233. }
  3234. /**
  3235. * The components of this vector are rounded towards zero (up if negative,
  3236. * down if positive) to an integer value.
  3237. *
  3238. * @return {Vector4} A reference to this vector.
  3239. */
  3240. roundToZero() {
  3241. this.x = Math.trunc( this.x );
  3242. this.y = Math.trunc( this.y );
  3243. this.z = Math.trunc( this.z );
  3244. this.w = Math.trunc( this.w );
  3245. return this;
  3246. }
  3247. /**
  3248. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  3249. *
  3250. * @return {Vector4} A reference to this vector.
  3251. */
  3252. negate() {
  3253. this.x = - this.x;
  3254. this.y = - this.y;
  3255. this.z = - this.z;
  3256. this.w = - this.w;
  3257. return this;
  3258. }
  3259. /**
  3260. * Calculates the dot product of the given vector with this instance.
  3261. *
  3262. * @param {Vector4} v - The vector to compute the dot product with.
  3263. * @return {number} The result of the dot product.
  3264. */
  3265. dot( v ) {
  3266. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3267. }
  3268. /**
  3269. * Computes the square of the Euclidean length (straight-line length) from
  3270. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  3271. * compare the length squared instead as it is slightly more efficient to calculate.
  3272. *
  3273. * @return {number} The square length of this vector.
  3274. */
  3275. lengthSq() {
  3276. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3277. }
  3278. /**
  3279. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  3280. *
  3281. * @return {number} The length of this vector.
  3282. */
  3283. length() {
  3284. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  3285. }
  3286. /**
  3287. * Computes the Manhattan length of this vector.
  3288. *
  3289. * @return {number} The length of this vector.
  3290. */
  3291. manhattanLength() {
  3292. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  3293. }
  3294. /**
  3295. * Converts this vector to a unit vector - that is, sets it equal to a vector
  3296. * with the same direction as this one, but with a vector length of `1`.
  3297. *
  3298. * @return {Vector4} A reference to this vector.
  3299. */
  3300. normalize() {
  3301. return this.divideScalar( this.length() || 1 );
  3302. }
  3303. /**
  3304. * Sets this vector to a vector with the same direction as this one, but
  3305. * with the specified length.
  3306. *
  3307. * @param {number} length - The new length of this vector.
  3308. * @return {Vector4} A reference to this vector.
  3309. */
  3310. setLength( length ) {
  3311. return this.normalize().multiplyScalar( length );
  3312. }
  3313. /**
  3314. * Linearly interpolates between the given vector and this instance, where
  3315. * alpha is the percent distance along the line - alpha = 0 will be this
  3316. * vector, and alpha = 1 will be the given one.
  3317. *
  3318. * @param {Vector4} v - The vector to interpolate towards.
  3319. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3320. * @return {Vector4} A reference to this vector.
  3321. */
  3322. lerp( v, alpha ) {
  3323. this.x += ( v.x - this.x ) * alpha;
  3324. this.y += ( v.y - this.y ) * alpha;
  3325. this.z += ( v.z - this.z ) * alpha;
  3326. this.w += ( v.w - this.w ) * alpha;
  3327. return this;
  3328. }
  3329. /**
  3330. * Linearly interpolates between the given vectors, where alpha is the percent
  3331. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  3332. * be the second one. The result is stored in this instance.
  3333. *
  3334. * @param {Vector4} v1 - The first vector.
  3335. * @param {Vector4} v2 - The second vector.
  3336. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3337. * @return {Vector4} A reference to this vector.
  3338. */
  3339. lerpVectors( v1, v2, alpha ) {
  3340. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3341. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3342. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  3343. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  3344. return this;
  3345. }
  3346. /**
  3347. * Returns `true` if this vector is equal with the given one.
  3348. *
  3349. * @param {Vector4} v - The vector to test for equality.
  3350. * @return {boolean} Whether this vector is equal with the given one.
  3351. */
  3352. equals( v ) {
  3353. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  3354. }
  3355. /**
  3356. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  3357. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  3358. *
  3359. * @param {Array<number>} array - An array holding the vector component values.
  3360. * @param {number} [offset=0] - The offset into the array.
  3361. * @return {Vector4} A reference to this vector.
  3362. */
  3363. fromArray( array, offset = 0 ) {
  3364. this.x = array[ offset ];
  3365. this.y = array[ offset + 1 ];
  3366. this.z = array[ offset + 2 ];
  3367. this.w = array[ offset + 3 ];
  3368. return this;
  3369. }
  3370. /**
  3371. * Writes the components of this vector to the given array. If no array is provided,
  3372. * the method returns a new instance.
  3373. *
  3374. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  3375. * @param {number} [offset=0] - Index of the first element in the array.
  3376. * @return {Array<number>} The vector components.
  3377. */
  3378. toArray( array = [], offset = 0 ) {
  3379. array[ offset ] = this.x;
  3380. array[ offset + 1 ] = this.y;
  3381. array[ offset + 2 ] = this.z;
  3382. array[ offset + 3 ] = this.w;
  3383. return array;
  3384. }
  3385. /**
  3386. * Sets the components of this vector from the given buffer attribute.
  3387. *
  3388. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  3389. * @param {number} index - The index into the attribute.
  3390. * @return {Vector4} A reference to this vector.
  3391. */
  3392. fromBufferAttribute( attribute, index ) {
  3393. this.x = attribute.getX( index );
  3394. this.y = attribute.getY( index );
  3395. this.z = attribute.getZ( index );
  3396. this.w = attribute.getW( index );
  3397. return this;
  3398. }
  3399. /**
  3400. * Sets each component of this vector to a pseudo-random value between `0` and
  3401. * `1`, excluding `1`.
  3402. *
  3403. * @return {Vector4} A reference to this vector.
  3404. */
  3405. random() {
  3406. this.x = Math.random();
  3407. this.y = Math.random();
  3408. this.z = Math.random();
  3409. this.w = Math.random();
  3410. return this;
  3411. }
  3412. *[ Symbol.iterator ]() {
  3413. yield this.x;
  3414. yield this.y;
  3415. yield this.z;
  3416. yield this.w;
  3417. }
  3418. }
  3419. /*
  3420. In options, we can specify:
  3421. * Texture parameters for an auto-generated target texture
  3422. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  3423. */
  3424. class RenderTarget extends EventDispatcher {
  3425. constructor( width = 1, height = 1, options = {} ) {
  3426. super();
  3427. this.isRenderTarget = true;
  3428. this.width = width;
  3429. this.height = height;
  3430. this.depth = 1;
  3431. this.scissor = new Vector4( 0, 0, width, height );
  3432. this.scissorTest = false;
  3433. this.viewport = new Vector4( 0, 0, width, height );
  3434. const image = { width: width, height: height, depth: 1 };
  3435. options = Object.assign( {
  3436. generateMipmaps: false,
  3437. internalFormat: null,
  3438. minFilter: LinearFilter,
  3439. depthBuffer: true,
  3440. stencilBuffer: false,
  3441. resolveDepthBuffer: true,
  3442. resolveStencilBuffer: true,
  3443. depthTexture: null,
  3444. samples: 0,
  3445. count: 1
  3446. }, options );
  3447. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  3448. texture.flipY = false;
  3449. texture.generateMipmaps = options.generateMipmaps;
  3450. texture.internalFormat = options.internalFormat;
  3451. this.textures = [];
  3452. const count = options.count;
  3453. for ( let i = 0; i < count; i ++ ) {
  3454. this.textures[ i ] = texture.clone();
  3455. this.textures[ i ].isRenderTargetTexture = true;
  3456. this.textures[ i ].renderTarget = this;
  3457. }
  3458. this.depthBuffer = options.depthBuffer;
  3459. this.stencilBuffer = options.stencilBuffer;
  3460. this.resolveDepthBuffer = options.resolveDepthBuffer;
  3461. this.resolveStencilBuffer = options.resolveStencilBuffer;
  3462. this._depthTexture = null;
  3463. this.depthTexture = options.depthTexture;
  3464. this.samples = options.samples;
  3465. }
  3466. get texture() {
  3467. return this.textures[ 0 ];
  3468. }
  3469. set texture( value ) {
  3470. this.textures[ 0 ] = value;
  3471. }
  3472. set depthTexture( current ) {
  3473. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  3474. if ( current !== null ) current.renderTarget = this;
  3475. this._depthTexture = current;
  3476. }
  3477. get depthTexture() {
  3478. return this._depthTexture;
  3479. }
  3480. setSize( width, height, depth = 1 ) {
  3481. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  3482. this.width = width;
  3483. this.height = height;
  3484. this.depth = depth;
  3485. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  3486. this.textures[ i ].image.width = width;
  3487. this.textures[ i ].image.height = height;
  3488. this.textures[ i ].image.depth = depth;
  3489. }
  3490. this.dispose();
  3491. }
  3492. this.viewport.set( 0, 0, width, height );
  3493. this.scissor.set( 0, 0, width, height );
  3494. }
  3495. clone() {
  3496. return new this.constructor().copy( this );
  3497. }
  3498. copy( source ) {
  3499. this.width = source.width;
  3500. this.height = source.height;
  3501. this.depth = source.depth;
  3502. this.scissor.copy( source.scissor );
  3503. this.scissorTest = source.scissorTest;
  3504. this.viewport.copy( source.viewport );
  3505. this.textures.length = 0;
  3506. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  3507. this.textures[ i ] = source.textures[ i ].clone();
  3508. this.textures[ i ].isRenderTargetTexture = true;
  3509. this.textures[ i ].renderTarget = this;
  3510. // ensure image object is not shared, see #20328
  3511. const image = Object.assign( {}, source.textures[ i ].image );
  3512. this.textures[ i ].source = new Source( image );
  3513. }
  3514. this.depthBuffer = source.depthBuffer;
  3515. this.stencilBuffer = source.stencilBuffer;
  3516. this.resolveDepthBuffer = source.resolveDepthBuffer;
  3517. this.resolveStencilBuffer = source.resolveStencilBuffer;
  3518. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  3519. this.samples = source.samples;
  3520. return this;
  3521. }
  3522. dispose() {
  3523. this.dispatchEvent( { type: 'dispose' } );
  3524. }
  3525. }
  3526. class WebGLRenderTarget extends RenderTarget {
  3527. constructor( width = 1, height = 1, options = {} ) {
  3528. super( width, height, options );
  3529. this.isWebGLRenderTarget = true;
  3530. }
  3531. }
  3532. class DataArrayTexture extends Texture {
  3533. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  3534. super( null );
  3535. this.isDataArrayTexture = true;
  3536. this.image = { data, width, height, depth };
  3537. this.magFilter = NearestFilter;
  3538. this.minFilter = NearestFilter;
  3539. this.wrapR = ClampToEdgeWrapping;
  3540. this.generateMipmaps = false;
  3541. this.flipY = false;
  3542. this.unpackAlignment = 1;
  3543. this.layerUpdates = new Set();
  3544. }
  3545. addLayerUpdate( layerIndex ) {
  3546. this.layerUpdates.add( layerIndex );
  3547. }
  3548. clearLayerUpdates() {
  3549. this.layerUpdates.clear();
  3550. }
  3551. }
  3552. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  3553. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  3554. super( width, height, options );
  3555. this.isWebGLArrayRenderTarget = true;
  3556. this.depth = depth;
  3557. this.texture = new DataArrayTexture( null, width, height, depth );
  3558. this.texture.isRenderTargetTexture = true;
  3559. }
  3560. }
  3561. class Data3DTexture extends Texture {
  3562. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  3563. // We're going to add .setXXX() methods for setting properties later.
  3564. // Users can still set in Data3DTexture directly.
  3565. //
  3566. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  3567. // texture.anisotropy = 16;
  3568. //
  3569. // See #14839
  3570. super( null );
  3571. this.isData3DTexture = true;
  3572. this.image = { data, width, height, depth };
  3573. this.magFilter = NearestFilter;
  3574. this.minFilter = NearestFilter;
  3575. this.wrapR = ClampToEdgeWrapping;
  3576. this.generateMipmaps = false;
  3577. this.flipY = false;
  3578. this.unpackAlignment = 1;
  3579. }
  3580. }
  3581. class WebGL3DRenderTarget extends WebGLRenderTarget {
  3582. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  3583. super( width, height, options );
  3584. this.isWebGL3DRenderTarget = true;
  3585. this.depth = depth;
  3586. this.texture = new Data3DTexture( null, width, height, depth );
  3587. this.texture.isRenderTargetTexture = true;
  3588. }
  3589. }
  3590. /**
  3591. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  3592. *
  3593. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  3594. * the corresponding order.
  3595. *
  3596. * Note that three.js expects Quaternions to be normalized.
  3597. * ```js
  3598. * const quaternion = new THREE.Quaternion();
  3599. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  3600. *
  3601. * const vector = new THREE.Vector3( 1, 0, 0 );
  3602. * vector.applyQuaternion( quaternion );
  3603. * ```
  3604. */
  3605. class Quaternion {
  3606. /**
  3607. * Constructs a new quaternion.
  3608. *
  3609. * @param {number} [x=0] - The x value of this quaternion.
  3610. * @param {number} [y=0] - The y value of this quaternion.
  3611. * @param {number} [z=0] - The z value of this quaternion.
  3612. * @param {number} [w=1] - The w value of this quaternion.
  3613. */
  3614. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  3615. /**
  3616. * This flag can be used for type testing.
  3617. *
  3618. * @type {boolean}
  3619. * @readonly
  3620. * @default true
  3621. */
  3622. this.isQuaternion = true;
  3623. this._x = x;
  3624. this._y = y;
  3625. this._z = z;
  3626. this._w = w;
  3627. }
  3628. /**
  3629. * Interpolates between two quaternions via SLERP. This implementation assumes the
  3630. * quaternion data are managed in flat arrays.
  3631. *
  3632. * @param {Array<number>} dst - The destination array.
  3633. * @param {number} dstOffset - An offset into the destination array.
  3634. * @param {Array<number>} src0 - The source array of the first quaternion.
  3635. * @param {number} srcOffset0 - An offset into the first source array.
  3636. * @param {Array<number>} src1 - The source array of the second quaternion.
  3637. * @param {number} srcOffset1 - An offset into the second source array.
  3638. * @param {number} t - The interpolation factor in the range `[0,1]`.
  3639. * @see {@link Quaternion#slerp}
  3640. */
  3641. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3642. // fuzz-free, array-based Quaternion SLERP operation
  3643. let x0 = src0[ srcOffset0 + 0 ],
  3644. y0 = src0[ srcOffset0 + 1 ],
  3645. z0 = src0[ srcOffset0 + 2 ],
  3646. w0 = src0[ srcOffset0 + 3 ];
  3647. const x1 = src1[ srcOffset1 + 0 ],
  3648. y1 = src1[ srcOffset1 + 1 ],
  3649. z1 = src1[ srcOffset1 + 2 ],
  3650. w1 = src1[ srcOffset1 + 3 ];
  3651. if ( t === 0 ) {
  3652. dst[ dstOffset + 0 ] = x0;
  3653. dst[ dstOffset + 1 ] = y0;
  3654. dst[ dstOffset + 2 ] = z0;
  3655. dst[ dstOffset + 3 ] = w0;
  3656. return;
  3657. }
  3658. if ( t === 1 ) {
  3659. dst[ dstOffset + 0 ] = x1;
  3660. dst[ dstOffset + 1 ] = y1;
  3661. dst[ dstOffset + 2 ] = z1;
  3662. dst[ dstOffset + 3 ] = w1;
  3663. return;
  3664. }
  3665. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3666. let s = 1 - t;
  3667. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  3668. dir = ( cos >= 0 ? 1 : -1 ),
  3669. sqrSin = 1 - cos * cos;
  3670. // Skip the Slerp for tiny steps to avoid numeric problems:
  3671. if ( sqrSin > Number.EPSILON ) {
  3672. const sin = Math.sqrt( sqrSin ),
  3673. len = Math.atan2( sin, cos * dir );
  3674. s = Math.sin( s * len ) / sin;
  3675. t = Math.sin( t * len ) / sin;
  3676. }
  3677. const tDir = t * dir;
  3678. x0 = x0 * s + x1 * tDir;
  3679. y0 = y0 * s + y1 * tDir;
  3680. z0 = z0 * s + z1 * tDir;
  3681. w0 = w0 * s + w1 * tDir;
  3682. // Normalize in case we just did a lerp:
  3683. if ( s === 1 - t ) {
  3684. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3685. x0 *= f;
  3686. y0 *= f;
  3687. z0 *= f;
  3688. w0 *= f;
  3689. }
  3690. }
  3691. dst[ dstOffset ] = x0;
  3692. dst[ dstOffset + 1 ] = y0;
  3693. dst[ dstOffset + 2 ] = z0;
  3694. dst[ dstOffset + 3 ] = w0;
  3695. }
  3696. /**
  3697. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3698. * in flat arrays.
  3699. *
  3700. * @param {Array<number>} dst - The destination array.
  3701. * @param {number} dstOffset - An offset into the destination array.
  3702. * @param {Array<number>} src0 - The source array of the first quaternion.
  3703. * @param {number} srcOffset0 - An offset into the first source array.
  3704. * @param {Array<number>} src1 - The source array of the second quaternion.
  3705. * @param {number} srcOffset1 - An offset into the second source array.
  3706. * @return {Array<number>} The destination array.
  3707. * @see {@link Quaternion#multiplyQuaternions}.
  3708. */
  3709. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3710. const x0 = src0[ srcOffset0 ];
  3711. const y0 = src0[ srcOffset0 + 1 ];
  3712. const z0 = src0[ srcOffset0 + 2 ];
  3713. const w0 = src0[ srcOffset0 + 3 ];
  3714. const x1 = src1[ srcOffset1 ];
  3715. const y1 = src1[ srcOffset1 + 1 ];
  3716. const z1 = src1[ srcOffset1 + 2 ];
  3717. const w1 = src1[ srcOffset1 + 3 ];
  3718. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3719. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3720. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3721. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3722. return dst;
  3723. }
  3724. /**
  3725. * The x value of this quaternion.
  3726. *
  3727. * @type {number}
  3728. * @default 0
  3729. */
  3730. get x() {
  3731. return this._x;
  3732. }
  3733. set x( value ) {
  3734. this._x = value;
  3735. this._onChangeCallback();
  3736. }
  3737. /**
  3738. * The y value of this quaternion.
  3739. *
  3740. * @type {number}
  3741. * @default 0
  3742. */
  3743. get y() {
  3744. return this._y;
  3745. }
  3746. set y( value ) {
  3747. this._y = value;
  3748. this._onChangeCallback();
  3749. }
  3750. /**
  3751. * The z value of this quaternion.
  3752. *
  3753. * @type {number}
  3754. * @default 0
  3755. */
  3756. get z() {
  3757. return this._z;
  3758. }
  3759. set z( value ) {
  3760. this._z = value;
  3761. this._onChangeCallback();
  3762. }
  3763. /**
  3764. * The w value of this quaternion.
  3765. *
  3766. * @type {number}
  3767. * @default 1
  3768. */
  3769. get w() {
  3770. return this._w;
  3771. }
  3772. set w( value ) {
  3773. this._w = value;
  3774. this._onChangeCallback();
  3775. }
  3776. /**
  3777. * Sets the quaternion components.
  3778. *
  3779. * @param {number} x - The x value of this quaternion.
  3780. * @param {number} y - The y value of this quaternion.
  3781. * @param {number} z - The z value of this quaternion.
  3782. * @param {number} w - The w value of this quaternion.
  3783. * @return {Quaternion} A reference to this quaternion.
  3784. */
  3785. set( x, y, z, w ) {
  3786. this._x = x;
  3787. this._y = y;
  3788. this._z = z;
  3789. this._w = w;
  3790. this._onChangeCallback();
  3791. return this;
  3792. }
  3793. /**
  3794. * Returns a new quaternion with copied values from this instance.
  3795. *
  3796. * @return {Quaternion} A clone of this instance.
  3797. */
  3798. clone() {
  3799. return new this.constructor( this._x, this._y, this._z, this._w );
  3800. }
  3801. /**
  3802. * Copies the values of the given quaternion to this instance.
  3803. *
  3804. * @param {Quaternion} quaternion - The quaternion to copy.
  3805. * @return {Quaternion} A reference to this quaternion.
  3806. */
  3807. copy( quaternion ) {
  3808. this._x = quaternion.x;
  3809. this._y = quaternion.y;
  3810. this._z = quaternion.z;
  3811. this._w = quaternion.w;
  3812. this._onChangeCallback();
  3813. return this;
  3814. }
  3815. /**
  3816. * Sets this quaternion from the rotation specified by the given
  3817. * Euler angles.
  3818. *
  3819. * @param {Euler} euler - The Euler angles.
  3820. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3821. * @return {Quaternion} A reference to this quaternion.
  3822. */
  3823. setFromEuler( euler, update = true ) {
  3824. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3825. // http://www.mathworks.com/matlabcentral/fileexchange/
  3826. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3827. // content/SpinCalc.m
  3828. const cos = Math.cos;
  3829. const sin = Math.sin;
  3830. const c1 = cos( x / 2 );
  3831. const c2 = cos( y / 2 );
  3832. const c3 = cos( z / 2 );
  3833. const s1 = sin( x / 2 );
  3834. const s2 = sin( y / 2 );
  3835. const s3 = sin( z / 2 );
  3836. switch ( order ) {
  3837. case 'XYZ':
  3838. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3839. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3840. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3841. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3842. break;
  3843. case 'YXZ':
  3844. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3845. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3846. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3847. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3848. break;
  3849. case 'ZXY':
  3850. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3851. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3852. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3853. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3854. break;
  3855. case 'ZYX':
  3856. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3857. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3858. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3859. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3860. break;
  3861. case 'YZX':
  3862. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3863. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3864. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3865. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3866. break;
  3867. case 'XZY':
  3868. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3869. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3870. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3871. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3872. break;
  3873. default:
  3874. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3875. }
  3876. if ( update === true ) this._onChangeCallback();
  3877. return this;
  3878. }
  3879. /**
  3880. * Sets this quaternion from the given axis and angle.
  3881. *
  3882. * @param {Vector3} axis - The normalized axis.
  3883. * @param {number} angle - The angle in radians.
  3884. * @return {Quaternion} A reference to this quaternion.
  3885. */
  3886. setFromAxisAngle( axis, angle ) {
  3887. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3888. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3889. this._x = axis.x * s;
  3890. this._y = axis.y * s;
  3891. this._z = axis.z * s;
  3892. this._w = Math.cos( halfAngle );
  3893. this._onChangeCallback();
  3894. return this;
  3895. }
  3896. /**
  3897. * Sets this quaternion from the given rotation matrix.
  3898. *
  3899. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3900. * @return {Quaternion} A reference to this quaternion.
  3901. */
  3902. setFromRotationMatrix( m ) {
  3903. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3904. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3905. const te = m.elements,
  3906. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3907. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3908. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3909. trace = m11 + m22 + m33;
  3910. if ( trace > 0 ) {
  3911. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3912. this._w = 0.25 / s;
  3913. this._x = ( m32 - m23 ) * s;
  3914. this._y = ( m13 - m31 ) * s;
  3915. this._z = ( m21 - m12 ) * s;
  3916. } else if ( m11 > m22 && m11 > m33 ) {
  3917. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3918. this._w = ( m32 - m23 ) / s;
  3919. this._x = 0.25 * s;
  3920. this._y = ( m12 + m21 ) / s;
  3921. this._z = ( m13 + m31 ) / s;
  3922. } else if ( m22 > m33 ) {
  3923. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3924. this._w = ( m13 - m31 ) / s;
  3925. this._x = ( m12 + m21 ) / s;
  3926. this._y = 0.25 * s;
  3927. this._z = ( m23 + m32 ) / s;
  3928. } else {
  3929. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3930. this._w = ( m21 - m12 ) / s;
  3931. this._x = ( m13 + m31 ) / s;
  3932. this._y = ( m23 + m32 ) / s;
  3933. this._z = 0.25 * s;
  3934. }
  3935. this._onChangeCallback();
  3936. return this;
  3937. }
  3938. /**
  3939. * Sets this quaternion to the rotation required to rotate the direction vector
  3940. * `vFrom` to the direction vector `vTo`.
  3941. *
  3942. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3943. * @param {Vector3} vTo - The second (normalized) direction vector.
  3944. * @return {Quaternion} A reference to this quaternion.
  3945. */
  3946. setFromUnitVectors( vFrom, vTo ) {
  3947. // assumes direction vectors vFrom and vTo are normalized
  3948. let r = vFrom.dot( vTo ) + 1;
  3949. if ( r < Number.EPSILON ) {
  3950. // vFrom and vTo point in opposite directions
  3951. r = 0;
  3952. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3953. this._x = - vFrom.y;
  3954. this._y = vFrom.x;
  3955. this._z = 0;
  3956. this._w = r;
  3957. } else {
  3958. this._x = 0;
  3959. this._y = - vFrom.z;
  3960. this._z = vFrom.y;
  3961. this._w = r;
  3962. }
  3963. } else {
  3964. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3965. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3966. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3967. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3968. this._w = r;
  3969. }
  3970. return this.normalize();
  3971. }
  3972. /**
  3973. * Returns the angle between this quaternion and the given one in radians.
  3974. *
  3975. * @param {Quaternion} q - The quaternion to compute the angle with.
  3976. * @return {number} The angle in radians.
  3977. */
  3978. angleTo( q ) {
  3979. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3980. }
  3981. /**
  3982. * Rotates this quaternion by a given angular step to the given quaternion.
  3983. * The method ensures that the final quaternion will not overshoot `q`.
  3984. *
  3985. * @param {Quaternion} q - The target quaternion.
  3986. * @param {number} step - The angular step in radians.
  3987. * @return {Quaternion} A reference to this quaternion.
  3988. */
  3989. rotateTowards( q, step ) {
  3990. const angle = this.angleTo( q );
  3991. if ( angle === 0 ) return this;
  3992. const t = Math.min( 1, step / angle );
  3993. this.slerp( q, t );
  3994. return this;
  3995. }
  3996. /**
  3997. * Sets this quaternion to the identity quaternion; that is, to the
  3998. * quaternion that represents "no rotation".
  3999. *
  4000. * @return {Quaternion} A reference to this quaternion.
  4001. */
  4002. identity() {
  4003. return this.set( 0, 0, 0, 1 );
  4004. }
  4005. /**
  4006. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  4007. * quaternion is assumed to have unit length.
  4008. *
  4009. * @return {Quaternion} A reference to this quaternion.
  4010. */
  4011. invert() {
  4012. return this.conjugate();
  4013. }
  4014. /**
  4015. * Returns the rotational conjugate of this quaternion. The conjugate of a
  4016. * quaternion represents the same rotation in the opposite direction about
  4017. * the rotational axis.
  4018. *
  4019. * @return {Quaternion} A reference to this quaternion.
  4020. */
  4021. conjugate() {
  4022. this._x *= -1;
  4023. this._y *= -1;
  4024. this._z *= -1;
  4025. this._onChangeCallback();
  4026. return this;
  4027. }
  4028. /**
  4029. * Calculates the dot product of this quaternion and the given one.
  4030. *
  4031. * @param {Quaternion} v - The quaternion to compute the dot product with.
  4032. * @return {number} The result of the dot product.
  4033. */
  4034. dot( v ) {
  4035. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  4036. }
  4037. /**
  4038. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  4039. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  4040. * lengths of two quaternions, as this is a slightly more efficient calculation than
  4041. * {@link Quaternion#length}.
  4042. *
  4043. * @return {number} The squared Euclidean length.
  4044. */
  4045. lengthSq() {
  4046. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  4047. }
  4048. /**
  4049. * Computes the Euclidean length (straight-line length) of this quaternion,
  4050. * considered as a 4 dimensional vector.
  4051. *
  4052. * @return {number} The Euclidean length.
  4053. */
  4054. length() {
  4055. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  4056. }
  4057. /**
  4058. * Normalizes this quaternion - that is, calculated the quaternion that performs
  4059. * the same rotation as this one, but has a length equal to `1`.
  4060. *
  4061. * @return {Quaternion} A reference to this quaternion.
  4062. */
  4063. normalize() {
  4064. let l = this.length();
  4065. if ( l === 0 ) {
  4066. this._x = 0;
  4067. this._y = 0;
  4068. this._z = 0;
  4069. this._w = 1;
  4070. } else {
  4071. l = 1 / l;
  4072. this._x = this._x * l;
  4073. this._y = this._y * l;
  4074. this._z = this._z * l;
  4075. this._w = this._w * l;
  4076. }
  4077. this._onChangeCallback();
  4078. return this;
  4079. }
  4080. /**
  4081. * Multiplies this quaternion by the given one.
  4082. *
  4083. * @param {Quaternion} q - The quaternion.
  4084. * @return {Quaternion} A reference to this quaternion.
  4085. */
  4086. multiply( q ) {
  4087. return this.multiplyQuaternions( this, q );
  4088. }
  4089. /**
  4090. * Pre-multiplies this quaternion by the given one.
  4091. *
  4092. * @param {Quaternion} q - The quaternion.
  4093. * @return {Quaternion} A reference to this quaternion.
  4094. */
  4095. premultiply( q ) {
  4096. return this.multiplyQuaternions( q, this );
  4097. }
  4098. /**
  4099. * Multiplies the given quaternions and stores the result in this instance.
  4100. *
  4101. * @param {Quaternion} a - The first quaternion.
  4102. * @param {Quaternion} b - The second quaternion.
  4103. * @return {Quaternion} A reference to this quaternion.
  4104. */
  4105. multiplyQuaternions( a, b ) {
  4106. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  4107. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  4108. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  4109. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  4110. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  4111. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  4112. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  4113. this._onChangeCallback();
  4114. return this;
  4115. }
  4116. /**
  4117. * Performs a spherical linear interpolation between quaternions.
  4118. *
  4119. * @param {Quaternion} qb - The target quaternion.
  4120. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  4121. * @return {Quaternion} A reference to this quaternion.
  4122. */
  4123. slerp( qb, t ) {
  4124. if ( t === 0 ) return this;
  4125. if ( t === 1 ) return this.copy( qb );
  4126. const x = this._x, y = this._y, z = this._z, w = this._w;
  4127. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  4128. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  4129. if ( cosHalfTheta < 0 ) {
  4130. this._w = - qb._w;
  4131. this._x = - qb._x;
  4132. this._y = - qb._y;
  4133. this._z = - qb._z;
  4134. cosHalfTheta = - cosHalfTheta;
  4135. } else {
  4136. this.copy( qb );
  4137. }
  4138. if ( cosHalfTheta >= 1.0 ) {
  4139. this._w = w;
  4140. this._x = x;
  4141. this._y = y;
  4142. this._z = z;
  4143. return this;
  4144. }
  4145. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  4146. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  4147. const s = 1 - t;
  4148. this._w = s * w + t * this._w;
  4149. this._x = s * x + t * this._x;
  4150. this._y = s * y + t * this._y;
  4151. this._z = s * z + t * this._z;
  4152. this.normalize(); // normalize calls _onChangeCallback()
  4153. return this;
  4154. }
  4155. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  4156. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  4157. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  4158. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  4159. this._w = ( w * ratioA + this._w * ratioB );
  4160. this._x = ( x * ratioA + this._x * ratioB );
  4161. this._y = ( y * ratioA + this._y * ratioB );
  4162. this._z = ( z * ratioA + this._z * ratioB );
  4163. this._onChangeCallback();
  4164. return this;
  4165. }
  4166. /**
  4167. * Performs a spherical linear interpolation between the given quaternions
  4168. * and stores the result in this quaternion.
  4169. *
  4170. * @param {Quaternion} qa - The source quaternion.
  4171. * @param {Quaternion} qb - The target quaternion.
  4172. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  4173. * @return {Quaternion} A reference to this quaternion.
  4174. */
  4175. slerpQuaternions( qa, qb, t ) {
  4176. return this.copy( qa ).slerp( qb, t );
  4177. }
  4178. /**
  4179. * Sets this quaternion to a uniformly random, normalized quaternion.
  4180. *
  4181. * @return {Quaternion} A reference to this quaternion.
  4182. */
  4183. random() {
  4184. // Ken Shoemake
  4185. // Uniform random rotations
  4186. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  4187. const theta1 = 2 * Math.PI * Math.random();
  4188. const theta2 = 2 * Math.PI * Math.random();
  4189. const x0 = Math.random();
  4190. const r1 = Math.sqrt( 1 - x0 );
  4191. const r2 = Math.sqrt( x0 );
  4192. return this.set(
  4193. r1 * Math.sin( theta1 ),
  4194. r1 * Math.cos( theta1 ),
  4195. r2 * Math.sin( theta2 ),
  4196. r2 * Math.cos( theta2 ),
  4197. );
  4198. }
  4199. /**
  4200. * Returns `true` if this quaternion is equal with the given one.
  4201. *
  4202. * @param {Quaternion} quaternion - The quaternion to test for equality.
  4203. * @return {boolean} Whether this quaternion is equal with the given one.
  4204. */
  4205. equals( quaternion ) {
  4206. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  4207. }
  4208. /**
  4209. * Sets this quaternion's components from the given array.
  4210. *
  4211. * @param {Array<number>} array - An array holding the quaternion component values.
  4212. * @param {number} [offset=0] - The offset into the array.
  4213. * @return {Quaternion} A reference to this quaternion.
  4214. */
  4215. fromArray( array, offset = 0 ) {
  4216. this._x = array[ offset ];
  4217. this._y = array[ offset + 1 ];
  4218. this._z = array[ offset + 2 ];
  4219. this._w = array[ offset + 3 ];
  4220. this._onChangeCallback();
  4221. return this;
  4222. }
  4223. /**
  4224. * Writes the components of this quaternion to the given array. If no array is provided,
  4225. * the method returns a new instance.
  4226. *
  4227. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  4228. * @param {number} [offset=0] - Index of the first element in the array.
  4229. * @return {Array<number>} The quaternion components.
  4230. */
  4231. toArray( array = [], offset = 0 ) {
  4232. array[ offset ] = this._x;
  4233. array[ offset + 1 ] = this._y;
  4234. array[ offset + 2 ] = this._z;
  4235. array[ offset + 3 ] = this._w;
  4236. return array;
  4237. }
  4238. /**
  4239. * Sets the components of this quaternion from the given buffer attribute.
  4240. *
  4241. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  4242. * @param {number} index - The index into the attribute.
  4243. * @return {Quaternion} A reference to this quaternion.
  4244. */
  4245. fromBufferAttribute( attribute, index ) {
  4246. this._x = attribute.getX( index );
  4247. this._y = attribute.getY( index );
  4248. this._z = attribute.getZ( index );
  4249. this._w = attribute.getW( index );
  4250. this._onChangeCallback();
  4251. return this;
  4252. }
  4253. /**
  4254. * This methods defines the serialization result of this class. Returns the
  4255. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  4256. *
  4257. * @return {Array<number>} The serialized quaternion.
  4258. */
  4259. toJSON() {
  4260. return this.toArray();
  4261. }
  4262. _onChange( callback ) {
  4263. this._onChangeCallback = callback;
  4264. return this;
  4265. }
  4266. _onChangeCallback() {}
  4267. *[ Symbol.iterator ]() {
  4268. yield this._x;
  4269. yield this._y;
  4270. yield this._z;
  4271. yield this._w;
  4272. }
  4273. }
  4274. /**
  4275. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  4276. * (labeled x, y and z), which can be used to represent a number of things, such as:
  4277. *
  4278. * - A point in 3D space.
  4279. * - A direction and length in 3D space. In three.js the length will
  4280. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  4281. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  4282. * - Any arbitrary ordered triplet of numbers.
  4283. *
  4284. * There are other things a 3D vector can be used to represent, such as
  4285. * momentum vectors and so on, however these are the most
  4286. * common uses in three.js.
  4287. *
  4288. * Iterating through a vector instance will yield its components `(x, y, z)` in
  4289. * the corresponding order.
  4290. * ```js
  4291. * const a = new THREE.Vector3( 0, 1, 0 );
  4292. *
  4293. * //no arguments; will be initialised to (0, 0, 0)
  4294. * const b = new THREE.Vector3( );
  4295. *
  4296. * const d = a.distanceTo( b );
  4297. * ```
  4298. */
  4299. class Vector3 {
  4300. /**
  4301. * Constructs a new 3D vector.
  4302. *
  4303. * @param {number} [x=0] - The x value of this vector.
  4304. * @param {number} [y=0] - The y value of this vector.
  4305. * @param {number} [z=0] - The z value of this vector.
  4306. */
  4307. constructor( x = 0, y = 0, z = 0 ) {
  4308. /**
  4309. * This flag can be used for type testing.
  4310. *
  4311. * @type {boolean}
  4312. * @readonly
  4313. * @default true
  4314. */
  4315. Vector3.prototype.isVector3 = true;
  4316. /**
  4317. * The x value of this vector.
  4318. *
  4319. * @type {number}
  4320. */
  4321. this.x = x;
  4322. /**
  4323. * The y value of this vector.
  4324. *
  4325. * @type {number}
  4326. */
  4327. this.y = y;
  4328. /**
  4329. * The z value of this vector.
  4330. *
  4331. * @type {number}
  4332. */
  4333. this.z = z;
  4334. }
  4335. /**
  4336. * Sets the vector components.
  4337. *
  4338. * @param {number} x - The value of the x component.
  4339. * @param {number} y - The value of the y component.
  4340. * @param {number} z - The value of the z component.
  4341. * @return {Vector3} A reference to this vector.
  4342. */
  4343. set( x, y, z ) {
  4344. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  4345. this.x = x;
  4346. this.y = y;
  4347. this.z = z;
  4348. return this;
  4349. }
  4350. /**
  4351. * Sets the vector components to the same value.
  4352. *
  4353. * @param {number} scalar - The value to set for all vector components.
  4354. * @return {Vector3} A reference to this vector.
  4355. */
  4356. setScalar( scalar ) {
  4357. this.x = scalar;
  4358. this.y = scalar;
  4359. this.z = scalar;
  4360. return this;
  4361. }
  4362. /**
  4363. * Sets the vector's x component to the given value
  4364. *
  4365. * @param {number} x - The value to set.
  4366. * @return {Vector3} A reference to this vector.
  4367. */
  4368. setX( x ) {
  4369. this.x = x;
  4370. return this;
  4371. }
  4372. /**
  4373. * Sets the vector's y component to the given value
  4374. *
  4375. * @param {number} y - The value to set.
  4376. * @return {Vector3} A reference to this vector.
  4377. */
  4378. setY( y ) {
  4379. this.y = y;
  4380. return this;
  4381. }
  4382. /**
  4383. * Sets the vector's z component to the given value
  4384. *
  4385. * @param {number} z - The value to set.
  4386. * @return {Vector3} A reference to this vector.
  4387. */
  4388. setZ( z ) {
  4389. this.z = z;
  4390. return this;
  4391. }
  4392. /**
  4393. * Allows to set a vector component with an index.
  4394. *
  4395. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  4396. * @param {number} value - The value to set.
  4397. * @return {Vector3} A reference to this vector.
  4398. */
  4399. setComponent( index, value ) {
  4400. switch ( index ) {
  4401. case 0: this.x = value; break;
  4402. case 1: this.y = value; break;
  4403. case 2: this.z = value; break;
  4404. default: throw new Error( 'index is out of range: ' + index );
  4405. }
  4406. return this;
  4407. }
  4408. /**
  4409. * Returns the value of the vector component which matches the given index.
  4410. *
  4411. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  4412. * @return {number} A vector component value.
  4413. */
  4414. getComponent( index ) {
  4415. switch ( index ) {
  4416. case 0: return this.x;
  4417. case 1: return this.y;
  4418. case 2: return this.z;
  4419. default: throw new Error( 'index is out of range: ' + index );
  4420. }
  4421. }
  4422. /**
  4423. * Returns a new vector with copied values from this instance.
  4424. *
  4425. * @return {Vector3} A clone of this instance.
  4426. */
  4427. clone() {
  4428. return new this.constructor( this.x, this.y, this.z );
  4429. }
  4430. /**
  4431. * Copies the values of the given vector to this instance.
  4432. *
  4433. * @param {Vector3} v - The vector to copy.
  4434. * @return {Vector3} A reference to this vector.
  4435. */
  4436. copy( v ) {
  4437. this.x = v.x;
  4438. this.y = v.y;
  4439. this.z = v.z;
  4440. return this;
  4441. }
  4442. /**
  4443. * Adds the given vector to this instance.
  4444. *
  4445. * @param {Vector3} v - The vector to add.
  4446. * @return {Vector3} A reference to this vector.
  4447. */
  4448. add( v ) {
  4449. this.x += v.x;
  4450. this.y += v.y;
  4451. this.z += v.z;
  4452. return this;
  4453. }
  4454. /**
  4455. * Adds the given scalar value to all components of this instance.
  4456. *
  4457. * @param {number} s - The scalar to add.
  4458. * @return {Vector3} A reference to this vector.
  4459. */
  4460. addScalar( s ) {
  4461. this.x += s;
  4462. this.y += s;
  4463. this.z += s;
  4464. return this;
  4465. }
  4466. /**
  4467. * Adds the given vectors and stores the result in this instance.
  4468. *
  4469. * @param {Vector3} a - The first vector.
  4470. * @param {Vector3} b - The second vector.
  4471. * @return {Vector3} A reference to this vector.
  4472. */
  4473. addVectors( a, b ) {
  4474. this.x = a.x + b.x;
  4475. this.y = a.y + b.y;
  4476. this.z = a.z + b.z;
  4477. return this;
  4478. }
  4479. /**
  4480. * Adds the given vector scaled by the given factor to this instance.
  4481. *
  4482. * @param {Vector3|Vector4} v - The vector.
  4483. * @param {number} s - The factor that scales `v`.
  4484. * @return {Vector3} A reference to this vector.
  4485. */
  4486. addScaledVector( v, s ) {
  4487. this.x += v.x * s;
  4488. this.y += v.y * s;
  4489. this.z += v.z * s;
  4490. return this;
  4491. }
  4492. /**
  4493. * Subtracts the given vector from this instance.
  4494. *
  4495. * @param {Vector3} v - The vector to subtract.
  4496. * @return {Vector3} A reference to this vector.
  4497. */
  4498. sub( v ) {
  4499. this.x -= v.x;
  4500. this.y -= v.y;
  4501. this.z -= v.z;
  4502. return this;
  4503. }
  4504. /**
  4505. * Subtracts the given scalar value from all components of this instance.
  4506. *
  4507. * @param {number} s - The scalar to subtract.
  4508. * @return {Vector3} A reference to this vector.
  4509. */
  4510. subScalar( s ) {
  4511. this.x -= s;
  4512. this.y -= s;
  4513. this.z -= s;
  4514. return this;
  4515. }
  4516. /**
  4517. * Subtracts the given vectors and stores the result in this instance.
  4518. *
  4519. * @param {Vector3} a - The first vector.
  4520. * @param {Vector3} b - The second vector.
  4521. * @return {Vector3} A reference to this vector.
  4522. */
  4523. subVectors( a, b ) {
  4524. this.x = a.x - b.x;
  4525. this.y = a.y - b.y;
  4526. this.z = a.z - b.z;
  4527. return this;
  4528. }
  4529. /**
  4530. * Multiplies the given vector with this instance.
  4531. *
  4532. * @param {Vector3} v - The vector to multiply.
  4533. * @return {Vector3} A reference to this vector.
  4534. */
  4535. multiply( v ) {
  4536. this.x *= v.x;
  4537. this.y *= v.y;
  4538. this.z *= v.z;
  4539. return this;
  4540. }
  4541. /**
  4542. * Multiplies the given scalar value with all components of this instance.
  4543. *
  4544. * @param {number} scalar - The scalar to multiply.
  4545. * @return {Vector3} A reference to this vector.
  4546. */
  4547. multiplyScalar( scalar ) {
  4548. this.x *= scalar;
  4549. this.y *= scalar;
  4550. this.z *= scalar;
  4551. return this;
  4552. }
  4553. /**
  4554. * Multiplies the given vectors and stores the result in this instance.
  4555. *
  4556. * @param {Vector3} a - The first vector.
  4557. * @param {Vector3} b - The second vector.
  4558. * @return {Vector3} A reference to this vector.
  4559. */
  4560. multiplyVectors( a, b ) {
  4561. this.x = a.x * b.x;
  4562. this.y = a.y * b.y;
  4563. this.z = a.z * b.z;
  4564. return this;
  4565. }
  4566. /**
  4567. * Applies the given Euler rotation to this vector.
  4568. *
  4569. * @param {Euler} euler - The Euler angles.
  4570. * @return {Vector3} A reference to this vector.
  4571. */
  4572. applyEuler( euler ) {
  4573. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  4574. }
  4575. /**
  4576. * Applies a rotation specified by an axis and an angle to this vector.
  4577. *
  4578. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  4579. * @param {number} angle - The angle in radians.
  4580. * @return {Vector3} A reference to this vector.
  4581. */
  4582. applyAxisAngle( axis, angle ) {
  4583. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  4584. }
  4585. /**
  4586. * Multiplies this vector with the given 3x3 matrix.
  4587. *
  4588. * @param {Matrix3} m - The 3x3 matrix.
  4589. * @return {Vector3} A reference to this vector.
  4590. */
  4591. applyMatrix3( m ) {
  4592. const x = this.x, y = this.y, z = this.z;
  4593. const e = m.elements;
  4594. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  4595. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  4596. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  4597. return this;
  4598. }
  4599. /**
  4600. * Multiplies this vector by the given normal matrix and normalizes
  4601. * the result.
  4602. *
  4603. * @param {Matrix3} m - The normal matrix.
  4604. * @return {Vector3} A reference to this vector.
  4605. */
  4606. applyNormalMatrix( m ) {
  4607. return this.applyMatrix3( m ).normalize();
  4608. }
  4609. /**
  4610. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  4611. * divides by perspective.
  4612. *
  4613. * @param {Matrix4} m - The matrix to apply.
  4614. * @return {Vector3} A reference to this vector.
  4615. */
  4616. applyMatrix4( m ) {
  4617. const x = this.x, y = this.y, z = this.z;
  4618. const e = m.elements;
  4619. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  4620. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  4621. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  4622. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  4623. return this;
  4624. }
  4625. /**
  4626. * Applies the given Quaternion to this vector.
  4627. *
  4628. * @param {Quaternion} q - The Quaternion.
  4629. * @return {Vector3} A reference to this vector.
  4630. */
  4631. applyQuaternion( q ) {
  4632. // quaternion q is assumed to have unit length
  4633. const vx = this.x, vy = this.y, vz = this.z;
  4634. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  4635. // t = 2 * cross( q.xyz, v );
  4636. const tx = 2 * ( qy * vz - qz * vy );
  4637. const ty = 2 * ( qz * vx - qx * vz );
  4638. const tz = 2 * ( qx * vy - qy * vx );
  4639. // v + q.w * t + cross( q.xyz, t );
  4640. this.x = vx + qw * tx + qy * tz - qz * ty;
  4641. this.y = vy + qw * ty + qz * tx - qx * tz;
  4642. this.z = vz + qw * tz + qx * ty - qy * tx;
  4643. return this;
  4644. }
  4645. /**
  4646. * Projects this vector from world space into the camera's normalized
  4647. * device coordinate (NDC) space.
  4648. *
  4649. * @param {Camera} camera - The camera.
  4650. * @return {Vector3} A reference to this vector.
  4651. */
  4652. project( camera ) {
  4653. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4654. }
  4655. /**
  4656. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4657. * space into world space.
  4658. *
  4659. * @param {Camera} camera - The camera.
  4660. * @return {Vector3} A reference to this vector.
  4661. */
  4662. unproject( camera ) {
  4663. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4664. }
  4665. /**
  4666. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4667. * subset of the given 4x4 matrix and then normalizes the result.
  4668. *
  4669. * @param {Matrix4} m - The matrix.
  4670. * @return {Vector3} A reference to this vector.
  4671. */
  4672. transformDirection( m ) {
  4673. // input: THREE.Matrix4 affine matrix
  4674. // vector interpreted as a direction
  4675. const x = this.x, y = this.y, z = this.z;
  4676. const e = m.elements;
  4677. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4678. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4679. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4680. return this.normalize();
  4681. }
  4682. /**
  4683. * Divides this instance by the given vector.
  4684. *
  4685. * @param {Vector3} v - The vector to divide.
  4686. * @return {Vector3} A reference to this vector.
  4687. */
  4688. divide( v ) {
  4689. this.x /= v.x;
  4690. this.y /= v.y;
  4691. this.z /= v.z;
  4692. return this;
  4693. }
  4694. /**
  4695. * Divides this vector by the given scalar.
  4696. *
  4697. * @param {number} scalar - The scalar to divide.
  4698. * @return {Vector3} A reference to this vector.
  4699. */
  4700. divideScalar( scalar ) {
  4701. return this.multiplyScalar( 1 / scalar );
  4702. }
  4703. /**
  4704. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4705. * value, replace that value with the corresponding min value.
  4706. *
  4707. * @param {Vector3} v - The vector.
  4708. * @return {Vector3} A reference to this vector.
  4709. */
  4710. min( v ) {
  4711. this.x = Math.min( this.x, v.x );
  4712. this.y = Math.min( this.y, v.y );
  4713. this.z = Math.min( this.z, v.z );
  4714. return this;
  4715. }
  4716. /**
  4717. * If this vector's x, y or z value is less than the given vector's x, y or z
  4718. * value, replace that value with the corresponding max value.
  4719. *
  4720. * @param {Vector3} v - The vector.
  4721. * @return {Vector3} A reference to this vector.
  4722. */
  4723. max( v ) {
  4724. this.x = Math.max( this.x, v.x );
  4725. this.y = Math.max( this.y, v.y );
  4726. this.z = Math.max( this.z, v.z );
  4727. return this;
  4728. }
  4729. /**
  4730. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4731. * value, it is replaced by the corresponding value.
  4732. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4733. * it is replaced by the corresponding value.
  4734. *
  4735. * @param {Vector3} min - The minimum x, y and z values.
  4736. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4737. * @return {Vector3} A reference to this vector.
  4738. */
  4739. clamp( min, max ) {
  4740. // assumes min < max, componentwise
  4741. this.x = clamp( this.x, min.x, max.x );
  4742. this.y = clamp( this.y, min.y, max.y );
  4743. this.z = clamp( this.z, min.z, max.z );
  4744. return this;
  4745. }
  4746. /**
  4747. * If this vector's x, y or z values are greater than the max value, they are
  4748. * replaced by the max value.
  4749. * If this vector's x, y or z values are less than the min value, they are
  4750. * replaced by the min value.
  4751. *
  4752. * @param {number} minVal - The minimum value the components will be clamped to.
  4753. * @param {number} maxVal - The maximum value the components will be clamped to.
  4754. * @return {Vector3} A reference to this vector.
  4755. */
  4756. clampScalar( minVal, maxVal ) {
  4757. this.x = clamp( this.x, minVal, maxVal );
  4758. this.y = clamp( this.y, minVal, maxVal );
  4759. this.z = clamp( this.z, minVal, maxVal );
  4760. return this;
  4761. }
  4762. /**
  4763. * If this vector's length is greater than the max value, it is replaced by
  4764. * the max value.
  4765. * If this vector's length is less than the min value, it is replaced by the
  4766. * min value.
  4767. *
  4768. * @param {number} min - The minimum value the vector length will be clamped to.
  4769. * @param {number} max - The maximum value the vector length will be clamped to.
  4770. * @return {Vector3} A reference to this vector.
  4771. */
  4772. clampLength( min, max ) {
  4773. const length = this.length();
  4774. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4775. }
  4776. /**
  4777. * The components of this vector are rounded down to the nearest integer value.
  4778. *
  4779. * @return {Vector3} A reference to this vector.
  4780. */
  4781. floor() {
  4782. this.x = Math.floor( this.x );
  4783. this.y = Math.floor( this.y );
  4784. this.z = Math.floor( this.z );
  4785. return this;
  4786. }
  4787. /**
  4788. * The components of this vector are rounded up to the nearest integer value.
  4789. *
  4790. * @return {Vector3} A reference to this vector.
  4791. */
  4792. ceil() {
  4793. this.x = Math.ceil( this.x );
  4794. this.y = Math.ceil( this.y );
  4795. this.z = Math.ceil( this.z );
  4796. return this;
  4797. }
  4798. /**
  4799. * The components of this vector are rounded to the nearest integer value
  4800. *
  4801. * @return {Vector3} A reference to this vector.
  4802. */
  4803. round() {
  4804. this.x = Math.round( this.x );
  4805. this.y = Math.round( this.y );
  4806. this.z = Math.round( this.z );
  4807. return this;
  4808. }
  4809. /**
  4810. * The components of this vector are rounded towards zero (up if negative,
  4811. * down if positive) to an integer value.
  4812. *
  4813. * @return {Vector3} A reference to this vector.
  4814. */
  4815. roundToZero() {
  4816. this.x = Math.trunc( this.x );
  4817. this.y = Math.trunc( this.y );
  4818. this.z = Math.trunc( this.z );
  4819. return this;
  4820. }
  4821. /**
  4822. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4823. *
  4824. * @return {Vector3} A reference to this vector.
  4825. */
  4826. negate() {
  4827. this.x = - this.x;
  4828. this.y = - this.y;
  4829. this.z = - this.z;
  4830. return this;
  4831. }
  4832. /**
  4833. * Calculates the dot product of the given vector with this instance.
  4834. *
  4835. * @param {Vector3} v - The vector to compute the dot product with.
  4836. * @return {number} The result of the dot product.
  4837. */
  4838. dot( v ) {
  4839. return this.x * v.x + this.y * v.y + this.z * v.z;
  4840. }
  4841. // TODO lengthSquared?
  4842. /**
  4843. * Computes the square of the Euclidean length (straight-line length) from
  4844. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4845. * compare the length squared instead as it is slightly more efficient to calculate.
  4846. *
  4847. * @return {number} The square length of this vector.
  4848. */
  4849. lengthSq() {
  4850. return this.x * this.x + this.y * this.y + this.z * this.z;
  4851. }
  4852. /**
  4853. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4854. *
  4855. * @return {number} The length of this vector.
  4856. */
  4857. length() {
  4858. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4859. }
  4860. /**
  4861. * Computes the Manhattan length of this vector.
  4862. *
  4863. * @return {number} The length of this vector.
  4864. */
  4865. manhattanLength() {
  4866. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4867. }
  4868. /**
  4869. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4870. * with the same direction as this one, but with a vector length of `1`.
  4871. *
  4872. * @return {Vector3} A reference to this vector.
  4873. */
  4874. normalize() {
  4875. return this.divideScalar( this.length() || 1 );
  4876. }
  4877. /**
  4878. * Sets this vector to a vector with the same direction as this one, but
  4879. * with the specified length.
  4880. *
  4881. * @param {number} length - The new length of this vector.
  4882. * @return {Vector3} A reference to this vector.
  4883. */
  4884. setLength( length ) {
  4885. return this.normalize().multiplyScalar( length );
  4886. }
  4887. /**
  4888. * Linearly interpolates between the given vector and this instance, where
  4889. * alpha is the percent distance along the line - alpha = 0 will be this
  4890. * vector, and alpha = 1 will be the given one.
  4891. *
  4892. * @param {Vector3} v - The vector to interpolate towards.
  4893. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4894. * @return {Vector3} A reference to this vector.
  4895. */
  4896. lerp( v, alpha ) {
  4897. this.x += ( v.x - this.x ) * alpha;
  4898. this.y += ( v.y - this.y ) * alpha;
  4899. this.z += ( v.z - this.z ) * alpha;
  4900. return this;
  4901. }
  4902. /**
  4903. * Linearly interpolates between the given vectors, where alpha is the percent
  4904. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4905. * be the second one. The result is stored in this instance.
  4906. *
  4907. * @param {Vector3} v1 - The first vector.
  4908. * @param {Vector3} v2 - The second vector.
  4909. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4910. * @return {Vector3} A reference to this vector.
  4911. */
  4912. lerpVectors( v1, v2, alpha ) {
  4913. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4914. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4915. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4916. return this;
  4917. }
  4918. /**
  4919. * Calculates the cross product of the given vector with this instance.
  4920. *
  4921. * @param {Vector3} v - The vector to compute the cross product with.
  4922. * @return {Vector3} The result of the cross product.
  4923. */
  4924. cross( v ) {
  4925. return this.crossVectors( this, v );
  4926. }
  4927. /**
  4928. * Calculates the cross product of the given vectors and stores the result
  4929. * in this instance.
  4930. *
  4931. * @param {Vector3} a - The first vector.
  4932. * @param {Vector3} b - The second vector.
  4933. * @return {Vector3} A reference to this vector.
  4934. */
  4935. crossVectors( a, b ) {
  4936. const ax = a.x, ay = a.y, az = a.z;
  4937. const bx = b.x, by = b.y, bz = b.z;
  4938. this.x = ay * bz - az * by;
  4939. this.y = az * bx - ax * bz;
  4940. this.z = ax * by - ay * bx;
  4941. return this;
  4942. }
  4943. /**
  4944. * Projects this vector onto the given one.
  4945. *
  4946. * @param {Vector3} v - The vector to project to.
  4947. * @return {Vector3} A reference to this vector.
  4948. */
  4949. projectOnVector( v ) {
  4950. const denominator = v.lengthSq();
  4951. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4952. const scalar = v.dot( this ) / denominator;
  4953. return this.copy( v ).multiplyScalar( scalar );
  4954. }
  4955. /**
  4956. * Projects this vector onto a plane by subtracting this
  4957. * vector projected onto the plane's normal from this vector.
  4958. *
  4959. * @param {Vector3} planeNormal - The plane normal.
  4960. * @return {Vector3} A reference to this vector.
  4961. */
  4962. projectOnPlane( planeNormal ) {
  4963. _vector$c.copy( this ).projectOnVector( planeNormal );
  4964. return this.sub( _vector$c );
  4965. }
  4966. /**
  4967. * Reflects this vector off a plane orthogonal to the given normal vector.
  4968. *
  4969. * @param {Vector3} normal - The (normalized) normal vector.
  4970. * @return {Vector3} A reference to this vector.
  4971. */
  4972. reflect( normal ) {
  4973. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4974. }
  4975. /**
  4976. * Returns the angle between the given vector and this instance in radians.
  4977. *
  4978. * @param {Vector3} v - The vector to compute the angle with.
  4979. * @return {number} The angle in radians.
  4980. */
  4981. angleTo( v ) {
  4982. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4983. if ( denominator === 0 ) return Math.PI / 2;
  4984. const theta = this.dot( v ) / denominator;
  4985. // clamp, to handle numerical problems
  4986. return Math.acos( clamp( theta, -1, 1 ) );
  4987. }
  4988. /**
  4989. * Computes the distance from the given vector to this instance.
  4990. *
  4991. * @param {Vector3} v - The vector to compute the distance to.
  4992. * @return {number} The distance.
  4993. */
  4994. distanceTo( v ) {
  4995. return Math.sqrt( this.distanceToSquared( v ) );
  4996. }
  4997. /**
  4998. * Computes the squared distance from the given vector to this instance.
  4999. * If you are just comparing the distance with another distance, you should compare
  5000. * the distance squared instead as it is slightly more efficient to calculate.
  5001. *
  5002. * @param {Vector3} v - The vector to compute the squared distance to.
  5003. * @return {number} The squared distance.
  5004. */
  5005. distanceToSquared( v ) {
  5006. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  5007. return dx * dx + dy * dy + dz * dz;
  5008. }
  5009. /**
  5010. * Computes the Manhattan distance from the given vector to this instance.
  5011. *
  5012. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  5013. * @return {number} The Manhattan distance.
  5014. */
  5015. manhattanDistanceTo( v ) {
  5016. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  5017. }
  5018. /**
  5019. * Sets the vector components from the given spherical coordinates.
  5020. *
  5021. * @param {Spherical} s - The spherical coordinates.
  5022. * @return {Vector3} A reference to this vector.
  5023. */
  5024. setFromSpherical( s ) {
  5025. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  5026. }
  5027. /**
  5028. * Sets the vector components from the given spherical coordinates.
  5029. *
  5030. * @param {number} radius - The radius.
  5031. * @param {number} phi - The phi angle in radians.
  5032. * @param {number} theta - The theta angle in radians.
  5033. * @return {Vector3} A reference to this vector.
  5034. */
  5035. setFromSphericalCoords( radius, phi, theta ) {
  5036. const sinPhiRadius = Math.sin( phi ) * radius;
  5037. this.x = sinPhiRadius * Math.sin( theta );
  5038. this.y = Math.cos( phi ) * radius;
  5039. this.z = sinPhiRadius * Math.cos( theta );
  5040. return this;
  5041. }
  5042. /**
  5043. * Sets the vector components from the given cylindrical coordinates.
  5044. *
  5045. * @param {Cylindrical} c - The cylindrical coordinates.
  5046. * @return {Vector3} A reference to this vector.
  5047. */
  5048. setFromCylindrical( c ) {
  5049. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  5050. }
  5051. /**
  5052. * Sets the vector components from the given cylindrical coordinates.
  5053. *
  5054. * @param {number} radius - The radius.
  5055. * @param {number} theta - The theta angle in radians.
  5056. * @param {number} y - The y value.
  5057. * @return {Vector3} A reference to this vector.
  5058. */
  5059. setFromCylindricalCoords( radius, theta, y ) {
  5060. this.x = radius * Math.sin( theta );
  5061. this.y = y;
  5062. this.z = radius * Math.cos( theta );
  5063. return this;
  5064. }
  5065. /**
  5066. * Sets the vector components to the position elements of the
  5067. * given transformation matrix.
  5068. *
  5069. * @param {Matrix4} m - The 4x4 matrix.
  5070. * @return {Vector3} A reference to this vector.
  5071. */
  5072. setFromMatrixPosition( m ) {
  5073. const e = m.elements;
  5074. this.x = e[ 12 ];
  5075. this.y = e[ 13 ];
  5076. this.z = e[ 14 ];
  5077. return this;
  5078. }
  5079. /**
  5080. * Sets the vector components to the scale elements of the
  5081. * given transformation matrix.
  5082. *
  5083. * @param {Matrix4} m - The 4x4 matrix.
  5084. * @return {Vector3} A reference to this vector.
  5085. */
  5086. setFromMatrixScale( m ) {
  5087. const sx = this.setFromMatrixColumn( m, 0 ).length();
  5088. const sy = this.setFromMatrixColumn( m, 1 ).length();
  5089. const sz = this.setFromMatrixColumn( m, 2 ).length();
  5090. this.x = sx;
  5091. this.y = sy;
  5092. this.z = sz;
  5093. return this;
  5094. }
  5095. /**
  5096. * Sets the vector components from the specified matrix column.
  5097. *
  5098. * @param {Matrix4} m - The 4x4 matrix.
  5099. * @param {number} index - The column index.
  5100. * @return {Vector3} A reference to this vector.
  5101. */
  5102. setFromMatrixColumn( m, index ) {
  5103. return this.fromArray( m.elements, index * 4 );
  5104. }
  5105. /**
  5106. * Sets the vector components from the specified matrix column.
  5107. *
  5108. * @param {Matrix3} m - The 3x3 matrix.
  5109. * @param {number} index - The column index.
  5110. * @return {Vector3} A reference to this vector.
  5111. */
  5112. setFromMatrix3Column( m, index ) {
  5113. return this.fromArray( m.elements, index * 3 );
  5114. }
  5115. /**
  5116. * Sets the vector components from the given Euler angles.
  5117. *
  5118. * @param {Euler} e - The Euler angles to set.
  5119. * @return {Vector3} A reference to this vector.
  5120. */
  5121. setFromEuler( e ) {
  5122. this.x = e._x;
  5123. this.y = e._y;
  5124. this.z = e._z;
  5125. return this;
  5126. }
  5127. /**
  5128. * Sets the vector components from the RGB components of the
  5129. * given color.
  5130. *
  5131. * @param {Color} c - The color to set.
  5132. * @return {Vector3} A reference to this vector.
  5133. */
  5134. setFromColor( c ) {
  5135. this.x = c.r;
  5136. this.y = c.g;
  5137. this.z = c.b;
  5138. return this;
  5139. }
  5140. /**
  5141. * Returns `true` if this vector is equal with the given one.
  5142. *
  5143. * @param {Vector3} v - The vector to test for equality.
  5144. * @return {boolean} Whether this vector is equal with the given one.
  5145. */
  5146. equals( v ) {
  5147. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  5148. }
  5149. /**
  5150. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  5151. * and z value to be `array[ offset + 2 ]`.
  5152. *
  5153. * @param {Array<number>} array - An array holding the vector component values.
  5154. * @param {number} [offset=0] - The offset into the array.
  5155. * @return {Vector3} A reference to this vector.
  5156. */
  5157. fromArray( array, offset = 0 ) {
  5158. this.x = array[ offset ];
  5159. this.y = array[ offset + 1 ];
  5160. this.z = array[ offset + 2 ];
  5161. return this;
  5162. }
  5163. /**
  5164. * Writes the components of this vector to the given array. If no array is provided,
  5165. * the method returns a new instance.
  5166. *
  5167. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  5168. * @param {number} [offset=0] - Index of the first element in the array.
  5169. * @return {Array<number>} The vector components.
  5170. */
  5171. toArray( array = [], offset = 0 ) {
  5172. array[ offset ] = this.x;
  5173. array[ offset + 1 ] = this.y;
  5174. array[ offset + 2 ] = this.z;
  5175. return array;
  5176. }
  5177. /**
  5178. * Sets the components of this vector from the given buffer attribute.
  5179. *
  5180. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  5181. * @param {number} index - The index into the attribute.
  5182. * @return {Vector3} A reference to this vector.
  5183. */
  5184. fromBufferAttribute( attribute, index ) {
  5185. this.x = attribute.getX( index );
  5186. this.y = attribute.getY( index );
  5187. this.z = attribute.getZ( index );
  5188. return this;
  5189. }
  5190. /**
  5191. * Sets each component of this vector to a pseudo-random value between `0` and
  5192. * `1`, excluding `1`.
  5193. *
  5194. * @return {Vector3} A reference to this vector.
  5195. */
  5196. random() {
  5197. this.x = Math.random();
  5198. this.y = Math.random();
  5199. this.z = Math.random();
  5200. return this;
  5201. }
  5202. /**
  5203. * Sets this vector to a uniformly random point on a unit sphere.
  5204. *
  5205. * @return {Vector3} A reference to this vector.
  5206. */
  5207. randomDirection() {
  5208. // https://mathworld.wolfram.com/SpherePointPicking.html
  5209. const theta = Math.random() * Math.PI * 2;
  5210. const u = Math.random() * 2 - 1;
  5211. const c = Math.sqrt( 1 - u * u );
  5212. this.x = c * Math.cos( theta );
  5213. this.y = u;
  5214. this.z = c * Math.sin( theta );
  5215. return this;
  5216. }
  5217. *[ Symbol.iterator ]() {
  5218. yield this.x;
  5219. yield this.y;
  5220. yield this.z;
  5221. }
  5222. }
  5223. const _vector$c = /*@__PURE__*/ new Vector3();
  5224. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  5225. /**
  5226. * Represents an axis-aligned bounding box (AABB) in 3D space.
  5227. */
  5228. class Box3 {
  5229. /**
  5230. * Constructs a new bounding box.
  5231. *
  5232. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  5233. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  5234. */
  5235. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  5236. /**
  5237. * This flag can be used for type testing.
  5238. *
  5239. * @type {boolean}
  5240. * @readonly
  5241. * @default true
  5242. */
  5243. this.isBox3 = true;
  5244. /**
  5245. * The lower boundary of the box.
  5246. *
  5247. * @type {Vector3}
  5248. */
  5249. this.min = min;
  5250. /**
  5251. * The upper boundary of the box.
  5252. *
  5253. * @type {Vector3}
  5254. */
  5255. this.max = max;
  5256. }
  5257. /**
  5258. * Sets the lower and upper boundaries of this box.
  5259. * Please note that this method only copies the values from the given objects.
  5260. *
  5261. * @param {Vector3} min - The lower boundary of the box.
  5262. * @param {Vector3} max - The upper boundary of the box.
  5263. * @return {Box3} A reference to this bounding box.
  5264. */
  5265. set( min, max ) {
  5266. this.min.copy( min );
  5267. this.max.copy( max );
  5268. return this;
  5269. }
  5270. /**
  5271. * Sets the upper and lower bounds of this box so it encloses the position data
  5272. * in the given array.
  5273. *
  5274. * @param {Array<number>} array - An array holding 3D position data.
  5275. * @return {Box3} A reference to this bounding box.
  5276. */
  5277. setFromArray( array ) {
  5278. this.makeEmpty();
  5279. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  5280. this.expandByPoint( _vector$b.fromArray( array, i ) );
  5281. }
  5282. return this;
  5283. }
  5284. /**
  5285. * Sets the upper and lower bounds of this box so it encloses the position data
  5286. * in the given buffer attribute.
  5287. *
  5288. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  5289. * @return {Box3} A reference to this bounding box.
  5290. */
  5291. setFromBufferAttribute( attribute ) {
  5292. this.makeEmpty();
  5293. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  5294. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  5295. }
  5296. return this;
  5297. }
  5298. /**
  5299. * Sets the upper and lower bounds of this box so it encloses the position data
  5300. * in the given array.
  5301. *
  5302. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  5303. * @return {Box3} A reference to this bounding box.
  5304. */
  5305. setFromPoints( points ) {
  5306. this.makeEmpty();
  5307. for ( let i = 0, il = points.length; i < il; i ++ ) {
  5308. this.expandByPoint( points[ i ] );
  5309. }
  5310. return this;
  5311. }
  5312. /**
  5313. * Centers this box on the given center vector and sets this box's width, height and
  5314. * depth to the given size values.
  5315. *
  5316. * @param {Vector3} center - The center of the box.
  5317. * @param {Vector3} size - The x, y and z dimensions of the box.
  5318. * @return {Box3} A reference to this bounding box.
  5319. */
  5320. setFromCenterAndSize( center, size ) {
  5321. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  5322. this.min.copy( center ).sub( halfSize );
  5323. this.max.copy( center ).add( halfSize );
  5324. return this;
  5325. }
  5326. /**
  5327. * Computes the world-axis-aligned bounding box for the given 3D object
  5328. * (including its children), accounting for the object's, and children's,
  5329. * world transforms. The function may result in a larger box than strictly necessary.
  5330. *
  5331. * @param {Object3D} object - The 3D object to compute the bounding box for.
  5332. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  5333. * world-axis-aligned bounding box at the expense of more computation.
  5334. * @return {Box3} A reference to this bounding box.
  5335. */
  5336. setFromObject( object, precise = false ) {
  5337. this.makeEmpty();
  5338. return this.expandByObject( object, precise );
  5339. }
  5340. /**
  5341. * Returns a new box with copied values from this instance.
  5342. *
  5343. * @return {Box3} A clone of this instance.
  5344. */
  5345. clone() {
  5346. return new this.constructor().copy( this );
  5347. }
  5348. /**
  5349. * Copies the values of the given box to this instance.
  5350. *
  5351. * @param {Box3} box - The box to copy.
  5352. * @return {Box3} A reference to this bounding box.
  5353. */
  5354. copy( box ) {
  5355. this.min.copy( box.min );
  5356. this.max.copy( box.max );
  5357. return this;
  5358. }
  5359. /**
  5360. * Makes this box empty which means in encloses a zero space in 3D.
  5361. *
  5362. * @return {Box3} A reference to this bounding box.
  5363. */
  5364. makeEmpty() {
  5365. this.min.x = this.min.y = this.min.z = + Infinity;
  5366. this.max.x = this.max.y = this.max.z = - Infinity;
  5367. return this;
  5368. }
  5369. /**
  5370. * Returns true if this box includes zero points within its bounds.
  5371. * Note that a box with equal lower and upper bounds still includes one
  5372. * point, the one both bounds share.
  5373. *
  5374. * @return {boolean} Whether this box is empty or not.
  5375. */
  5376. isEmpty() {
  5377. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5378. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  5379. }
  5380. /**
  5381. * Returns the center point of this box.
  5382. *
  5383. * @param {Vector3} target - The target vector that is used to store the method's result.
  5384. * @return {Vector3} The center point.
  5385. */
  5386. getCenter( target ) {
  5387. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  5388. }
  5389. /**
  5390. * Returns the dimensions of this box.
  5391. *
  5392. * @param {Vector3} target - The target vector that is used to store the method's result.
  5393. * @return {Vector3} The size.
  5394. */
  5395. getSize( target ) {
  5396. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  5397. }
  5398. /**
  5399. * Expands the boundaries of this box to include the given point.
  5400. *
  5401. * @param {Vector3} point - The point that should be included by the bounding box.
  5402. * @return {Box3} A reference to this bounding box.
  5403. */
  5404. expandByPoint( point ) {
  5405. this.min.min( point );
  5406. this.max.max( point );
  5407. return this;
  5408. }
  5409. /**
  5410. * Expands this box equilaterally by the given vector. The width of this
  5411. * box will be expanded by the x component of the vector in both
  5412. * directions. The height of this box will be expanded by the y component of
  5413. * the vector in both directions. The depth of this box will be
  5414. * expanded by the z component of the vector in both directions.
  5415. *
  5416. * @param {Vector3} vector - The vector that should expand the bounding box.
  5417. * @return {Box3} A reference to this bounding box.
  5418. */
  5419. expandByVector( vector ) {
  5420. this.min.sub( vector );
  5421. this.max.add( vector );
  5422. return this;
  5423. }
  5424. /**
  5425. * Expands each dimension of the box by the given scalar. If negative, the
  5426. * dimensions of the box will be contracted.
  5427. *
  5428. * @param {number} scalar - The scalar value that should expand the bounding box.
  5429. * @return {Box3} A reference to this bounding box.
  5430. */
  5431. expandByScalar( scalar ) {
  5432. this.min.addScalar( - scalar );
  5433. this.max.addScalar( scalar );
  5434. return this;
  5435. }
  5436. /**
  5437. * Expands the boundaries of this box to include the given 3D object and
  5438. * its children, accounting for the object's, and children's, world
  5439. * transforms. The function may result in a larger box than strictly
  5440. * necessary (unless the precise parameter is set to true).
  5441. *
  5442. * @param {Object3D} object - The 3D object that should expand the bounding box.
  5443. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  5444. * as little as necessary at the expense of more computation.
  5445. * @return {Box3} A reference to this bounding box.
  5446. */
  5447. expandByObject( object, precise = false ) {
  5448. // Computes the world-axis-aligned bounding box of an object (including its children),
  5449. // accounting for both the object's, and children's, world transforms
  5450. object.updateWorldMatrix( false, false );
  5451. const geometry = object.geometry;
  5452. if ( geometry !== undefined ) {
  5453. const positionAttribute = geometry.getAttribute( 'position' );
  5454. // precise AABB computation based on vertex data requires at least a position attribute.
  5455. // instancing isn't supported so far and uses the normal (conservative) code path.
  5456. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  5457. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  5458. if ( object.isMesh === true ) {
  5459. object.getVertexPosition( i, _vector$b );
  5460. } else {
  5461. _vector$b.fromBufferAttribute( positionAttribute, i );
  5462. }
  5463. _vector$b.applyMatrix4( object.matrixWorld );
  5464. this.expandByPoint( _vector$b );
  5465. }
  5466. } else {
  5467. if ( object.boundingBox !== undefined ) {
  5468. // object-level bounding box
  5469. if ( object.boundingBox === null ) {
  5470. object.computeBoundingBox();
  5471. }
  5472. _box$4.copy( object.boundingBox );
  5473. } else {
  5474. // geometry-level bounding box
  5475. if ( geometry.boundingBox === null ) {
  5476. geometry.computeBoundingBox();
  5477. }
  5478. _box$4.copy( geometry.boundingBox );
  5479. }
  5480. _box$4.applyMatrix4( object.matrixWorld );
  5481. this.union( _box$4 );
  5482. }
  5483. }
  5484. const children = object.children;
  5485. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5486. this.expandByObject( children[ i ], precise );
  5487. }
  5488. return this;
  5489. }
  5490. /**
  5491. * Returns `true` if the given point lies within or on the boundaries of this box.
  5492. *
  5493. * @param {Vector3} point - The point to test.
  5494. * @return {boolean} Whether the bounding box contains the given point or not.
  5495. */
  5496. containsPoint( point ) {
  5497. return point.x >= this.min.x && point.x <= this.max.x &&
  5498. point.y >= this.min.y && point.y <= this.max.y &&
  5499. point.z >= this.min.z && point.z <= this.max.z;
  5500. }
  5501. /**
  5502. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  5503. * If this box and the given one are identical, this function also returns `true`.
  5504. *
  5505. * @param {Box3} box - The bounding box to test.
  5506. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  5507. */
  5508. containsBox( box ) {
  5509. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  5510. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  5511. this.min.z <= box.min.z && box.max.z <= this.max.z;
  5512. }
  5513. /**
  5514. * Returns a point as a proportion of this box's width, height and depth.
  5515. *
  5516. * @param {Vector3} point - A point in 3D space.
  5517. * @param {Vector3} target - The target vector that is used to store the method's result.
  5518. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  5519. */
  5520. getParameter( point, target ) {
  5521. // This can potentially have a divide by zero if the box
  5522. // has a size dimension of 0.
  5523. return target.set(
  5524. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  5525. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  5526. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  5527. );
  5528. }
  5529. /**
  5530. * Returns `true` if the given bounding box intersects with this bounding box.
  5531. *
  5532. * @param {Box3} box - The bounding box to test.
  5533. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  5534. */
  5535. intersectsBox( box ) {
  5536. // using 6 splitting planes to rule out intersections.
  5537. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  5538. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  5539. box.max.z >= this.min.z && box.min.z <= this.max.z;
  5540. }
  5541. /**
  5542. * Returns `true` if the given bounding sphere intersects with this bounding box.
  5543. *
  5544. * @param {Sphere} sphere - The bounding sphere to test.
  5545. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  5546. */
  5547. intersectsSphere( sphere ) {
  5548. // Find the point on the AABB closest to the sphere center.
  5549. this.clampPoint( sphere.center, _vector$b );
  5550. // If that point is inside the sphere, the AABB and sphere intersect.
  5551. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  5552. }
  5553. /**
  5554. * Returns `true` if the given plane intersects with this bounding box.
  5555. *
  5556. * @param {Plane} plane - The plane to test.
  5557. * @return {boolean} Whether the given plane intersects with this bounding box.
  5558. */
  5559. intersectsPlane( plane ) {
  5560. // We compute the minimum and maximum dot product values. If those values
  5561. // are on the same side (back or front) of the plane, then there is no intersection.
  5562. let min, max;
  5563. if ( plane.normal.x > 0 ) {
  5564. min = plane.normal.x * this.min.x;
  5565. max = plane.normal.x * this.max.x;
  5566. } else {
  5567. min = plane.normal.x * this.max.x;
  5568. max = plane.normal.x * this.min.x;
  5569. }
  5570. if ( plane.normal.y > 0 ) {
  5571. min += plane.normal.y * this.min.y;
  5572. max += plane.normal.y * this.max.y;
  5573. } else {
  5574. min += plane.normal.y * this.max.y;
  5575. max += plane.normal.y * this.min.y;
  5576. }
  5577. if ( plane.normal.z > 0 ) {
  5578. min += plane.normal.z * this.min.z;
  5579. max += plane.normal.z * this.max.z;
  5580. } else {
  5581. min += plane.normal.z * this.max.z;
  5582. max += plane.normal.z * this.min.z;
  5583. }
  5584. return ( min <= - plane.constant && max >= - plane.constant );
  5585. }
  5586. /**
  5587. * Returns `true` if the given triangle intersects with this bounding box.
  5588. *
  5589. * @param {Triangle} triangle - The triangle to test.
  5590. * @return {boolean} Whether the given triangle intersects with this bounding box.
  5591. */
  5592. intersectsTriangle( triangle ) {
  5593. if ( this.isEmpty() ) {
  5594. return false;
  5595. }
  5596. // compute box center and extents
  5597. this.getCenter( _center );
  5598. _extents.subVectors( this.max, _center );
  5599. // translate triangle to aabb origin
  5600. _v0$3.subVectors( triangle.a, _center );
  5601. _v1$7.subVectors( triangle.b, _center );
  5602. _v2$4.subVectors( triangle.c, _center );
  5603. // compute edge vectors for triangle
  5604. _f0.subVectors( _v1$7, _v0$3 );
  5605. _f1.subVectors( _v2$4, _v1$7 );
  5606. _f2.subVectors( _v0$3, _v2$4 );
  5607. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  5608. // 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
  5609. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  5610. let axes = [
  5611. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  5612. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  5613. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  5614. ];
  5615. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  5616. return false;
  5617. }
  5618. // test 3 face normals from the aabb
  5619. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  5620. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  5621. return false;
  5622. }
  5623. // finally testing the face normal of the triangle
  5624. // use already existing triangle edge vectors here
  5625. _triangleNormal.crossVectors( _f0, _f1 );
  5626. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  5627. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  5628. }
  5629. /**
  5630. * Clamps the given point within the bounds of this box.
  5631. *
  5632. * @param {Vector3} point - The point to clamp.
  5633. * @param {Vector3} target - The target vector that is used to store the method's result.
  5634. * @return {Vector3} The clamped point.
  5635. */
  5636. clampPoint( point, target ) {
  5637. return target.copy( point ).clamp( this.min, this.max );
  5638. }
  5639. /**
  5640. * Returns the euclidean distance from any edge of this box to the specified point. If
  5641. * the given point lies inside of this box, the distance will be `0`.
  5642. *
  5643. * @param {Vector3} point - The point to compute the distance to.
  5644. * @return {number} The euclidean distance.
  5645. */
  5646. distanceToPoint( point ) {
  5647. return this.clampPoint( point, _vector$b ).distanceTo( point );
  5648. }
  5649. /**
  5650. * Returns a bounding sphere that encloses this bounding box.
  5651. *
  5652. * @param {Sphere} target - The target sphere that is used to store the method's result.
  5653. * @return {Sphere} The bounding sphere that encloses this bounding box.
  5654. */
  5655. getBoundingSphere( target ) {
  5656. if ( this.isEmpty() ) {
  5657. target.makeEmpty();
  5658. } else {
  5659. this.getCenter( target.center );
  5660. target.radius = this.getSize( _vector$b ).length() * 0.5;
  5661. }
  5662. return target;
  5663. }
  5664. /**
  5665. * Computes the intersection of this bounding box and the given one, setting the upper
  5666. * bound of this box to the lesser of the two boxes' upper bounds and the
  5667. * lower bound of this box to the greater of the two boxes' lower bounds. If
  5668. * there's no overlap, makes this box empty.
  5669. *
  5670. * @param {Box3} box - The bounding box to intersect with.
  5671. * @return {Box3} A reference to this bounding box.
  5672. */
  5673. intersect( box ) {
  5674. this.min.max( box.min );
  5675. this.max.min( box.max );
  5676. // 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.
  5677. if ( this.isEmpty() ) this.makeEmpty();
  5678. return this;
  5679. }
  5680. /**
  5681. * Computes the union of this box and another and the given one, setting the upper
  5682. * bound of this box to the greater of the two boxes' upper bounds and the
  5683. * lower bound of this box to the lesser of the two boxes' lower bounds.
  5684. *
  5685. * @param {Box3} box - The bounding box that will be unioned with this instance.
  5686. * @return {Box3} A reference to this bounding box.
  5687. */
  5688. union( box ) {
  5689. this.min.min( box.min );
  5690. this.max.max( box.max );
  5691. return this;
  5692. }
  5693. /**
  5694. * Transforms this bounding box by the given 4x4 transformation matrix.
  5695. *
  5696. * @param {Matrix4} matrix - The transformation matrix.
  5697. * @return {Box3} A reference to this bounding box.
  5698. */
  5699. applyMatrix4( matrix ) {
  5700. // transform of empty box is an empty box.
  5701. if ( this.isEmpty() ) return this;
  5702. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5703. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5704. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5705. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5706. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5707. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5708. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5709. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5710. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5711. this.setFromPoints( _points );
  5712. return this;
  5713. }
  5714. /**
  5715. * Adds the given offset to both the upper and lower bounds of this bounding box,
  5716. * effectively moving it in 3D space.
  5717. *
  5718. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  5719. * @return {Box3} A reference to this bounding box.
  5720. */
  5721. translate( offset ) {
  5722. this.min.add( offset );
  5723. this.max.add( offset );
  5724. return this;
  5725. }
  5726. /**
  5727. * Returns `true` if this bounding box is equal with the given one.
  5728. *
  5729. * @param {Box3} box - The box to test for equality.
  5730. * @return {boolean} Whether this bounding box is equal with the given one.
  5731. */
  5732. equals( box ) {
  5733. return box.min.equals( this.min ) && box.max.equals( this.max );
  5734. }
  5735. }
  5736. const _points = [
  5737. /*@__PURE__*/ new Vector3(),
  5738. /*@__PURE__*/ new Vector3(),
  5739. /*@__PURE__*/ new Vector3(),
  5740. /*@__PURE__*/ new Vector3(),
  5741. /*@__PURE__*/ new Vector3(),
  5742. /*@__PURE__*/ new Vector3(),
  5743. /*@__PURE__*/ new Vector3(),
  5744. /*@__PURE__*/ new Vector3()
  5745. ];
  5746. const _vector$b = /*@__PURE__*/ new Vector3();
  5747. const _box$4 = /*@__PURE__*/ new Box3();
  5748. // triangle centered vertices
  5749. const _v0$3 = /*@__PURE__*/ new Vector3();
  5750. const _v1$7 = /*@__PURE__*/ new Vector3();
  5751. const _v2$4 = /*@__PURE__*/ new Vector3();
  5752. // triangle edge vectors
  5753. const _f0 = /*@__PURE__*/ new Vector3();
  5754. const _f1 = /*@__PURE__*/ new Vector3();
  5755. const _f2 = /*@__PURE__*/ new Vector3();
  5756. const _center = /*@__PURE__*/ new Vector3();
  5757. const _extents = /*@__PURE__*/ new Vector3();
  5758. const _triangleNormal = /*@__PURE__*/ new Vector3();
  5759. const _testAxis = /*@__PURE__*/ new Vector3();
  5760. function satForAxes( axes, v0, v1, v2, extents ) {
  5761. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  5762. _testAxis.fromArray( axes, i );
  5763. // project the aabb onto the separating axis
  5764. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  5765. // project all 3 vertices of the triangle onto the separating axis
  5766. const p0 = v0.dot( _testAxis );
  5767. const p1 = v1.dot( _testAxis );
  5768. const p2 = v2.dot( _testAxis );
  5769. // actual test, basically see if either of the most extreme of the triangle points intersects r
  5770. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  5771. // points of the projected triangle are outside the projected half-length of the aabb
  5772. // the axis is separating and we can exit
  5773. return false;
  5774. }
  5775. }
  5776. return true;
  5777. }
  5778. const _box$3 = /*@__PURE__*/ new Box3();
  5779. const _v1$6 = /*@__PURE__*/ new Vector3();
  5780. const _v2$3 = /*@__PURE__*/ new Vector3();
  5781. /**
  5782. * An analytical 3D sphere defined by a center and radius. This class is mainly
  5783. * used as a Bounding Sphere for 3D objects.
  5784. */
  5785. class Sphere {
  5786. /**
  5787. * Constructs a new sphere.
  5788. *
  5789. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  5790. * @param {number} [radius=-1] - The radius of the sphere.
  5791. */
  5792. constructor( center = new Vector3(), radius = -1 ) {
  5793. /**
  5794. * This flag can be used for type testing.
  5795. *
  5796. * @type {boolean}
  5797. * @readonly
  5798. * @default true
  5799. */
  5800. this.isSphere = true;
  5801. /**
  5802. * The center of the sphere
  5803. *
  5804. * @type {Vector3}
  5805. */
  5806. this.center = center;
  5807. /**
  5808. * The radius of the sphere.
  5809. *
  5810. * @type {number}
  5811. */
  5812. this.radius = radius;
  5813. }
  5814. /**
  5815. * Sets the sphere's components by copying the given values.
  5816. *
  5817. * @param {Vector3} center - The center.
  5818. * @param {number} radius - The radius.
  5819. * @return {Sphere} A reference to this sphere.
  5820. */
  5821. set( center, radius ) {
  5822. this.center.copy( center );
  5823. this.radius = radius;
  5824. return this;
  5825. }
  5826. /**
  5827. * Computes the minimum bounding sphere for list of points.
  5828. * If the optional center point is given, it is used as the sphere's
  5829. * center. Otherwise, the center of the axis-aligned bounding box
  5830. * encompassing the points is calculated.
  5831. *
  5832. * @param {Array<Vector3>} points - A list of points in 3D space.
  5833. * @param {Vector3} [optionalCenter] - The center of the sphere.
  5834. * @return {Sphere} A reference to this sphere.
  5835. */
  5836. setFromPoints( points, optionalCenter ) {
  5837. const center = this.center;
  5838. if ( optionalCenter !== undefined ) {
  5839. center.copy( optionalCenter );
  5840. } else {
  5841. _box$3.setFromPoints( points ).getCenter( center );
  5842. }
  5843. let maxRadiusSq = 0;
  5844. for ( let i = 0, il = points.length; i < il; i ++ ) {
  5845. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5846. }
  5847. this.radius = Math.sqrt( maxRadiusSq );
  5848. return this;
  5849. }
  5850. /**
  5851. * Copies the values of the given sphere to this instance.
  5852. *
  5853. * @param {Sphere} sphere - The sphere to copy.
  5854. * @return {Sphere} A reference to this sphere.
  5855. */
  5856. copy( sphere ) {
  5857. this.center.copy( sphere.center );
  5858. this.radius = sphere.radius;
  5859. return this;
  5860. }
  5861. /**
  5862. * Returns `true` if the sphere is empty (the radius set to a negative number).
  5863. *
  5864. * Spheres with a radius of `0` contain only their center point and are not
  5865. * considered to be empty.
  5866. *
  5867. * @return {boolean} Whether this sphere is empty or not.
  5868. */
  5869. isEmpty() {
  5870. return ( this.radius < 0 );
  5871. }
  5872. /**
  5873. * Makes this sphere empty which means in encloses a zero space in 3D.
  5874. *
  5875. * @return {Sphere} A reference to this sphere.
  5876. */
  5877. makeEmpty() {
  5878. this.center.set( 0, 0, 0 );
  5879. this.radius = -1;
  5880. return this;
  5881. }
  5882. /**
  5883. * Returns `true` if this sphere contains the given point inclusive of
  5884. * the surface of the sphere.
  5885. *
  5886. * @param {Vector3} point - The point to check.
  5887. * @return {boolean} Whether this sphere contains the given point or not.
  5888. */
  5889. containsPoint( point ) {
  5890. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5891. }
  5892. /**
  5893. * Returns the closest distance from the boundary of the sphere to the
  5894. * given point. If the sphere contains the point, the distance will
  5895. * be negative.
  5896. *
  5897. * @param {Vector3} point - The point to compute the distance to.
  5898. * @return {number} The distance to the point.
  5899. */
  5900. distanceToPoint( point ) {
  5901. return ( point.distanceTo( this.center ) - this.radius );
  5902. }
  5903. /**
  5904. * Returns `true` if this sphere intersects with the given one.
  5905. *
  5906. * @param {Sphere} sphere - The sphere to test.
  5907. * @return {boolean} Whether this sphere intersects with the given one or not.
  5908. */
  5909. intersectsSphere( sphere ) {
  5910. const radiusSum = this.radius + sphere.radius;
  5911. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5912. }
  5913. /**
  5914. * Returns `true` if this sphere intersects with the given box.
  5915. *
  5916. * @param {Box3} box - The box to test.
  5917. * @return {boolean} Whether this sphere intersects with the given box or not.
  5918. */
  5919. intersectsBox( box ) {
  5920. return box.intersectsSphere( this );
  5921. }
  5922. /**
  5923. * Returns `true` if this sphere intersects with the given plane.
  5924. *
  5925. * @param {Plane} plane - The plane to test.
  5926. * @return {boolean} Whether this sphere intersects with the given plane or not.
  5927. */
  5928. intersectsPlane( plane ) {
  5929. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  5930. }
  5931. /**
  5932. * Clamps a point within the sphere. If the point is outside the sphere, it
  5933. * will clamp it to the closest point on the edge of the sphere. Points
  5934. * already inside the sphere will not be affected.
  5935. *
  5936. * @param {Vector3} point - The plane to clamp.
  5937. * @param {Vector3} target - The target vector that is used to store the method's result.
  5938. * @return {Vector3} The clamped point.
  5939. */
  5940. clampPoint( point, target ) {
  5941. const deltaLengthSq = this.center.distanceToSquared( point );
  5942. target.copy( point );
  5943. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5944. target.sub( this.center ).normalize();
  5945. target.multiplyScalar( this.radius ).add( this.center );
  5946. }
  5947. return target;
  5948. }
  5949. /**
  5950. * Returns a bounding box that encloses this sphere.
  5951. *
  5952. * @param {Box3} target - The target box that is used to store the method's result.
  5953. * @return {Box3} The bounding box that encloses this sphere.
  5954. */
  5955. getBoundingBox( target ) {
  5956. if ( this.isEmpty() ) {
  5957. // Empty sphere produces empty bounding box
  5958. target.makeEmpty();
  5959. return target;
  5960. }
  5961. target.set( this.center, this.center );
  5962. target.expandByScalar( this.radius );
  5963. return target;
  5964. }
  5965. /**
  5966. * Transforms this sphere with the given 4x4 transformation matrix.
  5967. *
  5968. * @param {Matrix4} matrix - The transformation matrix.
  5969. * @return {Sphere} A reference to this sphere.
  5970. */
  5971. applyMatrix4( matrix ) {
  5972. this.center.applyMatrix4( matrix );
  5973. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5974. return this;
  5975. }
  5976. /**
  5977. * Translates the sphere's center by the given offset.
  5978. *
  5979. * @param {Vector3} offset - The offset.
  5980. * @return {Sphere} A reference to this sphere.
  5981. */
  5982. translate( offset ) {
  5983. this.center.add( offset );
  5984. return this;
  5985. }
  5986. /**
  5987. * Expands the boundaries of this sphere to include the given point.
  5988. *
  5989. * @param {Vector3} point - The point to include.
  5990. * @return {Sphere} A reference to this sphere.
  5991. */
  5992. expandByPoint( point ) {
  5993. if ( this.isEmpty() ) {
  5994. this.center.copy( point );
  5995. this.radius = 0;
  5996. return this;
  5997. }
  5998. _v1$6.subVectors( point, this.center );
  5999. const lengthSq = _v1$6.lengthSq();
  6000. if ( lengthSq > ( this.radius * this.radius ) ) {
  6001. // calculate the minimal sphere
  6002. const length = Math.sqrt( lengthSq );
  6003. const delta = ( length - this.radius ) * 0.5;
  6004. this.center.addScaledVector( _v1$6, delta / length );
  6005. this.radius += delta;
  6006. }
  6007. return this;
  6008. }
  6009. /**
  6010. * Expands this sphere to enclose both the original sphere and the given sphere.
  6011. *
  6012. * @param {Sphere} sphere - The sphere to include.
  6013. * @return {Sphere} A reference to this sphere.
  6014. */
  6015. union( sphere ) {
  6016. if ( sphere.isEmpty() ) {
  6017. return this;
  6018. }
  6019. if ( this.isEmpty() ) {
  6020. this.copy( sphere );
  6021. return this;
  6022. }
  6023. if ( this.center.equals( sphere.center ) === true ) {
  6024. this.radius = Math.max( this.radius, sphere.radius );
  6025. } else {
  6026. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  6027. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  6028. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  6029. }
  6030. return this;
  6031. }
  6032. /**
  6033. * Returns `true` if this sphere is equal with the given one.
  6034. *
  6035. * @param {Sphere} sphere - The sphere to test for equality.
  6036. * @return {boolean} Whether this bounding sphere is equal with the given one.
  6037. */
  6038. equals( sphere ) {
  6039. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  6040. }
  6041. /**
  6042. * Returns a new sphere with copied values from this instance.
  6043. *
  6044. * @return {Sphere} A clone of this instance.
  6045. */
  6046. clone() {
  6047. return new this.constructor().copy( this );
  6048. }
  6049. }
  6050. const _vector$a = /*@__PURE__*/ new Vector3();
  6051. const _segCenter = /*@__PURE__*/ new Vector3();
  6052. const _segDir = /*@__PURE__*/ new Vector3();
  6053. const _diff = /*@__PURE__*/ new Vector3();
  6054. const _edge1 = /*@__PURE__*/ new Vector3();
  6055. const _edge2 = /*@__PURE__*/ new Vector3();
  6056. const _normal$1 = /*@__PURE__*/ new Vector3();
  6057. /**
  6058. * A ray that emits from an origin in a certain direction. The class is used by
  6059. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  6060. * mouse picking (working out what objects in the 3D space the mouse is over)
  6061. * amongst other things.
  6062. */
  6063. class Ray {
  6064. /**
  6065. * Constructs a new ray.
  6066. *
  6067. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  6068. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  6069. */
  6070. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  6071. /**
  6072. * The origin of the ray.
  6073. *
  6074. * @type {Vector3}
  6075. */
  6076. this.origin = origin;
  6077. /**
  6078. * The (normalized) direction of the ray.
  6079. *
  6080. * @type {Vector3}
  6081. */
  6082. this.direction = direction;
  6083. }
  6084. /**
  6085. * Sets the ray's components by copying the given values.
  6086. *
  6087. * @param {Vector3} origin - The origin.
  6088. * @param {Vector3} direction - The direction.
  6089. * @return {Ray} A reference to this ray.
  6090. */
  6091. set( origin, direction ) {
  6092. this.origin.copy( origin );
  6093. this.direction.copy( direction );
  6094. return this;
  6095. }
  6096. /**
  6097. * Copies the values of the given ray to this instance.
  6098. *
  6099. * @param {Ray} ray - The ray to copy.
  6100. * @return {Ray} A reference to this ray.
  6101. */
  6102. copy( ray ) {
  6103. this.origin.copy( ray.origin );
  6104. this.direction.copy( ray.direction );
  6105. return this;
  6106. }
  6107. /**
  6108. * Returns a vector that is located at a given distance along this ray.
  6109. *
  6110. * @param {number} t - The distance along the ray to retrieve a position for.
  6111. * @param {Vector3} target - The target vector that is used to store the method's result.
  6112. * @return {Vector3} A position on the ray.
  6113. */
  6114. at( t, target ) {
  6115. return target.copy( this.origin ).addScaledVector( this.direction, t );
  6116. }
  6117. /**
  6118. * Adjusts the direction of the ray to point at the given vector in world space.
  6119. *
  6120. * @param {Vector3} v - The target position.
  6121. * @return {Ray} A reference to this ray.
  6122. */
  6123. lookAt( v ) {
  6124. this.direction.copy( v ).sub( this.origin ).normalize();
  6125. return this;
  6126. }
  6127. /**
  6128. * Shift the origin of this ray along its direction by the given distance.
  6129. *
  6130. * @param {number} t - The distance along the ray to interpolate.
  6131. * @return {Ray} A reference to this ray.
  6132. */
  6133. recast( t ) {
  6134. this.origin.copy( this.at( t, _vector$a ) );
  6135. return this;
  6136. }
  6137. /**
  6138. * Returns the point along this ray that is closest to the given point.
  6139. *
  6140. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  6141. * @param {Vector3} target - The target vector that is used to store the method's result.
  6142. * @return {Vector3} The closest point on this ray.
  6143. */
  6144. closestPointToPoint( point, target ) {
  6145. target.subVectors( point, this.origin );
  6146. const directionDistance = target.dot( this.direction );
  6147. if ( directionDistance < 0 ) {
  6148. return target.copy( this.origin );
  6149. }
  6150. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  6151. }
  6152. /**
  6153. * Returns the distance of the closest approach between this ray and the given point.
  6154. *
  6155. * @param {Vector3} point - A point in 3D space to compute the distance to.
  6156. * @return {number} The distance.
  6157. */
  6158. distanceToPoint( point ) {
  6159. return Math.sqrt( this.distanceSqToPoint( point ) );
  6160. }
  6161. /**
  6162. * Returns the squared distance of the closest approach between this ray and the given point.
  6163. *
  6164. * @param {Vector3} point - A point in 3D space to compute the distance to.
  6165. * @return {number} The squared distance.
  6166. */
  6167. distanceSqToPoint( point ) {
  6168. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  6169. // point behind the ray
  6170. if ( directionDistance < 0 ) {
  6171. return this.origin.distanceToSquared( point );
  6172. }
  6173. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  6174. return _vector$a.distanceToSquared( point );
  6175. }
  6176. /**
  6177. * Returns the squared distance between this ray and the given line segment.
  6178. *
  6179. * @param {Vector3} v0 - The start point of the line segment.
  6180. * @param {Vector3} v1 - The end point of the line segment.
  6181. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  6182. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  6183. * @return {number} The squared distance.
  6184. */
  6185. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  6186. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  6187. // It returns the min distance between the ray and the segment
  6188. // defined by v0 and v1
  6189. // It can also set two optional targets :
  6190. // - The closest point on the ray
  6191. // - The closest point on the segment
  6192. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  6193. _segDir.copy( v1 ).sub( v0 ).normalize();
  6194. _diff.copy( this.origin ).sub( _segCenter );
  6195. const segExtent = v0.distanceTo( v1 ) * 0.5;
  6196. const a01 = - this.direction.dot( _segDir );
  6197. const b0 = _diff.dot( this.direction );
  6198. const b1 = - _diff.dot( _segDir );
  6199. const c = _diff.lengthSq();
  6200. const det = Math.abs( 1 - a01 * a01 );
  6201. let s0, s1, sqrDist, extDet;
  6202. if ( det > 0 ) {
  6203. // The ray and segment are not parallel.
  6204. s0 = a01 * b1 - b0;
  6205. s1 = a01 * b0 - b1;
  6206. extDet = segExtent * det;
  6207. if ( s0 >= 0 ) {
  6208. if ( s1 >= - extDet ) {
  6209. if ( s1 <= extDet ) {
  6210. // region 0
  6211. // Minimum at interior points of ray and segment.
  6212. const invDet = 1 / det;
  6213. s0 *= invDet;
  6214. s1 *= invDet;
  6215. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  6216. } else {
  6217. // region 1
  6218. s1 = segExtent;
  6219. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6220. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6221. }
  6222. } else {
  6223. // region 5
  6224. s1 = - segExtent;
  6225. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6226. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6227. }
  6228. } else {
  6229. if ( s1 <= - extDet ) {
  6230. // region 4
  6231. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  6232. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6233. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6234. } else if ( s1 <= extDet ) {
  6235. // region 3
  6236. s0 = 0;
  6237. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6238. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  6239. } else {
  6240. // region 2
  6241. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  6242. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6243. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6244. }
  6245. }
  6246. } else {
  6247. // Ray and segment are parallel.
  6248. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  6249. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6250. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6251. }
  6252. if ( optionalPointOnRay ) {
  6253. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  6254. }
  6255. if ( optionalPointOnSegment ) {
  6256. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  6257. }
  6258. return sqrDist;
  6259. }
  6260. /**
  6261. * Intersects this ray with the given sphere, returning the intersection
  6262. * point or `null` if there is no intersection.
  6263. *
  6264. * @param {Sphere} sphere - The sphere to intersect.
  6265. * @param {Vector3} target - The target vector that is used to store the method's result.
  6266. * @return {?Vector3} The intersection point.
  6267. */
  6268. intersectSphere( sphere, target ) {
  6269. _vector$a.subVectors( sphere.center, this.origin );
  6270. const tca = _vector$a.dot( this.direction );
  6271. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  6272. const radius2 = sphere.radius * sphere.radius;
  6273. if ( d2 > radius2 ) return null;
  6274. const thc = Math.sqrt( radius2 - d2 );
  6275. // t0 = first intersect point - entrance on front of sphere
  6276. const t0 = tca - thc;
  6277. // t1 = second intersect point - exit point on back of sphere
  6278. const t1 = tca + thc;
  6279. // test to see if t1 is behind the ray - if so, return null
  6280. if ( t1 < 0 ) return null;
  6281. // test to see if t0 is behind the ray:
  6282. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6283. // in order to always return an intersect point that is in front of the ray.
  6284. if ( t0 < 0 ) return this.at( t1, target );
  6285. // else t0 is in front of the ray, so return the first collision point scaled by t0
  6286. return this.at( t0, target );
  6287. }
  6288. /**
  6289. * Returns `true` if this ray intersects with the given sphere.
  6290. *
  6291. * @param {Sphere} sphere - The sphere to intersect.
  6292. * @return {boolean} Whether this ray intersects with the given sphere or not.
  6293. */
  6294. intersectsSphere( sphere ) {
  6295. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  6296. }
  6297. /**
  6298. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  6299. * does not intersect with the plane.
  6300. *
  6301. * @param {Plane} plane - The plane to compute the distance to.
  6302. * @return {?number} Whether this ray intersects with the given sphere or not.
  6303. */
  6304. distanceToPlane( plane ) {
  6305. const denominator = plane.normal.dot( this.direction );
  6306. if ( denominator === 0 ) {
  6307. // line is coplanar, return origin
  6308. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  6309. return 0;
  6310. }
  6311. // Null is preferable to undefined since undefined means.... it is undefined
  6312. return null;
  6313. }
  6314. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  6315. // Return if the ray never intersects the plane
  6316. return t >= 0 ? t : null;
  6317. }
  6318. /**
  6319. * Intersects this ray with the given plane, returning the intersection
  6320. * point or `null` if there is no intersection.
  6321. *
  6322. * @param {Plane} plane - The plane to intersect.
  6323. * @param {Vector3} target - The target vector that is used to store the method's result.
  6324. * @return {?Vector3} The intersection point.
  6325. */
  6326. intersectPlane( plane, target ) {
  6327. const t = this.distanceToPlane( plane );
  6328. if ( t === null ) {
  6329. return null;
  6330. }
  6331. return this.at( t, target );
  6332. }
  6333. /**
  6334. * Returns `true` if this ray intersects with the given plane.
  6335. *
  6336. * @param {Plane} plane - The plane to intersect.
  6337. * @return {boolean} Whether this ray intersects with the given plane or not.
  6338. */
  6339. intersectsPlane( plane ) {
  6340. // check if the ray lies on the plane first
  6341. const distToPoint = plane.distanceToPoint( this.origin );
  6342. if ( distToPoint === 0 ) {
  6343. return true;
  6344. }
  6345. const denominator = plane.normal.dot( this.direction );
  6346. if ( denominator * distToPoint < 0 ) {
  6347. return true;
  6348. }
  6349. // ray origin is behind the plane (and is pointing behind it)
  6350. return false;
  6351. }
  6352. /**
  6353. * Intersects this ray with the given bounding box, returning the intersection
  6354. * point or `null` if there is no intersection.
  6355. *
  6356. * @param {Box3} box - The box to intersect.
  6357. * @param {Vector3} target - The target vector that is used to store the method's result.
  6358. * @return {?Vector3} The intersection point.
  6359. */
  6360. intersectBox( box, target ) {
  6361. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  6362. const invdirx = 1 / this.direction.x,
  6363. invdiry = 1 / this.direction.y,
  6364. invdirz = 1 / this.direction.z;
  6365. const origin = this.origin;
  6366. if ( invdirx >= 0 ) {
  6367. tmin = ( box.min.x - origin.x ) * invdirx;
  6368. tmax = ( box.max.x - origin.x ) * invdirx;
  6369. } else {
  6370. tmin = ( box.max.x - origin.x ) * invdirx;
  6371. tmax = ( box.min.x - origin.x ) * invdirx;
  6372. }
  6373. if ( invdiry >= 0 ) {
  6374. tymin = ( box.min.y - origin.y ) * invdiry;
  6375. tymax = ( box.max.y - origin.y ) * invdiry;
  6376. } else {
  6377. tymin = ( box.max.y - origin.y ) * invdiry;
  6378. tymax = ( box.min.y - origin.y ) * invdiry;
  6379. }
  6380. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  6381. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  6382. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  6383. if ( invdirz >= 0 ) {
  6384. tzmin = ( box.min.z - origin.z ) * invdirz;
  6385. tzmax = ( box.max.z - origin.z ) * invdirz;
  6386. } else {
  6387. tzmin = ( box.max.z - origin.z ) * invdirz;
  6388. tzmax = ( box.min.z - origin.z ) * invdirz;
  6389. }
  6390. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  6391. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  6392. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  6393. //return point closest to the ray (positive side)
  6394. if ( tmax < 0 ) return null;
  6395. return this.at( tmin >= 0 ? tmin : tmax, target );
  6396. }
  6397. /**
  6398. * Returns `true` if this ray intersects with the given box.
  6399. *
  6400. * @param {Box3} box - The box to intersect.
  6401. * @return {boolean} Whether this ray intersects with the given box or not.
  6402. */
  6403. intersectsBox( box ) {
  6404. return this.intersectBox( box, _vector$a ) !== null;
  6405. }
  6406. /**
  6407. * Intersects this ray with the given triangle, returning the intersection
  6408. * point or `null` if there is no intersection.
  6409. *
  6410. * @param {Vector3} a - The first vertex of the triangle.
  6411. * @param {Vector3} b - The second vertex of the triangle.
  6412. * @param {Vector3} c - The third vertex of the triangle.
  6413. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  6414. * @param {Vector3} target - The target vector that is used to store the method's result.
  6415. * @return {?Vector3} The intersection point.
  6416. */
  6417. intersectTriangle( a, b, c, backfaceCulling, target ) {
  6418. // Compute the offset origin, edges, and normal.
  6419. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6420. _edge1.subVectors( b, a );
  6421. _edge2.subVectors( c, a );
  6422. _normal$1.crossVectors( _edge1, _edge2 );
  6423. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6424. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6425. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6426. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6427. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6428. let DdN = this.direction.dot( _normal$1 );
  6429. let sign;
  6430. if ( DdN > 0 ) {
  6431. if ( backfaceCulling ) return null;
  6432. sign = 1;
  6433. } else if ( DdN < 0 ) {
  6434. sign = -1;
  6435. DdN = - DdN;
  6436. } else {
  6437. return null;
  6438. }
  6439. _diff.subVectors( this.origin, a );
  6440. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  6441. // b1 < 0, no intersection
  6442. if ( DdQxE2 < 0 ) {
  6443. return null;
  6444. }
  6445. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  6446. // b2 < 0, no intersection
  6447. if ( DdE1xQ < 0 ) {
  6448. return null;
  6449. }
  6450. // b1+b2 > 1, no intersection
  6451. if ( DdQxE2 + DdE1xQ > DdN ) {
  6452. return null;
  6453. }
  6454. // Line intersects triangle, check if ray does.
  6455. const QdN = - sign * _diff.dot( _normal$1 );
  6456. // t < 0, no intersection
  6457. if ( QdN < 0 ) {
  6458. return null;
  6459. }
  6460. // Ray intersects triangle.
  6461. return this.at( QdN / DdN, target );
  6462. }
  6463. /**
  6464. * Transforms this ray with the given 4x4 transformation matrix.
  6465. *
  6466. * @param {Matrix4} matrix4 - The transformation matrix.
  6467. * @return {Ray} A reference to this ray.
  6468. */
  6469. applyMatrix4( matrix4 ) {
  6470. this.origin.applyMatrix4( matrix4 );
  6471. this.direction.transformDirection( matrix4 );
  6472. return this;
  6473. }
  6474. /**
  6475. * Returns `true` if this ray is equal with the given one.
  6476. *
  6477. * @param {Ray} ray - The ray to test for equality.
  6478. * @return {boolean} Whether this ray is equal with the given one.
  6479. */
  6480. equals( ray ) {
  6481. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  6482. }
  6483. /**
  6484. * Returns a new ray with copied values from this instance.
  6485. *
  6486. * @return {Ray} A clone of this instance.
  6487. */
  6488. clone() {
  6489. return new this.constructor().copy( this );
  6490. }
  6491. }
  6492. /**
  6493. * Represents a 4x4 matrix.
  6494. *
  6495. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  6496. * 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}
  6497. *
  6498. * This allows a 3D vector representing a point in 3D space to undergo
  6499. * transformations such as translation, rotation, shear, scale, reflection,
  6500. * orthogonal or perspective projection and so on, by being multiplied by the
  6501. * matrix. This is known as `applying` the matrix to the vector.
  6502. *
  6503. * A Note on Row-Major and Column-Major Ordering:
  6504. *
  6505. * The constructor and {@link Matrix3#set} method take arguments in
  6506. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  6507. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  6508. * This means that calling:
  6509. * ```js
  6510. * const m = new THREE.Matrix4();
  6511. * m.set( 11, 12, 13, 14,
  6512. * 21, 22, 23, 24,
  6513. * 31, 32, 33, 34,
  6514. * 41, 42, 43, 44 );
  6515. * ```
  6516. * will result in the elements array containing:
  6517. * ```js
  6518. * m.elements = [ 11, 21, 31, 41,
  6519. * 12, 22, 32, 42,
  6520. * 13, 23, 33, 43,
  6521. * 14, 24, 34, 44 ];
  6522. * ```
  6523. * and internally all calculations are performed using column-major ordering.
  6524. * However, as the actual ordering makes no difference mathematically and
  6525. * most people are used to thinking about matrices in row-major order, the
  6526. * three.js documentation shows matrices in row-major order. Just bear in
  6527. * mind that if you are reading the source code, you'll have to take the
  6528. * transpose of any matrices outlined here to make sense of the calculations.
  6529. */
  6530. class Matrix4 {
  6531. /**
  6532. * Constructs a new 4x4 matrix. The arguments are supposed to be
  6533. * in row-major order. If no arguments are provided, the constructor
  6534. * initializes the matrix as an identity matrix.
  6535. *
  6536. * @param {number} [n11] - 1-1 matrix element.
  6537. * @param {number} [n12] - 1-2 matrix element.
  6538. * @param {number} [n13] - 1-3 matrix element.
  6539. * @param {number} [n14] - 1-4 matrix element.
  6540. * @param {number} [n21] - 2-1 matrix element.
  6541. * @param {number} [n22] - 2-2 matrix element.
  6542. * @param {number} [n23] - 2-3 matrix element.
  6543. * @param {number} [n24] - 2-4 matrix element.
  6544. * @param {number} [n31] - 3-1 matrix element.
  6545. * @param {number} [n32] - 3-2 matrix element.
  6546. * @param {number} [n33] - 3-3 matrix element.
  6547. * @param {number} [n34] - 3-4 matrix element.
  6548. * @param {number} [n41] - 4-1 matrix element.
  6549. * @param {number} [n42] - 4-2 matrix element.
  6550. * @param {number} [n43] - 4-3 matrix element.
  6551. * @param {number} [n44] - 4-4 matrix element.
  6552. */
  6553. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  6554. /**
  6555. * This flag can be used for type testing.
  6556. *
  6557. * @type {boolean}
  6558. * @readonly
  6559. * @default true
  6560. */
  6561. Matrix4.prototype.isMatrix4 = true;
  6562. /**
  6563. * A column-major list of matrix values.
  6564. *
  6565. * @type {Array<number>}
  6566. */
  6567. this.elements = [
  6568. 1, 0, 0, 0,
  6569. 0, 1, 0, 0,
  6570. 0, 0, 1, 0,
  6571. 0, 0, 0, 1
  6572. ];
  6573. if ( n11 !== undefined ) {
  6574. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  6575. }
  6576. }
  6577. /**
  6578. * Sets the elements of the matrix.The arguments are supposed to be
  6579. * in row-major order.
  6580. *
  6581. * @param {number} [n11] - 1-1 matrix element.
  6582. * @param {number} [n12] - 1-2 matrix element.
  6583. * @param {number} [n13] - 1-3 matrix element.
  6584. * @param {number} [n14] - 1-4 matrix element.
  6585. * @param {number} [n21] - 2-1 matrix element.
  6586. * @param {number} [n22] - 2-2 matrix element.
  6587. * @param {number} [n23] - 2-3 matrix element.
  6588. * @param {number} [n24] - 2-4 matrix element.
  6589. * @param {number} [n31] - 3-1 matrix element.
  6590. * @param {number} [n32] - 3-2 matrix element.
  6591. * @param {number} [n33] - 3-3 matrix element.
  6592. * @param {number} [n34] - 3-4 matrix element.
  6593. * @param {number} [n41] - 4-1 matrix element.
  6594. * @param {number} [n42] - 4-2 matrix element.
  6595. * @param {number} [n43] - 4-3 matrix element.
  6596. * @param {number} [n44] - 4-4 matrix element.
  6597. * @return {Matrix4} A reference to this matrix.
  6598. */
  6599. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  6600. const te = this.elements;
  6601. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  6602. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  6603. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  6604. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  6605. return this;
  6606. }
  6607. /**
  6608. * Sets this matrix to the 4x4 identity matrix.
  6609. *
  6610. * @return {Matrix4} A reference to this matrix.
  6611. */
  6612. identity() {
  6613. this.set(
  6614. 1, 0, 0, 0,
  6615. 0, 1, 0, 0,
  6616. 0, 0, 1, 0,
  6617. 0, 0, 0, 1
  6618. );
  6619. return this;
  6620. }
  6621. /**
  6622. * Returns a matrix with copied values from this instance.
  6623. *
  6624. * @return {Matrix4} A clone of this instance.
  6625. */
  6626. clone() {
  6627. return new Matrix4().fromArray( this.elements );
  6628. }
  6629. /**
  6630. * Copies the values of the given matrix to this instance.
  6631. *
  6632. * @param {Matrix4} m - The matrix to copy.
  6633. * @return {Matrix4} A reference to this matrix.
  6634. */
  6635. copy( m ) {
  6636. const te = this.elements;
  6637. const me = m.elements;
  6638. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  6639. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  6640. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  6641. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  6642. return this;
  6643. }
  6644. /**
  6645. * Copies the translation component of the given matrix
  6646. * into this matrix's translation component.
  6647. *
  6648. * @param {Matrix4} m - The matrix to copy the translation component.
  6649. * @return {Matrix4} A reference to this matrix.
  6650. */
  6651. copyPosition( m ) {
  6652. const te = this.elements, me = m.elements;
  6653. te[ 12 ] = me[ 12 ];
  6654. te[ 13 ] = me[ 13 ];
  6655. te[ 14 ] = me[ 14 ];
  6656. return this;
  6657. }
  6658. /**
  6659. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  6660. *
  6661. * @param {Matrix3} m - The 3x3 matrix.
  6662. * @return {Matrix4} A reference to this matrix.
  6663. */
  6664. setFromMatrix3( m ) {
  6665. const me = m.elements;
  6666. this.set(
  6667. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  6668. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  6669. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  6670. 0, 0, 0, 1
  6671. );
  6672. return this;
  6673. }
  6674. /**
  6675. * Extracts the basis of this matrix into the three axis vectors provided.
  6676. *
  6677. * @param {Vector3} xAxis - The basis's x axis.
  6678. * @param {Vector3} yAxis - The basis's y axis.
  6679. * @param {Vector3} zAxis - The basis's z axis.
  6680. * @return {Matrix4} A reference to this matrix.
  6681. */
  6682. extractBasis( xAxis, yAxis, zAxis ) {
  6683. xAxis.setFromMatrixColumn( this, 0 );
  6684. yAxis.setFromMatrixColumn( this, 1 );
  6685. zAxis.setFromMatrixColumn( this, 2 );
  6686. return this;
  6687. }
  6688. /**
  6689. * Sets the given basis vectors to this matrix.
  6690. *
  6691. * @param {Vector3} xAxis - The basis's x axis.
  6692. * @param {Vector3} yAxis - The basis's y axis.
  6693. * @param {Vector3} zAxis - The basis's z axis.
  6694. * @return {Matrix4} A reference to this matrix.
  6695. */
  6696. makeBasis( xAxis, yAxis, zAxis ) {
  6697. this.set(
  6698. xAxis.x, yAxis.x, zAxis.x, 0,
  6699. xAxis.y, yAxis.y, zAxis.y, 0,
  6700. xAxis.z, yAxis.z, zAxis.z, 0,
  6701. 0, 0, 0, 1
  6702. );
  6703. return this;
  6704. }
  6705. /**
  6706. * Extracts the rotation component of the given matrix
  6707. * into this matrix's rotation component.
  6708. *
  6709. * Note: This method does not support reflection matrices.
  6710. *
  6711. * @param {Matrix4} m - The matrix.
  6712. * @return {Matrix4} A reference to this matrix.
  6713. */
  6714. extractRotation( m ) {
  6715. const te = this.elements;
  6716. const me = m.elements;
  6717. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  6718. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  6719. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  6720. te[ 0 ] = me[ 0 ] * scaleX;
  6721. te[ 1 ] = me[ 1 ] * scaleX;
  6722. te[ 2 ] = me[ 2 ] * scaleX;
  6723. te[ 3 ] = 0;
  6724. te[ 4 ] = me[ 4 ] * scaleY;
  6725. te[ 5 ] = me[ 5 ] * scaleY;
  6726. te[ 6 ] = me[ 6 ] * scaleY;
  6727. te[ 7 ] = 0;
  6728. te[ 8 ] = me[ 8 ] * scaleZ;
  6729. te[ 9 ] = me[ 9 ] * scaleZ;
  6730. te[ 10 ] = me[ 10 ] * scaleZ;
  6731. te[ 11 ] = 0;
  6732. te[ 12 ] = 0;
  6733. te[ 13 ] = 0;
  6734. te[ 14 ] = 0;
  6735. te[ 15 ] = 1;
  6736. return this;
  6737. }
  6738. /**
  6739. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  6740. * the rotation specified by the given Euler angles. The rest of
  6741. * the matrix is set to the identity. Depending on the {@link Euler#order},
  6742. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  6743. * for a complete list.
  6744. *
  6745. * @param {Euler} euler - The Euler angles.
  6746. * @return {Matrix4} A reference to this matrix.
  6747. */
  6748. makeRotationFromEuler( euler ) {
  6749. const te = this.elements;
  6750. const x = euler.x, y = euler.y, z = euler.z;
  6751. const a = Math.cos( x ), b = Math.sin( x );
  6752. const c = Math.cos( y ), d = Math.sin( y );
  6753. const e = Math.cos( z ), f = Math.sin( z );
  6754. if ( euler.order === 'XYZ' ) {
  6755. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  6756. te[ 0 ] = c * e;
  6757. te[ 4 ] = - c * f;
  6758. te[ 8 ] = d;
  6759. te[ 1 ] = af + be * d;
  6760. te[ 5 ] = ae - bf * d;
  6761. te[ 9 ] = - b * c;
  6762. te[ 2 ] = bf - ae * d;
  6763. te[ 6 ] = be + af * d;
  6764. te[ 10 ] = a * c;
  6765. } else if ( euler.order === 'YXZ' ) {
  6766. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  6767. te[ 0 ] = ce + df * b;
  6768. te[ 4 ] = de * b - cf;
  6769. te[ 8 ] = a * d;
  6770. te[ 1 ] = a * f;
  6771. te[ 5 ] = a * e;
  6772. te[ 9 ] = - b;
  6773. te[ 2 ] = cf * b - de;
  6774. te[ 6 ] = df + ce * b;
  6775. te[ 10 ] = a * c;
  6776. } else if ( euler.order === 'ZXY' ) {
  6777. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  6778. te[ 0 ] = ce - df * b;
  6779. te[ 4 ] = - a * f;
  6780. te[ 8 ] = de + cf * b;
  6781. te[ 1 ] = cf + de * b;
  6782. te[ 5 ] = a * e;
  6783. te[ 9 ] = df - ce * b;
  6784. te[ 2 ] = - a * d;
  6785. te[ 6 ] = b;
  6786. te[ 10 ] = a * c;
  6787. } else if ( euler.order === 'ZYX' ) {
  6788. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  6789. te[ 0 ] = c * e;
  6790. te[ 4 ] = be * d - af;
  6791. te[ 8 ] = ae * d + bf;
  6792. te[ 1 ] = c * f;
  6793. te[ 5 ] = bf * d + ae;
  6794. te[ 9 ] = af * d - be;
  6795. te[ 2 ] = - d;
  6796. te[ 6 ] = b * c;
  6797. te[ 10 ] = a * c;
  6798. } else if ( euler.order === 'YZX' ) {
  6799. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6800. te[ 0 ] = c * e;
  6801. te[ 4 ] = bd - ac * f;
  6802. te[ 8 ] = bc * f + ad;
  6803. te[ 1 ] = f;
  6804. te[ 5 ] = a * e;
  6805. te[ 9 ] = - b * e;
  6806. te[ 2 ] = - d * e;
  6807. te[ 6 ] = ad * f + bc;
  6808. te[ 10 ] = ac - bd * f;
  6809. } else if ( euler.order === 'XZY' ) {
  6810. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6811. te[ 0 ] = c * e;
  6812. te[ 4 ] = - f;
  6813. te[ 8 ] = d * e;
  6814. te[ 1 ] = ac * f + bd;
  6815. te[ 5 ] = a * e;
  6816. te[ 9 ] = ad * f - bc;
  6817. te[ 2 ] = bc * f - ad;
  6818. te[ 6 ] = b * e;
  6819. te[ 10 ] = bd * f + ac;
  6820. }
  6821. // bottom row
  6822. te[ 3 ] = 0;
  6823. te[ 7 ] = 0;
  6824. te[ 11 ] = 0;
  6825. // last column
  6826. te[ 12 ] = 0;
  6827. te[ 13 ] = 0;
  6828. te[ 14 ] = 0;
  6829. te[ 15 ] = 1;
  6830. return this;
  6831. }
  6832. /**
  6833. * Sets the rotation component of this matrix to the rotation specified by
  6834. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  6835. * The rest of the matrix is set to the identity.
  6836. *
  6837. * @param {Quaternion} q - The Quaternion.
  6838. * @return {Matrix4} A reference to this matrix.
  6839. */
  6840. makeRotationFromQuaternion( q ) {
  6841. return this.compose( _zero, q, _one );
  6842. }
  6843. /**
  6844. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  6845. * `target`, and oriented by the up-direction.
  6846. *
  6847. * @param {Vector3} eye - The eye vector.
  6848. * @param {Vector3} target - The target vector.
  6849. * @param {Vector3} up - The up vector.
  6850. * @return {Matrix4} A reference to this matrix.
  6851. */
  6852. lookAt( eye, target, up ) {
  6853. const te = this.elements;
  6854. _z.subVectors( eye, target );
  6855. if ( _z.lengthSq() === 0 ) {
  6856. // eye and target are in the same position
  6857. _z.z = 1;
  6858. }
  6859. _z.normalize();
  6860. _x.crossVectors( up, _z );
  6861. if ( _x.lengthSq() === 0 ) {
  6862. // up and z are parallel
  6863. if ( Math.abs( up.z ) === 1 ) {
  6864. _z.x += 0.0001;
  6865. } else {
  6866. _z.z += 0.0001;
  6867. }
  6868. _z.normalize();
  6869. _x.crossVectors( up, _z );
  6870. }
  6871. _x.normalize();
  6872. _y.crossVectors( _z, _x );
  6873. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  6874. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  6875. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  6876. return this;
  6877. }
  6878. /**
  6879. * Post-multiplies this matrix by the given 4x4 matrix.
  6880. *
  6881. * @param {Matrix4} m - The matrix to multiply with.
  6882. * @return {Matrix4} A reference to this matrix.
  6883. */
  6884. multiply( m ) {
  6885. return this.multiplyMatrices( this, m );
  6886. }
  6887. /**
  6888. * Pre-multiplies this matrix by the given 4x4 matrix.
  6889. *
  6890. * @param {Matrix4} m - The matrix to multiply with.
  6891. * @return {Matrix4} A reference to this matrix.
  6892. */
  6893. premultiply( m ) {
  6894. return this.multiplyMatrices( m, this );
  6895. }
  6896. /**
  6897. * Multiples the given 4x4 matrices and stores the result
  6898. * in this matrix.
  6899. *
  6900. * @param {Matrix4} a - The first matrix.
  6901. * @param {Matrix4} b - The second matrix.
  6902. * @return {Matrix4} A reference to this matrix.
  6903. */
  6904. multiplyMatrices( a, b ) {
  6905. const ae = a.elements;
  6906. const be = b.elements;
  6907. const te = this.elements;
  6908. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  6909. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  6910. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  6911. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  6912. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  6913. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  6914. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  6915. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  6916. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  6917. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  6918. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  6919. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  6920. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  6921. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  6922. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  6923. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  6924. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  6925. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  6926. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  6927. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  6928. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  6929. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  6930. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  6931. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  6932. return this;
  6933. }
  6934. /**
  6935. * Multiplies every component of the matrix by the given scalar.
  6936. *
  6937. * @param {number} s - The scalar.
  6938. * @return {Matrix4} A reference to this matrix.
  6939. */
  6940. multiplyScalar( s ) {
  6941. const te = this.elements;
  6942. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  6943. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  6944. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  6945. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  6946. return this;
  6947. }
  6948. /**
  6949. * Computes and returns the determinant of this matrix.
  6950. *
  6951. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  6952. *
  6953. * @return {number} The determinant.
  6954. */
  6955. determinant() {
  6956. const te = this.elements;
  6957. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  6958. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  6959. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  6960. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  6961. //TODO: make this more efficient
  6962. return (
  6963. n41 * (
  6964. + n14 * n23 * n32
  6965. - n13 * n24 * n32
  6966. - n14 * n22 * n33
  6967. + n12 * n24 * n33
  6968. + n13 * n22 * n34
  6969. - n12 * n23 * n34
  6970. ) +
  6971. n42 * (
  6972. + n11 * n23 * n34
  6973. - n11 * n24 * n33
  6974. + n14 * n21 * n33
  6975. - n13 * n21 * n34
  6976. + n13 * n24 * n31
  6977. - n14 * n23 * n31
  6978. ) +
  6979. n43 * (
  6980. + n11 * n24 * n32
  6981. - n11 * n22 * n34
  6982. - n14 * n21 * n32
  6983. + n12 * n21 * n34
  6984. + n14 * n22 * n31
  6985. - n12 * n24 * n31
  6986. ) +
  6987. n44 * (
  6988. - n13 * n22 * n31
  6989. - n11 * n23 * n32
  6990. + n11 * n22 * n33
  6991. + n13 * n21 * n32
  6992. - n12 * n21 * n33
  6993. + n12 * n23 * n31
  6994. )
  6995. );
  6996. }
  6997. /**
  6998. * Transposes this matrix in place.
  6999. *
  7000. * @return {Matrix4} A reference to this matrix.
  7001. */
  7002. transpose() {
  7003. const te = this.elements;
  7004. let tmp;
  7005. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  7006. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  7007. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  7008. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  7009. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  7010. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  7011. return this;
  7012. }
  7013. /**
  7014. * Sets the position component for this matrix from the given vector,
  7015. * without affecting the rest of the matrix.
  7016. *
  7017. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  7018. * @param {number} y - The y component of the vector.
  7019. * @param {number} z - The z component of the vector.
  7020. * @return {Matrix4} A reference to this matrix.
  7021. */
  7022. setPosition( x, y, z ) {
  7023. const te = this.elements;
  7024. if ( x.isVector3 ) {
  7025. te[ 12 ] = x.x;
  7026. te[ 13 ] = x.y;
  7027. te[ 14 ] = x.z;
  7028. } else {
  7029. te[ 12 ] = x;
  7030. te[ 13 ] = y;
  7031. te[ 14 ] = z;
  7032. }
  7033. return this;
  7034. }
  7035. /**
  7036. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  7037. * You can not invert with a determinant of zero. If you attempt this, the method produces
  7038. * a zero matrix instead.
  7039. *
  7040. * @return {Matrix4} A reference to this matrix.
  7041. */
  7042. invert() {
  7043. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  7044. const te = this.elements,
  7045. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  7046. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  7047. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  7048. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  7049. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  7050. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  7051. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  7052. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  7053. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  7054. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  7055. const detInv = 1 / det;
  7056. te[ 0 ] = t11 * detInv;
  7057. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  7058. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  7059. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  7060. te[ 4 ] = t12 * detInv;
  7061. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  7062. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  7063. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  7064. te[ 8 ] = t13 * detInv;
  7065. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  7066. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  7067. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  7068. te[ 12 ] = t14 * detInv;
  7069. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  7070. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  7071. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  7072. return this;
  7073. }
  7074. /**
  7075. * Multiplies the columns of this matrix by the given vector.
  7076. *
  7077. * @param {Vector3} v - The scale vector.
  7078. * @return {Matrix4} A reference to this matrix.
  7079. */
  7080. scale( v ) {
  7081. const te = this.elements;
  7082. const x = v.x, y = v.y, z = v.z;
  7083. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  7084. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  7085. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  7086. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  7087. return this;
  7088. }
  7089. /**
  7090. * Gets the maximum scale value of the three axes.
  7091. *
  7092. * @return {number} The maximum scale.
  7093. */
  7094. getMaxScaleOnAxis() {
  7095. const te = this.elements;
  7096. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  7097. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  7098. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  7099. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  7100. }
  7101. /**
  7102. * Sets this matrix as a translation transform from the given vector.
  7103. *
  7104. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  7105. * @param {number} y - The amount to translate in the Y axis.
  7106. * @param {number} z - The amount to translate in the z axis.
  7107. * @return {Matrix4} A reference to this matrix.
  7108. */
  7109. makeTranslation( x, y, z ) {
  7110. if ( x.isVector3 ) {
  7111. this.set(
  7112. 1, 0, 0, x.x,
  7113. 0, 1, 0, x.y,
  7114. 0, 0, 1, x.z,
  7115. 0, 0, 0, 1
  7116. );
  7117. } else {
  7118. this.set(
  7119. 1, 0, 0, x,
  7120. 0, 1, 0, y,
  7121. 0, 0, 1, z,
  7122. 0, 0, 0, 1
  7123. );
  7124. }
  7125. return this;
  7126. }
  7127. /**
  7128. * Sets this matrix as a rotational transformation around the X axis by
  7129. * the given angle.
  7130. *
  7131. * @param {number} theta - The rotation in radians.
  7132. * @return {Matrix4} A reference to this matrix.
  7133. */
  7134. makeRotationX( theta ) {
  7135. const c = Math.cos( theta ), s = Math.sin( theta );
  7136. this.set(
  7137. 1, 0, 0, 0,
  7138. 0, c, - s, 0,
  7139. 0, s, c, 0,
  7140. 0, 0, 0, 1
  7141. );
  7142. return this;
  7143. }
  7144. /**
  7145. * Sets this matrix as a rotational transformation around the Y axis by
  7146. * the given angle.
  7147. *
  7148. * @param {number} theta - The rotation in radians.
  7149. * @return {Matrix4} A reference to this matrix.
  7150. */
  7151. makeRotationY( theta ) {
  7152. const c = Math.cos( theta ), s = Math.sin( theta );
  7153. this.set(
  7154. c, 0, s, 0,
  7155. 0, 1, 0, 0,
  7156. - s, 0, c, 0,
  7157. 0, 0, 0, 1
  7158. );
  7159. return this;
  7160. }
  7161. /**
  7162. * Sets this matrix as a rotational transformation around the Z axis by
  7163. * the given angle.
  7164. *
  7165. * @param {number} theta - The rotation in radians.
  7166. * @return {Matrix4} A reference to this matrix.
  7167. */
  7168. makeRotationZ( theta ) {
  7169. const c = Math.cos( theta ), s = Math.sin( theta );
  7170. this.set(
  7171. c, - s, 0, 0,
  7172. s, c, 0, 0,
  7173. 0, 0, 1, 0,
  7174. 0, 0, 0, 1
  7175. );
  7176. return this;
  7177. }
  7178. /**
  7179. * Sets this matrix as a rotational transformation around the given axis by
  7180. * the given angle.
  7181. *
  7182. * This is a somewhat controversial but mathematically sound alternative to
  7183. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  7184. *
  7185. * @param {Vector3} axis - The normalized rotation axis.
  7186. * @param {number} angle - The rotation in radians.
  7187. * @return {Matrix4} A reference to this matrix.
  7188. */
  7189. makeRotationAxis( axis, angle ) {
  7190. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  7191. const c = Math.cos( angle );
  7192. const s = Math.sin( angle );
  7193. const t = 1 - c;
  7194. const x = axis.x, y = axis.y, z = axis.z;
  7195. const tx = t * x, ty = t * y;
  7196. this.set(
  7197. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  7198. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  7199. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  7200. 0, 0, 0, 1
  7201. );
  7202. return this;
  7203. }
  7204. /**
  7205. * Sets this matrix as a scale transformation.
  7206. *
  7207. * @param {number} x - The amount to scale in the X axis.
  7208. * @param {number} y - The amount to scale in the Y axis.
  7209. * @param {number} z - The amount to scale in the Z axis.
  7210. * @return {Matrix4} A reference to this matrix.
  7211. */
  7212. makeScale( x, y, z ) {
  7213. this.set(
  7214. x, 0, 0, 0,
  7215. 0, y, 0, 0,
  7216. 0, 0, z, 0,
  7217. 0, 0, 0, 1
  7218. );
  7219. return this;
  7220. }
  7221. /**
  7222. * Sets this matrix as a shear transformation.
  7223. *
  7224. * @param {number} xy - The amount to shear X by Y.
  7225. * @param {number} xz - The amount to shear X by Z.
  7226. * @param {number} yx - The amount to shear Y by X.
  7227. * @param {number} yz - The amount to shear Y by Z.
  7228. * @param {number} zx - The amount to shear Z by X.
  7229. * @param {number} zy - The amount to shear Z by Y.
  7230. * @return {Matrix4} A reference to this matrix.
  7231. */
  7232. makeShear( xy, xz, yx, yz, zx, zy ) {
  7233. this.set(
  7234. 1, yx, zx, 0,
  7235. xy, 1, zy, 0,
  7236. xz, yz, 1, 0,
  7237. 0, 0, 0, 1
  7238. );
  7239. return this;
  7240. }
  7241. /**
  7242. * Sets this matrix to the transformation composed of the given position,
  7243. * rotation (Quaternion) and scale.
  7244. *
  7245. * @param {Vector3} position - The position vector.
  7246. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  7247. * @param {Vector3} scale - The scale vector.
  7248. * @return {Matrix4} A reference to this matrix.
  7249. */
  7250. compose( position, quaternion, scale ) {
  7251. const te = this.elements;
  7252. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  7253. const x2 = x + x, y2 = y + y, z2 = z + z;
  7254. const xx = x * x2, xy = x * y2, xz = x * z2;
  7255. const yy = y * y2, yz = y * z2, zz = z * z2;
  7256. const wx = w * x2, wy = w * y2, wz = w * z2;
  7257. const sx = scale.x, sy = scale.y, sz = scale.z;
  7258. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  7259. te[ 1 ] = ( xy + wz ) * sx;
  7260. te[ 2 ] = ( xz - wy ) * sx;
  7261. te[ 3 ] = 0;
  7262. te[ 4 ] = ( xy - wz ) * sy;
  7263. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  7264. te[ 6 ] = ( yz + wx ) * sy;
  7265. te[ 7 ] = 0;
  7266. te[ 8 ] = ( xz + wy ) * sz;
  7267. te[ 9 ] = ( yz - wx ) * sz;
  7268. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  7269. te[ 11 ] = 0;
  7270. te[ 12 ] = position.x;
  7271. te[ 13 ] = position.y;
  7272. te[ 14 ] = position.z;
  7273. te[ 15 ] = 1;
  7274. return this;
  7275. }
  7276. /**
  7277. * Decomposes this matrix into its position, rotation and scale components
  7278. * and provides the result in the given objects.
  7279. *
  7280. * Note: Not all matrices are decomposable in this way. For example, if an
  7281. * object has a non-uniformly scaled parent, then the object's world matrix
  7282. * may not be decomposable, and this method may not be appropriate.
  7283. *
  7284. * @param {Vector3} position - The position vector.
  7285. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  7286. * @param {Vector3} scale - The scale vector.
  7287. * @return {Matrix4} A reference to this matrix.
  7288. */
  7289. decompose( position, quaternion, scale ) {
  7290. const te = this.elements;
  7291. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  7292. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  7293. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  7294. // if determine is negative, we need to invert one scale
  7295. const det = this.determinant();
  7296. if ( det < 0 ) sx = - sx;
  7297. position.x = te[ 12 ];
  7298. position.y = te[ 13 ];
  7299. position.z = te[ 14 ];
  7300. // scale the rotation part
  7301. _m1$4.copy( this );
  7302. const invSX = 1 / sx;
  7303. const invSY = 1 / sy;
  7304. const invSZ = 1 / sz;
  7305. _m1$4.elements[ 0 ] *= invSX;
  7306. _m1$4.elements[ 1 ] *= invSX;
  7307. _m1$4.elements[ 2 ] *= invSX;
  7308. _m1$4.elements[ 4 ] *= invSY;
  7309. _m1$4.elements[ 5 ] *= invSY;
  7310. _m1$4.elements[ 6 ] *= invSY;
  7311. _m1$4.elements[ 8 ] *= invSZ;
  7312. _m1$4.elements[ 9 ] *= invSZ;
  7313. _m1$4.elements[ 10 ] *= invSZ;
  7314. quaternion.setFromRotationMatrix( _m1$4 );
  7315. scale.x = sx;
  7316. scale.y = sy;
  7317. scale.z = sz;
  7318. return this;
  7319. }
  7320. /**
  7321. * Creates a perspective projection matrix. This is used internally by
  7322. * {@link PerspectiveCamera#updateProjectionMatrix}.
  7323. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  7324. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  7325. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  7326. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  7327. * @param {number} near - The distance from the camera to the near plane.
  7328. * @param {number} far - The distance from the camera to the far plane.
  7329. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  7330. * @return {Matrix4} A reference to this matrix.
  7331. */
  7332. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  7333. const te = this.elements;
  7334. const x = 2 * near / ( right - left );
  7335. const y = 2 * near / ( top - bottom );
  7336. const a = ( right + left ) / ( right - left );
  7337. const b = ( top + bottom ) / ( top - bottom );
  7338. let c, d;
  7339. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7340. c = - ( far + near ) / ( far - near );
  7341. d = ( -2 * far * near ) / ( far - near );
  7342. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7343. c = - far / ( far - near );
  7344. d = ( - far * near ) / ( far - near );
  7345. } else {
  7346. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  7347. }
  7348. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  7349. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  7350. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  7351. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  7352. return this;
  7353. }
  7354. /**
  7355. * Creates a orthographic projection matrix. This is used internally by
  7356. * {@link OrthographicCamera#updateProjectionMatrix}.
  7357. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  7358. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  7359. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  7360. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  7361. * @param {number} near - The distance from the camera to the near plane.
  7362. * @param {number} far - The distance from the camera to the far plane.
  7363. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  7364. * @return {Matrix4} A reference to this matrix.
  7365. */
  7366. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  7367. const te = this.elements;
  7368. const w = 1.0 / ( right - left );
  7369. const h = 1.0 / ( top - bottom );
  7370. const p = 1.0 / ( far - near );
  7371. const x = ( right + left ) * w;
  7372. const y = ( top + bottom ) * h;
  7373. let z, zInv;
  7374. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7375. z = ( far + near ) * p;
  7376. zInv = -2 * p;
  7377. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7378. z = near * p;
  7379. zInv = -1 * p;
  7380. } else {
  7381. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  7382. }
  7383. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  7384. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  7385. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  7386. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  7387. return this;
  7388. }
  7389. /**
  7390. * Returns `true` if this matrix is equal with the given one.
  7391. *
  7392. * @param {Matrix4} matrix - The matrix to test for equality.
  7393. * @return {boolean} Whether this matrix is equal with the given one.
  7394. */
  7395. equals( matrix ) {
  7396. const te = this.elements;
  7397. const me = matrix.elements;
  7398. for ( let i = 0; i < 16; i ++ ) {
  7399. if ( te[ i ] !== me[ i ] ) return false;
  7400. }
  7401. return true;
  7402. }
  7403. /**
  7404. * Sets the elements of the matrix from the given array.
  7405. *
  7406. * @param {Array<number>} array - The matrix elements in column-major order.
  7407. * @param {number} [offset=0] - Index of the first element in the array.
  7408. * @return {Matrix4} A reference to this matrix.
  7409. */
  7410. fromArray( array, offset = 0 ) {
  7411. for ( let i = 0; i < 16; i ++ ) {
  7412. this.elements[ i ] = array[ i + offset ];
  7413. }
  7414. return this;
  7415. }
  7416. /**
  7417. * Writes the elements of this matrix to the given array. If no array is provided,
  7418. * the method returns a new instance.
  7419. *
  7420. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  7421. * @param {number} [offset=0] - Index of the first element in the array.
  7422. * @return {Array<number>} The matrix elements in column-major order.
  7423. */
  7424. toArray( array = [], offset = 0 ) {
  7425. const te = this.elements;
  7426. array[ offset ] = te[ 0 ];
  7427. array[ offset + 1 ] = te[ 1 ];
  7428. array[ offset + 2 ] = te[ 2 ];
  7429. array[ offset + 3 ] = te[ 3 ];
  7430. array[ offset + 4 ] = te[ 4 ];
  7431. array[ offset + 5 ] = te[ 5 ];
  7432. array[ offset + 6 ] = te[ 6 ];
  7433. array[ offset + 7 ] = te[ 7 ];
  7434. array[ offset + 8 ] = te[ 8 ];
  7435. array[ offset + 9 ] = te[ 9 ];
  7436. array[ offset + 10 ] = te[ 10 ];
  7437. array[ offset + 11 ] = te[ 11 ];
  7438. array[ offset + 12 ] = te[ 12 ];
  7439. array[ offset + 13 ] = te[ 13 ];
  7440. array[ offset + 14 ] = te[ 14 ];
  7441. array[ offset + 15 ] = te[ 15 ];
  7442. return array;
  7443. }
  7444. }
  7445. const _v1$5 = /*@__PURE__*/ new Vector3();
  7446. const _m1$4 = /*@__PURE__*/ new Matrix4();
  7447. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  7448. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  7449. const _x = /*@__PURE__*/ new Vector3();
  7450. const _y = /*@__PURE__*/ new Vector3();
  7451. const _z = /*@__PURE__*/ new Vector3();
  7452. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  7453. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  7454. /**
  7455. * A class representing Euler angles.
  7456. *
  7457. * Euler angles describe a rotational transformation by rotating an object on
  7458. * its various axes in specified amounts per axis, and a specified axis
  7459. * order.
  7460. *
  7461. * Iterating through an instance will yield its components (x, y, z,
  7462. * order) in the corresponding order.
  7463. *
  7464. * ```js
  7465. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  7466. * const b = new THREE.Vector3( 1, 0, 1 );
  7467. * b.applyEuler(a);
  7468. * ```
  7469. */
  7470. class Euler {
  7471. /**
  7472. * Constructs a new euler instance.
  7473. *
  7474. * @param {number} [x=0] - The angle of the x axis in radians.
  7475. * @param {number} [y=0] - The angle of the y axis in radians.
  7476. * @param {number} [z=0] - The angle of the z axis in radians.
  7477. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  7478. */
  7479. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  7480. /**
  7481. * This flag can be used for type testing.
  7482. *
  7483. * @type {boolean}
  7484. * @readonly
  7485. * @default true
  7486. */
  7487. this.isEuler = true;
  7488. this._x = x;
  7489. this._y = y;
  7490. this._z = z;
  7491. this._order = order;
  7492. }
  7493. /**
  7494. * The angle of the x axis in radians.
  7495. *
  7496. * @type {number}
  7497. * @default 0
  7498. */
  7499. get x() {
  7500. return this._x;
  7501. }
  7502. set x( value ) {
  7503. this._x = value;
  7504. this._onChangeCallback();
  7505. }
  7506. /**
  7507. * The angle of the y axis in radians.
  7508. *
  7509. * @type {number}
  7510. * @default 0
  7511. */
  7512. get y() {
  7513. return this._y;
  7514. }
  7515. set y( value ) {
  7516. this._y = value;
  7517. this._onChangeCallback();
  7518. }
  7519. /**
  7520. * The angle of the z axis in radians.
  7521. *
  7522. * @type {number}
  7523. * @default 0
  7524. */
  7525. get z() {
  7526. return this._z;
  7527. }
  7528. set z( value ) {
  7529. this._z = value;
  7530. this._onChangeCallback();
  7531. }
  7532. /**
  7533. * A string representing the order that the rotations are applied.
  7534. *
  7535. * @type {string}
  7536. * @default 'XYZ'
  7537. */
  7538. get order() {
  7539. return this._order;
  7540. }
  7541. set order( value ) {
  7542. this._order = value;
  7543. this._onChangeCallback();
  7544. }
  7545. /**
  7546. * Sets the Euler components.
  7547. *
  7548. * @param {number} x - The angle of the x axis in radians.
  7549. * @param {number} y - The angle of the y axis in radians.
  7550. * @param {number} z - The angle of the z axis in radians.
  7551. * @param {string} [order] - A string representing the order that the rotations are applied.
  7552. * @return {Euler} A reference to this Euler instance.
  7553. */
  7554. set( x, y, z, order = this._order ) {
  7555. this._x = x;
  7556. this._y = y;
  7557. this._z = z;
  7558. this._order = order;
  7559. this._onChangeCallback();
  7560. return this;
  7561. }
  7562. /**
  7563. * Returns a new Euler instance with copied values from this instance.
  7564. *
  7565. * @return {Euler} A clone of this instance.
  7566. */
  7567. clone() {
  7568. return new this.constructor( this._x, this._y, this._z, this._order );
  7569. }
  7570. /**
  7571. * Copies the values of the given Euler instance to this instance.
  7572. *
  7573. * @param {Euler} euler - The Euler instance to copy.
  7574. * @return {Euler} A reference to this Euler instance.
  7575. */
  7576. copy( euler ) {
  7577. this._x = euler._x;
  7578. this._y = euler._y;
  7579. this._z = euler._z;
  7580. this._order = euler._order;
  7581. this._onChangeCallback();
  7582. return this;
  7583. }
  7584. /**
  7585. * Sets the angles of this Euler instance from a pure rotation matrix.
  7586. *
  7587. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  7588. * @param {string} [order] - A string representing the order that the rotations are applied.
  7589. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  7590. * @return {Euler} A reference to this Euler instance.
  7591. */
  7592. setFromRotationMatrix( m, order = this._order, update = true ) {
  7593. const te = m.elements;
  7594. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  7595. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  7596. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  7597. switch ( order ) {
  7598. case 'XYZ':
  7599. this._y = Math.asin( clamp( m13, -1, 1 ) );
  7600. if ( Math.abs( m13 ) < 0.9999999 ) {
  7601. this._x = Math.atan2( - m23, m33 );
  7602. this._z = Math.atan2( - m12, m11 );
  7603. } else {
  7604. this._x = Math.atan2( m32, m22 );
  7605. this._z = 0;
  7606. }
  7607. break;
  7608. case 'YXZ':
  7609. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  7610. if ( Math.abs( m23 ) < 0.9999999 ) {
  7611. this._y = Math.atan2( m13, m33 );
  7612. this._z = Math.atan2( m21, m22 );
  7613. } else {
  7614. this._y = Math.atan2( - m31, m11 );
  7615. this._z = 0;
  7616. }
  7617. break;
  7618. case 'ZXY':
  7619. this._x = Math.asin( clamp( m32, -1, 1 ) );
  7620. if ( Math.abs( m32 ) < 0.9999999 ) {
  7621. this._y = Math.atan2( - m31, m33 );
  7622. this._z = Math.atan2( - m12, m22 );
  7623. } else {
  7624. this._y = 0;
  7625. this._z = Math.atan2( m21, m11 );
  7626. }
  7627. break;
  7628. case 'ZYX':
  7629. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  7630. if ( Math.abs( m31 ) < 0.9999999 ) {
  7631. this._x = Math.atan2( m32, m33 );
  7632. this._z = Math.atan2( m21, m11 );
  7633. } else {
  7634. this._x = 0;
  7635. this._z = Math.atan2( - m12, m22 );
  7636. }
  7637. break;
  7638. case 'YZX':
  7639. this._z = Math.asin( clamp( m21, -1, 1 ) );
  7640. if ( Math.abs( m21 ) < 0.9999999 ) {
  7641. this._x = Math.atan2( - m23, m22 );
  7642. this._y = Math.atan2( - m31, m11 );
  7643. } else {
  7644. this._x = 0;
  7645. this._y = Math.atan2( m13, m33 );
  7646. }
  7647. break;
  7648. case 'XZY':
  7649. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  7650. if ( Math.abs( m12 ) < 0.9999999 ) {
  7651. this._x = Math.atan2( m32, m22 );
  7652. this._y = Math.atan2( m13, m11 );
  7653. } else {
  7654. this._x = Math.atan2( - m23, m33 );
  7655. this._y = 0;
  7656. }
  7657. break;
  7658. default:
  7659. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  7660. }
  7661. this._order = order;
  7662. if ( update === true ) this._onChangeCallback();
  7663. return this;
  7664. }
  7665. /**
  7666. * Sets the angles of this Euler instance from a normalized quaternion.
  7667. *
  7668. * @param {Quaternion} q - A normalized Quaternion.
  7669. * @param {string} [order] - A string representing the order that the rotations are applied.
  7670. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  7671. * @return {Euler} A reference to this Euler instance.
  7672. */
  7673. setFromQuaternion( q, order, update ) {
  7674. _matrix$2.makeRotationFromQuaternion( q );
  7675. return this.setFromRotationMatrix( _matrix$2, order, update );
  7676. }
  7677. /**
  7678. * Sets the angles of this Euler instance from the given vector.
  7679. *
  7680. * @param {Vector3} v - The vector.
  7681. * @param {string} [order] - A string representing the order that the rotations are applied.
  7682. * @return {Euler} A reference to this Euler instance.
  7683. */
  7684. setFromVector3( v, order = this._order ) {
  7685. return this.set( v.x, v.y, v.z, order );
  7686. }
  7687. /**
  7688. * Resets the euler angle with a new order by creating a quaternion from this
  7689. * euler angle and then setting this euler angle with the quaternion and the
  7690. * new order.
  7691. *
  7692. * Warning: This discards revolution information.
  7693. *
  7694. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  7695. * @return {Euler} A reference to this Euler instance.
  7696. */
  7697. reorder( newOrder ) {
  7698. _quaternion$3.setFromEuler( this );
  7699. return this.setFromQuaternion( _quaternion$3, newOrder );
  7700. }
  7701. /**
  7702. * Returns `true` if this Euler instance is equal with the given one.
  7703. *
  7704. * @param {Euler} euler - The Euler instance to test for equality.
  7705. * @return {boolean} Whether this Euler instance is equal with the given one.
  7706. */
  7707. equals( euler ) {
  7708. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  7709. }
  7710. /**
  7711. * Sets this Euler instance's components to values from the given array. The first three
  7712. * entries of the array are assign to the x,y and z components. An optional fourth entry
  7713. * defines the Euler order.
  7714. *
  7715. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  7716. * @return {Euler} A reference to this Euler instance.
  7717. */
  7718. fromArray( array ) {
  7719. this._x = array[ 0 ];
  7720. this._y = array[ 1 ];
  7721. this._z = array[ 2 ];
  7722. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  7723. this._onChangeCallback();
  7724. return this;
  7725. }
  7726. /**
  7727. * Writes the components of this Euler instance to the given array. If no array is provided,
  7728. * the method returns a new instance.
  7729. *
  7730. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  7731. * @param {number} [offset=0] - Index of the first element in the array.
  7732. * @return {Array<number,number,number,string>} The Euler components.
  7733. */
  7734. toArray( array = [], offset = 0 ) {
  7735. array[ offset ] = this._x;
  7736. array[ offset + 1 ] = this._y;
  7737. array[ offset + 2 ] = this._z;
  7738. array[ offset + 3 ] = this._order;
  7739. return array;
  7740. }
  7741. _onChange( callback ) {
  7742. this._onChangeCallback = callback;
  7743. return this;
  7744. }
  7745. _onChangeCallback() {}
  7746. *[ Symbol.iterator ]() {
  7747. yield this._x;
  7748. yield this._y;
  7749. yield this._z;
  7750. yield this._order;
  7751. }
  7752. }
  7753. /**
  7754. * The default Euler angle order.
  7755. *
  7756. * @static
  7757. * @type {string}
  7758. * @default 'XYZ'
  7759. */
  7760. Euler.DEFAULT_ORDER = 'XYZ';
  7761. class Layers {
  7762. constructor() {
  7763. this.mask = 1 | 0;
  7764. }
  7765. set( channel ) {
  7766. this.mask = ( 1 << channel | 0 ) >>> 0;
  7767. }
  7768. enable( channel ) {
  7769. this.mask |= 1 << channel | 0;
  7770. }
  7771. enableAll() {
  7772. this.mask = 0xffffffff | 0;
  7773. }
  7774. toggle( channel ) {
  7775. this.mask ^= 1 << channel | 0;
  7776. }
  7777. disable( channel ) {
  7778. this.mask &= ~ ( 1 << channel | 0 );
  7779. }
  7780. disableAll() {
  7781. this.mask = 0;
  7782. }
  7783. test( layers ) {
  7784. return ( this.mask & layers.mask ) !== 0;
  7785. }
  7786. isEnabled( channel ) {
  7787. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  7788. }
  7789. }
  7790. let _object3DId = 0;
  7791. const _v1$4 = /*@__PURE__*/ new Vector3();
  7792. const _q1 = /*@__PURE__*/ new Quaternion();
  7793. const _m1$3 = /*@__PURE__*/ new Matrix4();
  7794. const _target = /*@__PURE__*/ new Vector3();
  7795. const _position$3 = /*@__PURE__*/ new Vector3();
  7796. const _scale$2 = /*@__PURE__*/ new Vector3();
  7797. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  7798. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  7799. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  7800. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  7801. /**
  7802. * Fires when the object has been added to its parent object.
  7803. *
  7804. * @event Object3D#added
  7805. * @type {Object}
  7806. */
  7807. const _addedEvent = { type: 'added' };
  7808. /**
  7809. * Fires when the object has been removed from its parent object.
  7810. *
  7811. * @event Object3D#removed
  7812. * @type {Object}
  7813. */
  7814. const _removedEvent = { type: 'removed' };
  7815. /**
  7816. * Fires when a new child object has been added.
  7817. *
  7818. * @event Object3D#childadded
  7819. * @type {Object}
  7820. */
  7821. const _childaddedEvent = { type: 'childadded', child: null };
  7822. /**
  7823. * Fires when a new child object has been added.
  7824. *
  7825. * @event Object3D#childremoved
  7826. * @type {Object}
  7827. */
  7828. const _childremovedEvent = { type: 'childremoved', child: null };
  7829. /**
  7830. * This is the base class for most objects in three.js and provides a set of
  7831. * properties and methods for manipulating objects in 3D space.
  7832. *
  7833. * @augments EventDispatcher
  7834. */
  7835. class Object3D extends EventDispatcher {
  7836. /**
  7837. * Constructs a new 3D object.
  7838. */
  7839. constructor() {
  7840. super();
  7841. /**
  7842. * This flag can be used for type testing.
  7843. *
  7844. * @type {boolean}
  7845. * @readonly
  7846. * @default true
  7847. */
  7848. this.isObject3D = true;
  7849. /**
  7850. * The ID of the 3D object.
  7851. *
  7852. * @name Object3D#id
  7853. * @type {number}
  7854. * @readonly
  7855. */
  7856. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  7857. /**
  7858. * The UUID of the 3D object.
  7859. *
  7860. * @type {string}
  7861. * @readonly
  7862. */
  7863. this.uuid = generateUUID();
  7864. /**
  7865. * The name of the 3D object.
  7866. *
  7867. * @type {string}
  7868. */
  7869. this.name = '';
  7870. /**
  7871. * The type property is used for detecting the object type
  7872. * in context of serialization/deserialization.
  7873. *
  7874. * @type {string}
  7875. * @readonly
  7876. */
  7877. this.type = 'Object3D';
  7878. /**
  7879. * A reference to the parent object.
  7880. *
  7881. * @type {?Object3D}
  7882. * @default null
  7883. */
  7884. this.parent = null;
  7885. /**
  7886. * An array holding the child 3D objects of this instance.
  7887. *
  7888. * @type {Array<Object3D>}
  7889. */
  7890. this.children = [];
  7891. /**
  7892. * Defines the `up` direction of the 3D object which influences
  7893. * the orientation via methods like {@link Object3D#lookAt}.
  7894. *
  7895. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  7896. *
  7897. * @type {Vector3}
  7898. */
  7899. this.up = Object3D.DEFAULT_UP.clone();
  7900. const position = new Vector3();
  7901. const rotation = new Euler();
  7902. const quaternion = new Quaternion();
  7903. const scale = new Vector3( 1, 1, 1 );
  7904. function onRotationChange() {
  7905. quaternion.setFromEuler( rotation, false );
  7906. }
  7907. function onQuaternionChange() {
  7908. rotation.setFromQuaternion( quaternion, undefined, false );
  7909. }
  7910. rotation._onChange( onRotationChange );
  7911. quaternion._onChange( onQuaternionChange );
  7912. Object.defineProperties( this, {
  7913. /**
  7914. * Represents the object's local position.
  7915. *
  7916. * @name Object3D#position
  7917. * @type {Vector3}
  7918. * @default (0,0,0)
  7919. */
  7920. position: {
  7921. configurable: true,
  7922. enumerable: true,
  7923. value: position
  7924. },
  7925. /**
  7926. * Represents the object's local rotation as Euler angles, in radians.
  7927. *
  7928. * @name Object3D#rotation
  7929. * @type {Euler}
  7930. * @default (0,0,0)
  7931. */
  7932. rotation: {
  7933. configurable: true,
  7934. enumerable: true,
  7935. value: rotation
  7936. },
  7937. /**
  7938. * Represents the object's local rotation as Quaternions.
  7939. *
  7940. * @name Object3D#quaternion
  7941. * @type {Quaternion}
  7942. */
  7943. quaternion: {
  7944. configurable: true,
  7945. enumerable: true,
  7946. value: quaternion
  7947. },
  7948. /**
  7949. * Represents the object's local scale.
  7950. *
  7951. * @name Object3D#scale
  7952. * @type {Vector3}
  7953. * @default (1,1,1)
  7954. */
  7955. scale: {
  7956. configurable: true,
  7957. enumerable: true,
  7958. value: scale
  7959. },
  7960. /**
  7961. * Represents the object's model-view matrix.
  7962. *
  7963. * @name Object3D#modelViewMatrix
  7964. * @type {Matrix4}
  7965. */
  7966. modelViewMatrix: {
  7967. value: new Matrix4()
  7968. },
  7969. /**
  7970. * Represents the object's normal matrix.
  7971. *
  7972. * @name Object3D#normalMatrix
  7973. * @type {Matrix3}
  7974. */
  7975. normalMatrix: {
  7976. value: new Matrix3()
  7977. }
  7978. } );
  7979. /**
  7980. * Represents the object's transformation matrix in local space.
  7981. *
  7982. * @type {Matrix4}
  7983. */
  7984. this.matrix = new Matrix4();
  7985. /**
  7986. * Represents the object's transformation matrix in world space.
  7987. * If the 3D object has no parent, then it's identical to the local transformation matrix
  7988. *
  7989. * @type {Matrix4}
  7990. */
  7991. this.matrixWorld = new Matrix4();
  7992. /**
  7993. * When set to `true`, the engine automatically computes the local matrix from position,
  7994. * rotation and scale every frame.
  7995. *
  7996. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  7997. *
  7998. * @type {boolean}
  7999. * @default true
  8000. */
  8001. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  8002. /**
  8003. * When set to `true`, the engine automatically computes the world matrix from the current local
  8004. * matrix and the object's transformation hierarchy.
  8005. *
  8006. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  8007. *
  8008. * @type {boolean}
  8009. * @default true
  8010. */
  8011. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  8012. /**
  8013. * When set to `true`, it calculates the world matrix in that frame and resets this property
  8014. * to `false`.
  8015. *
  8016. * @type {boolean}
  8017. * @default false
  8018. */
  8019. this.matrixWorldNeedsUpdate = false;
  8020. /**
  8021. * The layer membership of the 3D object. The 3D object is only visible if it has
  8022. * at least one layer in common with the camera in use. This property can also be
  8023. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  8024. *
  8025. * @type {Layers}
  8026. */
  8027. this.layers = new Layers();
  8028. /**
  8029. * When set to `true`, the 3D object gets rendered.
  8030. *
  8031. * @type {boolean}
  8032. * @default true
  8033. */
  8034. this.visible = true;
  8035. /**
  8036. * When set to `true`, the 3D object gets rendered into shadow maps.
  8037. *
  8038. * @type {boolean}
  8039. * @default false
  8040. */
  8041. this.castShadow = false;
  8042. /**
  8043. * When set to `true`, the 3D object is affected by shadows in the scene.
  8044. *
  8045. * @type {boolean}
  8046. * @default false
  8047. */
  8048. this.receiveShadow = false;
  8049. /**
  8050. * When set to `true`, the 3D object is honored by view frustum culling.
  8051. *
  8052. * @type {boolean}
  8053. * @default true
  8054. */
  8055. this.frustumCulled = true;
  8056. /**
  8057. * This value allows the default rendering order of scene graph objects to be
  8058. * overridden although opaque and transparent objects remain sorted independently.
  8059. * When this property is set for an instance of {@link Group},all descendants
  8060. * objects will be sorted and rendered together. Sorting is from lowest to highest
  8061. * render order.
  8062. *
  8063. * @type {number}
  8064. * @default 0
  8065. */
  8066. this.renderOrder = 0;
  8067. /**
  8068. * An array holding the animation clips of the 3D object.
  8069. *
  8070. * @type {Array<AnimationClip>}
  8071. */
  8072. this.animations = [];
  8073. /**
  8074. * An object that can be used to store custom data about the 3D object. It
  8075. * should not hold references to functions as these will not be cloned.
  8076. *
  8077. * @type {Object}
  8078. */
  8079. this.userData = {};
  8080. }
  8081. /**
  8082. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  8083. *
  8084. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8085. * @param {Object3D} object - The 3D object.
  8086. * @param {Camera} camera - The camera that is used to render the scene.
  8087. * @param {Camera} shadowCamera - The shadow camera.
  8088. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8089. * @param {Material} depthMaterial - The depth material.
  8090. * @param {Object} group - The geometry group data.
  8091. */
  8092. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  8093. /**
  8094. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  8095. *
  8096. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8097. * @param {Object3D} object - The 3D object.
  8098. * @param {Camera} camera - The camera that is used to render the scene.
  8099. * @param {Camera} shadowCamera - The shadow camera.
  8100. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8101. * @param {Material} depthMaterial - The depth material.
  8102. * @param {Object} group - The geometry group data.
  8103. */
  8104. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  8105. /**
  8106. * A callback that is executed immediately before a 3D object is rendered.
  8107. *
  8108. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8109. * @param {Object3D} object - The 3D object.
  8110. * @param {Camera} camera - The camera that is used to render the scene.
  8111. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8112. * @param {Material} material - The 3D object's material.
  8113. * @param {Object} group - The geometry group data.
  8114. */
  8115. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  8116. /**
  8117. * A callback that is executed immediately after a 3D object is rendered.
  8118. *
  8119. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8120. * @param {Object3D} object - The 3D object.
  8121. * @param {Camera} camera - The camera that is used to render the scene.
  8122. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8123. * @param {Material} material - The 3D object's material.
  8124. * @param {Object} group - The geometry group data.
  8125. */
  8126. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  8127. /**
  8128. * Applies the given transformation matrix to the object and updates the object's position,
  8129. * rotation and scale.
  8130. *
  8131. * @param {Matrix4} matrix - The transformation matrix.
  8132. */
  8133. applyMatrix4( matrix ) {
  8134. if ( this.matrixAutoUpdate ) this.updateMatrix();
  8135. this.matrix.premultiply( matrix );
  8136. this.matrix.decompose( this.position, this.quaternion, this.scale );
  8137. }
  8138. /**
  8139. * Applies a rotation represented by given the quaternion to the 3D object.
  8140. *
  8141. * @param {Quaternion} q - The quaternion.
  8142. * @return {Object3D} A reference to this instance.
  8143. */
  8144. applyQuaternion( q ) {
  8145. this.quaternion.premultiply( q );
  8146. return this;
  8147. }
  8148. /**
  8149. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  8150. *
  8151. * @param {Vector3} axis - The (normalized) axis vector.
  8152. * @param {number} angle - The angle in radians.
  8153. */
  8154. setRotationFromAxisAngle( axis, angle ) {
  8155. // assumes axis is normalized
  8156. this.quaternion.setFromAxisAngle( axis, angle );
  8157. }
  8158. /**
  8159. * Sets the given rotation represented as Euler angles to the 3D object.
  8160. *
  8161. * @param {Euler} euler - The Euler angles.
  8162. */
  8163. setRotationFromEuler( euler ) {
  8164. this.quaternion.setFromEuler( euler, true );
  8165. }
  8166. /**
  8167. * Sets the given rotation represented as rotation matrix to the 3D object.
  8168. *
  8169. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  8170. * a pure rotation matrix (i.e, unscaled).
  8171. */
  8172. setRotationFromMatrix( m ) {
  8173. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8174. this.quaternion.setFromRotationMatrix( m );
  8175. }
  8176. /**
  8177. * Sets the given rotation represented as a Quaternion to the 3D object.
  8178. *
  8179. * @param {Quaternion} q - The Quaternion
  8180. */
  8181. setRotationFromQuaternion( q ) {
  8182. // assumes q is normalized
  8183. this.quaternion.copy( q );
  8184. }
  8185. /**
  8186. * Rotates the 3D object along an axis in local space.
  8187. *
  8188. * @param {Vector3} axis - The (normalized) axis vector.
  8189. * @param {number} angle - The angle in radians.
  8190. * @return {Object3D} A reference to this instance.
  8191. */
  8192. rotateOnAxis( axis, angle ) {
  8193. // rotate object on axis in object space
  8194. // axis is assumed to be normalized
  8195. _q1.setFromAxisAngle( axis, angle );
  8196. this.quaternion.multiply( _q1 );
  8197. return this;
  8198. }
  8199. /**
  8200. * Rotates the 3D object along an axis in world space.
  8201. *
  8202. * @param {Vector3} axis - The (normalized) axis vector.
  8203. * @param {number} angle - The angle in radians.
  8204. * @return {Object3D} A reference to this instance.
  8205. */
  8206. rotateOnWorldAxis( axis, angle ) {
  8207. // rotate object on axis in world space
  8208. // axis is assumed to be normalized
  8209. // method assumes no rotated parent
  8210. _q1.setFromAxisAngle( axis, angle );
  8211. this.quaternion.premultiply( _q1 );
  8212. return this;
  8213. }
  8214. /**
  8215. * Rotates the 3D object around its X axis in local space.
  8216. *
  8217. * @param {number} angle - The angle in radians.
  8218. * @return {Object3D} A reference to this instance.
  8219. */
  8220. rotateX( angle ) {
  8221. return this.rotateOnAxis( _xAxis, angle );
  8222. }
  8223. /**
  8224. * Rotates the 3D object around its Y axis in local space.
  8225. *
  8226. * @param {number} angle - The angle in radians.
  8227. * @return {Object3D} A reference to this instance.
  8228. */
  8229. rotateY( angle ) {
  8230. return this.rotateOnAxis( _yAxis, angle );
  8231. }
  8232. /**
  8233. * Rotates the 3D object around its Z axis in local space.
  8234. *
  8235. * @param {number} angle - The angle in radians.
  8236. * @return {Object3D} A reference to this instance.
  8237. */
  8238. rotateZ( angle ) {
  8239. return this.rotateOnAxis( _zAxis, angle );
  8240. }
  8241. /**
  8242. * Translate the 3D object by a distance along the given axis in local space.
  8243. *
  8244. * @param {Vector3} axis - The (normalized) axis vector.
  8245. * @param {number} distance - The distance in world units.
  8246. * @return {Object3D} A reference to this instance.
  8247. */
  8248. translateOnAxis( axis, distance ) {
  8249. // translate object by distance along axis in object space
  8250. // axis is assumed to be normalized
  8251. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  8252. this.position.add( _v1$4.multiplyScalar( distance ) );
  8253. return this;
  8254. }
  8255. /**
  8256. * Translate the 3D object by a distance along its X-axis in local space.
  8257. *
  8258. * @param {number} distance - The distance in world units.
  8259. * @return {Object3D} A reference to this instance.
  8260. */
  8261. translateX( distance ) {
  8262. return this.translateOnAxis( _xAxis, distance );
  8263. }
  8264. /**
  8265. * Translate the 3D object by a distance along its Y-axis in local space.
  8266. *
  8267. * @param {number} distance - The distance in world units.
  8268. * @return {Object3D} A reference to this instance.
  8269. */
  8270. translateY( distance ) {
  8271. return this.translateOnAxis( _yAxis, distance );
  8272. }
  8273. /**
  8274. * Translate the 3D object by a distance along its Z-axis in local space.
  8275. *
  8276. * @param {number} distance - The distance in world units.
  8277. * @return {Object3D} A reference to this instance.
  8278. */
  8279. translateZ( distance ) {
  8280. return this.translateOnAxis( _zAxis, distance );
  8281. }
  8282. /**
  8283. * Converts the given vector from this 3D object's local space to world space.
  8284. *
  8285. * @param {Vector3} vector - The vector to convert.
  8286. * @return {Vector3} The converted vector.
  8287. */
  8288. localToWorld( vector ) {
  8289. this.updateWorldMatrix( true, false );
  8290. return vector.applyMatrix4( this.matrixWorld );
  8291. }
  8292. /**
  8293. * Converts the given vector from this 3D object's word space to local space.
  8294. *
  8295. * @param {Vector3} vector - The vector to convert.
  8296. * @return {Vector3} The converted vector.
  8297. */
  8298. worldToLocal( vector ) {
  8299. this.updateWorldMatrix( true, false );
  8300. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  8301. }
  8302. /**
  8303. * Rotates the object to face a point in world space.
  8304. *
  8305. * This method does not support objects having non-uniformly-scaled parent(s).
  8306. *
  8307. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  8308. * @param {number} [y] - The y coordinate in world space.
  8309. * @param {number} [z] - The z coordinate in world space.
  8310. */
  8311. lookAt( x, y, z ) {
  8312. // This method does not support objects having non-uniformly-scaled parent(s)
  8313. if ( x.isVector3 ) {
  8314. _target.copy( x );
  8315. } else {
  8316. _target.set( x, y, z );
  8317. }
  8318. const parent = this.parent;
  8319. this.updateWorldMatrix( true, false );
  8320. _position$3.setFromMatrixPosition( this.matrixWorld );
  8321. if ( this.isCamera || this.isLight ) {
  8322. _m1$3.lookAt( _position$3, _target, this.up );
  8323. } else {
  8324. _m1$3.lookAt( _target, _position$3, this.up );
  8325. }
  8326. this.quaternion.setFromRotationMatrix( _m1$3 );
  8327. if ( parent ) {
  8328. _m1$3.extractRotation( parent.matrixWorld );
  8329. _q1.setFromRotationMatrix( _m1$3 );
  8330. this.quaternion.premultiply( _q1.invert() );
  8331. }
  8332. }
  8333. /**
  8334. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  8335. * objects may be added. Any current parent on an object passed in here will be
  8336. * removed, since an object can have at most one parent.
  8337. *
  8338. * @fires Object3D#added
  8339. * @fires Object3D#childadded
  8340. * @param {Object3D} object - The 3D object to add.
  8341. * @return {Object3D} A reference to this instance.
  8342. */
  8343. add( object ) {
  8344. if ( arguments.length > 1 ) {
  8345. for ( let i = 0; i < arguments.length; i ++ ) {
  8346. this.add( arguments[ i ] );
  8347. }
  8348. return this;
  8349. }
  8350. if ( object === this ) {
  8351. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  8352. return this;
  8353. }
  8354. if ( object && object.isObject3D ) {
  8355. object.removeFromParent();
  8356. object.parent = this;
  8357. this.children.push( object );
  8358. object.dispatchEvent( _addedEvent );
  8359. _childaddedEvent.child = object;
  8360. this.dispatchEvent( _childaddedEvent );
  8361. _childaddedEvent.child = null;
  8362. } else {
  8363. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  8364. }
  8365. return this;
  8366. }
  8367. /**
  8368. * Removes the given 3D object as child from this 3D object.
  8369. * An arbitrary number of objects may be removed.
  8370. *
  8371. * @fires Object3D#removed
  8372. * @fires Object3D#childremoved
  8373. * @param {Object3D} object - The 3D object to remove.
  8374. * @return {Object3D} A reference to this instance.
  8375. */
  8376. remove( object ) {
  8377. if ( arguments.length > 1 ) {
  8378. for ( let i = 0; i < arguments.length; i ++ ) {
  8379. this.remove( arguments[ i ] );
  8380. }
  8381. return this;
  8382. }
  8383. const index = this.children.indexOf( object );
  8384. if ( index !== -1 ) {
  8385. object.parent = null;
  8386. this.children.splice( index, 1 );
  8387. object.dispatchEvent( _removedEvent );
  8388. _childremovedEvent.child = object;
  8389. this.dispatchEvent( _childremovedEvent );
  8390. _childremovedEvent.child = null;
  8391. }
  8392. return this;
  8393. }
  8394. /**
  8395. * Removes this 3D object from its current parent.
  8396. *
  8397. * @fires Object3D#removed
  8398. * @fires Object3D#childremoved
  8399. * @return {Object3D} A reference to this instance.
  8400. */
  8401. removeFromParent() {
  8402. const parent = this.parent;
  8403. if ( parent !== null ) {
  8404. parent.remove( this );
  8405. }
  8406. return this;
  8407. }
  8408. /**
  8409. * Removes all child objects.
  8410. *
  8411. * @fires Object3D#removed
  8412. * @fires Object3D#childremoved
  8413. * @return {Object3D} A reference to this instance.
  8414. */
  8415. clear() {
  8416. return this.remove( ... this.children );
  8417. }
  8418. /**
  8419. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  8420. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  8421. *
  8422. * @fires Object3D#added
  8423. * @fires Object3D#childadded
  8424. * @param {Object3D} object - The 3D object to attach.
  8425. * @return {Object3D} A reference to this instance.
  8426. */
  8427. attach( object ) {
  8428. // adds object as a child of this, while maintaining the object's world transform
  8429. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  8430. this.updateWorldMatrix( true, false );
  8431. _m1$3.copy( this.matrixWorld ).invert();
  8432. if ( object.parent !== null ) {
  8433. object.parent.updateWorldMatrix( true, false );
  8434. _m1$3.multiply( object.parent.matrixWorld );
  8435. }
  8436. object.applyMatrix4( _m1$3 );
  8437. object.removeFromParent();
  8438. object.parent = this;
  8439. this.children.push( object );
  8440. object.updateWorldMatrix( false, true );
  8441. object.dispatchEvent( _addedEvent );
  8442. _childaddedEvent.child = object;
  8443. this.dispatchEvent( _childaddedEvent );
  8444. _childaddedEvent.child = null;
  8445. return this;
  8446. }
  8447. /**
  8448. * Searches through the 3D object and its children, starting with the 3D object
  8449. * itself, and returns the first with a matching ID.
  8450. *
  8451. * @param {number} id - The id.
  8452. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  8453. */
  8454. getObjectById( id ) {
  8455. return this.getObjectByProperty( 'id', id );
  8456. }
  8457. /**
  8458. * Searches through the 3D object and its children, starting with the 3D object
  8459. * itself, and returns the first with a matching name.
  8460. *
  8461. * @param {string} name - The name.
  8462. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  8463. */
  8464. getObjectByName( name ) {
  8465. return this.getObjectByProperty( 'name', name );
  8466. }
  8467. /**
  8468. * Searches through the 3D object and its children, starting with the 3D object
  8469. * itself, and returns the first with a matching property value.
  8470. *
  8471. * @param {string} name - The name of the property.
  8472. * @param {any} value - The value.
  8473. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  8474. */
  8475. getObjectByProperty( name, value ) {
  8476. if ( this[ name ] === value ) return this;
  8477. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  8478. const child = this.children[ i ];
  8479. const object = child.getObjectByProperty( name, value );
  8480. if ( object !== undefined ) {
  8481. return object;
  8482. }
  8483. }
  8484. return undefined;
  8485. }
  8486. /**
  8487. * Searches through the 3D object and its children, starting with the 3D object
  8488. * itself, and returns all 3D objects with a matching property value.
  8489. *
  8490. * @param {string} name - The name of the property.
  8491. * @param {any} value - The value.
  8492. * @param {Array<Object3D>} result - The method stores the result in this array.
  8493. * @return {Array<Object3D>} The found 3D objects.
  8494. */
  8495. getObjectsByProperty( name, value, result = [] ) {
  8496. if ( this[ name ] === value ) result.push( this );
  8497. const children = this.children;
  8498. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8499. children[ i ].getObjectsByProperty( name, value, result );
  8500. }
  8501. return result;
  8502. }
  8503. /**
  8504. * Returns a vector representing the position of the 3D object in world space.
  8505. *
  8506. * @param {Vector3} target - The target vector the result is stored to.
  8507. * @return {Vector3} The 3D object's position in world space.
  8508. */
  8509. getWorldPosition( target ) {
  8510. this.updateWorldMatrix( true, false );
  8511. return target.setFromMatrixPosition( this.matrixWorld );
  8512. }
  8513. /**
  8514. * Returns a Quaternion representing the position of the 3D object in world space.
  8515. *
  8516. * @param {Quaternion} target - The target Quaternion the result is stored to.
  8517. * @return {Quaternion} The 3D object's rotation in world space.
  8518. */
  8519. getWorldQuaternion( target ) {
  8520. this.updateWorldMatrix( true, false );
  8521. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  8522. return target;
  8523. }
  8524. /**
  8525. * Returns a vector representing the scale of the 3D object in world space.
  8526. *
  8527. * @param {Vector3} target - The target vector the result is stored to.
  8528. * @return {Vector3} The 3D object's scale in world space.
  8529. */
  8530. getWorldScale( target ) {
  8531. this.updateWorldMatrix( true, false );
  8532. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  8533. return target;
  8534. }
  8535. /**
  8536. * Returns a vector representing the ("look") direction of the 3D object in world space.
  8537. *
  8538. * @param {Vector3} target - The target vector the result is stored to.
  8539. * @return {Vector3} The 3D object's direction in world space.
  8540. */
  8541. getWorldDirection( target ) {
  8542. this.updateWorldMatrix( true, false );
  8543. const e = this.matrixWorld.elements;
  8544. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  8545. }
  8546. /**
  8547. * Abstract method to get intersections between a casted ray and this
  8548. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  8549. * implement this method in order to use raycasting.
  8550. *
  8551. * @abstract
  8552. * @param {Raycaster} raycaster - The raycaster.
  8553. * @param {Array<Object>} intersects - An array holding the result of the method.
  8554. */
  8555. raycast( /* raycaster, intersects */ ) {}
  8556. /**
  8557. * Executes the callback on this 3D object and all descendants.
  8558. *
  8559. * Note: Modifying the scene graph inside the callback is discouraged.
  8560. *
  8561. * @param {Function} callback - A callback function that allows to process the current 3D object.
  8562. */
  8563. traverse( callback ) {
  8564. callback( this );
  8565. const children = this.children;
  8566. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8567. children[ i ].traverse( callback );
  8568. }
  8569. }
  8570. /**
  8571. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  8572. * Descendants of invisible 3D objects are not traversed.
  8573. *
  8574. * Note: Modifying the scene graph inside the callback is discouraged.
  8575. *
  8576. * @param {Function} callback - A callback function that allows to process the current 3D object.
  8577. */
  8578. traverseVisible( callback ) {
  8579. if ( this.visible === false ) return;
  8580. callback( this );
  8581. const children = this.children;
  8582. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8583. children[ i ].traverseVisible( callback );
  8584. }
  8585. }
  8586. /**
  8587. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  8588. *
  8589. * Note: Modifying the scene graph inside the callback is discouraged.
  8590. *
  8591. * @param {Function} callback - A callback function that allows to process the current 3D object.
  8592. */
  8593. traverseAncestors( callback ) {
  8594. const parent = this.parent;
  8595. if ( parent !== null ) {
  8596. callback( parent );
  8597. parent.traverseAncestors( callback );
  8598. }
  8599. }
  8600. /**
  8601. * Updates the transformation matrix in local space by computing it from the current
  8602. * position, rotation and scale values.
  8603. */
  8604. updateMatrix() {
  8605. this.matrix.compose( this.position, this.quaternion, this.scale );
  8606. this.matrixWorldNeedsUpdate = true;
  8607. }
  8608. /**
  8609. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  8610. *
  8611. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  8612. * local space. The computation of the local and world matrix can be controlled with the
  8613. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  8614. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  8615. *
  8616. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  8617. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  8618. */
  8619. updateMatrixWorld( force ) {
  8620. if ( this.matrixAutoUpdate ) this.updateMatrix();
  8621. if ( this.matrixWorldNeedsUpdate || force ) {
  8622. if ( this.matrixWorldAutoUpdate === true ) {
  8623. if ( this.parent === null ) {
  8624. this.matrixWorld.copy( this.matrix );
  8625. } else {
  8626. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8627. }
  8628. }
  8629. this.matrixWorldNeedsUpdate = false;
  8630. force = true;
  8631. }
  8632. // make sure descendants are updated if required
  8633. const children = this.children;
  8634. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8635. const child = children[ i ];
  8636. child.updateMatrixWorld( force );
  8637. }
  8638. }
  8639. /**
  8640. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  8641. * update of ancestor and descendant nodes.
  8642. *
  8643. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  8644. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  8645. */
  8646. updateWorldMatrix( updateParents, updateChildren ) {
  8647. const parent = this.parent;
  8648. if ( updateParents === true && parent !== null ) {
  8649. parent.updateWorldMatrix( true, false );
  8650. }
  8651. if ( this.matrixAutoUpdate ) this.updateMatrix();
  8652. if ( this.matrixWorldAutoUpdate === true ) {
  8653. if ( this.parent === null ) {
  8654. this.matrixWorld.copy( this.matrix );
  8655. } else {
  8656. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8657. }
  8658. }
  8659. // make sure descendants are updated
  8660. if ( updateChildren === true ) {
  8661. const children = this.children;
  8662. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8663. const child = children[ i ];
  8664. child.updateWorldMatrix( false, true );
  8665. }
  8666. }
  8667. }
  8668. /**
  8669. * Serializes the 3D object into JSON.
  8670. *
  8671. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  8672. * @return {Object} A JSON object representing the serialized 3D object.
  8673. * @see {@link ObjectLoader#parse}
  8674. */
  8675. toJSON( meta ) {
  8676. // meta is a string when called from JSON.stringify
  8677. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  8678. const output = {};
  8679. // meta is a hash used to collect geometries, materials.
  8680. // not providing it implies that this is the root object
  8681. // being serialized.
  8682. if ( isRootObject ) {
  8683. // initialize meta obj
  8684. meta = {
  8685. geometries: {},
  8686. materials: {},
  8687. textures: {},
  8688. images: {},
  8689. shapes: {},
  8690. skeletons: {},
  8691. animations: {},
  8692. nodes: {}
  8693. };
  8694. output.metadata = {
  8695. version: 4.6,
  8696. type: 'Object',
  8697. generator: 'Object3D.toJSON'
  8698. };
  8699. }
  8700. // standard Object3D serialization
  8701. const object = {};
  8702. object.uuid = this.uuid;
  8703. object.type = this.type;
  8704. if ( this.name !== '' ) object.name = this.name;
  8705. if ( this.castShadow === true ) object.castShadow = true;
  8706. if ( this.receiveShadow === true ) object.receiveShadow = true;
  8707. if ( this.visible === false ) object.visible = false;
  8708. if ( this.frustumCulled === false ) object.frustumCulled = false;
  8709. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  8710. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  8711. object.layers = this.layers.mask;
  8712. object.matrix = this.matrix.toArray();
  8713. object.up = this.up.toArray();
  8714. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  8715. // object specific properties
  8716. if ( this.isInstancedMesh ) {
  8717. object.type = 'InstancedMesh';
  8718. object.count = this.count;
  8719. object.instanceMatrix = this.instanceMatrix.toJSON();
  8720. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  8721. }
  8722. if ( this.isBatchedMesh ) {
  8723. object.type = 'BatchedMesh';
  8724. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  8725. object.sortObjects = this.sortObjects;
  8726. object.drawRanges = this._drawRanges;
  8727. object.reservedRanges = this._reservedRanges;
  8728. object.visibility = this._visibility;
  8729. object.active = this._active;
  8730. object.bounds = this._bounds.map( bound => ( {
  8731. boxInitialized: bound.boxInitialized,
  8732. boxMin: bound.box.min.toArray(),
  8733. boxMax: bound.box.max.toArray(),
  8734. sphereInitialized: bound.sphereInitialized,
  8735. sphereRadius: bound.sphere.radius,
  8736. sphereCenter: bound.sphere.center.toArray()
  8737. } ) );
  8738. object.maxInstanceCount = this._maxInstanceCount;
  8739. object.maxVertexCount = this._maxVertexCount;
  8740. object.maxIndexCount = this._maxIndexCount;
  8741. object.geometryInitialized = this._geometryInitialized;
  8742. object.geometryCount = this._geometryCount;
  8743. object.matricesTexture = this._matricesTexture.toJSON( meta );
  8744. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  8745. if ( this.boundingSphere !== null ) {
  8746. object.boundingSphere = {
  8747. center: object.boundingSphere.center.toArray(),
  8748. radius: object.boundingSphere.radius
  8749. };
  8750. }
  8751. if ( this.boundingBox !== null ) {
  8752. object.boundingBox = {
  8753. min: object.boundingBox.min.toArray(),
  8754. max: object.boundingBox.max.toArray()
  8755. };
  8756. }
  8757. }
  8758. //
  8759. function serialize( library, element ) {
  8760. if ( library[ element.uuid ] === undefined ) {
  8761. library[ element.uuid ] = element.toJSON( meta );
  8762. }
  8763. return element.uuid;
  8764. }
  8765. if ( this.isScene ) {
  8766. if ( this.background ) {
  8767. if ( this.background.isColor ) {
  8768. object.background = this.background.toJSON();
  8769. } else if ( this.background.isTexture ) {
  8770. object.background = this.background.toJSON( meta ).uuid;
  8771. }
  8772. }
  8773. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  8774. object.environment = this.environment.toJSON( meta ).uuid;
  8775. }
  8776. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  8777. object.geometry = serialize( meta.geometries, this.geometry );
  8778. const parameters = this.geometry.parameters;
  8779. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  8780. const shapes = parameters.shapes;
  8781. if ( Array.isArray( shapes ) ) {
  8782. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  8783. const shape = shapes[ i ];
  8784. serialize( meta.shapes, shape );
  8785. }
  8786. } else {
  8787. serialize( meta.shapes, shapes );
  8788. }
  8789. }
  8790. }
  8791. if ( this.isSkinnedMesh ) {
  8792. object.bindMode = this.bindMode;
  8793. object.bindMatrix = this.bindMatrix.toArray();
  8794. if ( this.skeleton !== undefined ) {
  8795. serialize( meta.skeletons, this.skeleton );
  8796. object.skeleton = this.skeleton.uuid;
  8797. }
  8798. }
  8799. if ( this.material !== undefined ) {
  8800. if ( Array.isArray( this.material ) ) {
  8801. const uuids = [];
  8802. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  8803. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  8804. }
  8805. object.material = uuids;
  8806. } else {
  8807. object.material = serialize( meta.materials, this.material );
  8808. }
  8809. }
  8810. //
  8811. if ( this.children.length > 0 ) {
  8812. object.children = [];
  8813. for ( let i = 0; i < this.children.length; i ++ ) {
  8814. object.children.push( this.children[ i ].toJSON( meta ).object );
  8815. }
  8816. }
  8817. //
  8818. if ( this.animations.length > 0 ) {
  8819. object.animations = [];
  8820. for ( let i = 0; i < this.animations.length; i ++ ) {
  8821. const animation = this.animations[ i ];
  8822. object.animations.push( serialize( meta.animations, animation ) );
  8823. }
  8824. }
  8825. if ( isRootObject ) {
  8826. const geometries = extractFromCache( meta.geometries );
  8827. const materials = extractFromCache( meta.materials );
  8828. const textures = extractFromCache( meta.textures );
  8829. const images = extractFromCache( meta.images );
  8830. const shapes = extractFromCache( meta.shapes );
  8831. const skeletons = extractFromCache( meta.skeletons );
  8832. const animations = extractFromCache( meta.animations );
  8833. const nodes = extractFromCache( meta.nodes );
  8834. if ( geometries.length > 0 ) output.geometries = geometries;
  8835. if ( materials.length > 0 ) output.materials = materials;
  8836. if ( textures.length > 0 ) output.textures = textures;
  8837. if ( images.length > 0 ) output.images = images;
  8838. if ( shapes.length > 0 ) output.shapes = shapes;
  8839. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  8840. if ( animations.length > 0 ) output.animations = animations;
  8841. if ( nodes.length > 0 ) output.nodes = nodes;
  8842. }
  8843. output.object = object;
  8844. return output;
  8845. // extract data from the cache hash
  8846. // remove metadata on each item
  8847. // and return as array
  8848. function extractFromCache( cache ) {
  8849. const values = [];
  8850. for ( const key in cache ) {
  8851. const data = cache[ key ];
  8852. delete data.metadata;
  8853. values.push( data );
  8854. }
  8855. return values;
  8856. }
  8857. }
  8858. /**
  8859. * Returns a new 3D object with copied values from this instance.
  8860. *
  8861. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  8862. * @return {Object3D} A clone of this instance.
  8863. */
  8864. clone( recursive ) {
  8865. return new this.constructor().copy( this, recursive );
  8866. }
  8867. /**
  8868. * Copies the values of the given 3D object to this instance.
  8869. *
  8870. * @param {Object3D} source - The 3D object to copy.
  8871. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  8872. * @return {Object3D} A reference to this instance.
  8873. */
  8874. copy( source, recursive = true ) {
  8875. this.name = source.name;
  8876. this.up.copy( source.up );
  8877. this.position.copy( source.position );
  8878. this.rotation.order = source.rotation.order;
  8879. this.quaternion.copy( source.quaternion );
  8880. this.scale.copy( source.scale );
  8881. this.matrix.copy( source.matrix );
  8882. this.matrixWorld.copy( source.matrixWorld );
  8883. this.matrixAutoUpdate = source.matrixAutoUpdate;
  8884. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  8885. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  8886. this.layers.mask = source.layers.mask;
  8887. this.visible = source.visible;
  8888. this.castShadow = source.castShadow;
  8889. this.receiveShadow = source.receiveShadow;
  8890. this.frustumCulled = source.frustumCulled;
  8891. this.renderOrder = source.renderOrder;
  8892. this.animations = source.animations.slice();
  8893. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  8894. if ( recursive === true ) {
  8895. for ( let i = 0; i < source.children.length; i ++ ) {
  8896. const child = source.children[ i ];
  8897. this.add( child.clone() );
  8898. }
  8899. }
  8900. return this;
  8901. }
  8902. }
  8903. /**
  8904. * The default up direction for objects, also used as the default
  8905. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  8906. *
  8907. * @static
  8908. * @type {Vector3}
  8909. * @default (0,1,0)
  8910. */
  8911. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  8912. /**
  8913. * The default setting for {@link Object3D#matrixAutoUpdate} for
  8914. * newly created 3D objects.
  8915. *
  8916. * @static
  8917. * @type {boolean}
  8918. * @default true
  8919. */
  8920. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  8921. /**
  8922. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  8923. * newly created 3D objects.
  8924. *
  8925. * @static
  8926. * @type {boolean}
  8927. * @default true
  8928. */
  8929. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  8930. const _v0$2 = /*@__PURE__*/ new Vector3();
  8931. const _v1$3 = /*@__PURE__*/ new Vector3();
  8932. const _v2$2 = /*@__PURE__*/ new Vector3();
  8933. const _v3$2 = /*@__PURE__*/ new Vector3();
  8934. const _vab = /*@__PURE__*/ new Vector3();
  8935. const _vac = /*@__PURE__*/ new Vector3();
  8936. const _vbc = /*@__PURE__*/ new Vector3();
  8937. const _vap = /*@__PURE__*/ new Vector3();
  8938. const _vbp = /*@__PURE__*/ new Vector3();
  8939. const _vcp = /*@__PURE__*/ new Vector3();
  8940. const _v40 = /*@__PURE__*/ new Vector4();
  8941. const _v41 = /*@__PURE__*/ new Vector4();
  8942. const _v42 = /*@__PURE__*/ new Vector4();
  8943. /**
  8944. * A geometric triangle as defined by three vectors representing its three corners.
  8945. */
  8946. class Triangle {
  8947. /**
  8948. * Constructs a new triangle.
  8949. *
  8950. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  8951. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  8952. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  8953. */
  8954. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  8955. /**
  8956. * The first corner of the triangle.
  8957. *
  8958. * @type {Vector3}
  8959. */
  8960. this.a = a;
  8961. /**
  8962. * The second corner of the triangle.
  8963. *
  8964. * @type {Vector3}
  8965. */
  8966. this.b = b;
  8967. /**
  8968. * The third corner of the triangle.
  8969. *
  8970. * @type {Vector3}
  8971. */
  8972. this.c = c;
  8973. }
  8974. /**
  8975. * Computes the normal vector of a triangle.
  8976. *
  8977. * @param {Vector3} a - The first corner of the triangle.
  8978. * @param {Vector3} b - The second corner of the triangle.
  8979. * @param {Vector3} c - The third corner of the triangle.
  8980. * @param {Vector3} target - The target vector that is used to store the method's result.
  8981. * @return {Vector3} The triangle's normal.
  8982. */
  8983. static getNormal( a, b, c, target ) {
  8984. target.subVectors( c, b );
  8985. _v0$2.subVectors( a, b );
  8986. target.cross( _v0$2 );
  8987. const targetLengthSq = target.lengthSq();
  8988. if ( targetLengthSq > 0 ) {
  8989. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  8990. }
  8991. return target.set( 0, 0, 0 );
  8992. }
  8993. /**
  8994. * Computes a barycentric coordinates from the given vector.
  8995. * Returns `null` if the triangle is degenerate.
  8996. *
  8997. * @param {Vector3} point - A point in 3D space.
  8998. * @param {Vector3} a - The first corner of the triangle.
  8999. * @param {Vector3} b - The second corner of the triangle.
  9000. * @param {Vector3} c - The third corner of the triangle.
  9001. * @param {Vector3} target - The target vector that is used to store the method's result.
  9002. * @return {?Vector3} The barycentric coordinates for the given point
  9003. */
  9004. static getBarycoord( point, a, b, c, target ) {
  9005. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  9006. _v0$2.subVectors( c, a );
  9007. _v1$3.subVectors( b, a );
  9008. _v2$2.subVectors( point, a );
  9009. const dot00 = _v0$2.dot( _v0$2 );
  9010. const dot01 = _v0$2.dot( _v1$3 );
  9011. const dot02 = _v0$2.dot( _v2$2 );
  9012. const dot11 = _v1$3.dot( _v1$3 );
  9013. const dot12 = _v1$3.dot( _v2$2 );
  9014. const denom = ( dot00 * dot11 - dot01 * dot01 );
  9015. // collinear or singular triangle
  9016. if ( denom === 0 ) {
  9017. target.set( 0, 0, 0 );
  9018. return null;
  9019. }
  9020. const invDenom = 1 / denom;
  9021. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  9022. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  9023. // barycentric coordinates must always sum to 1
  9024. return target.set( 1 - u - v, v, u );
  9025. }
  9026. /**
  9027. * Returns `true` if the given point, when projected onto the plane of the
  9028. * triangle, lies within the triangle.
  9029. *
  9030. * @param {Vector3} point - The point in 3D space to test.
  9031. * @param {Vector3} a - The first corner of the triangle.
  9032. * @param {Vector3} b - The second corner of the triangle.
  9033. * @param {Vector3} c - The third corner of the triangle.
  9034. * @return {boolean} Whether the given point, when projected onto the plane of the
  9035. * triangle, lies within the triangle or not.
  9036. */
  9037. static containsPoint( point, a, b, c ) {
  9038. // if the triangle is degenerate then we can't contain a point
  9039. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  9040. return false;
  9041. }
  9042. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  9043. }
  9044. /**
  9045. * Computes the value barycentrically interpolated for the given point on the
  9046. * triangle. Returns `null` if the triangle is degenerate.
  9047. *
  9048. * @param {Vector3} point - Position of interpolated point.
  9049. * @param {Vector3} p1 - The first corner of the triangle.
  9050. * @param {Vector3} p2 - The second corner of the triangle.
  9051. * @param {Vector3} p3 - The third corner of the triangle.
  9052. * @param {Vector3} v1 - Value to interpolate of first vertex.
  9053. * @param {Vector3} v2 - Value to interpolate of second vertex.
  9054. * @param {Vector3} v3 - Value to interpolate of third vertex.
  9055. * @param {Vector3} target - The target vector that is used to store the method's result.
  9056. * @return {?Vector3} The interpolated value.
  9057. */
  9058. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  9059. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  9060. target.x = 0;
  9061. target.y = 0;
  9062. if ( 'z' in target ) target.z = 0;
  9063. if ( 'w' in target ) target.w = 0;
  9064. return null;
  9065. }
  9066. target.setScalar( 0 );
  9067. target.addScaledVector( v1, _v3$2.x );
  9068. target.addScaledVector( v2, _v3$2.y );
  9069. target.addScaledVector( v3, _v3$2.z );
  9070. return target;
  9071. }
  9072. /**
  9073. * Computes the value barycentrically interpolated for the given attribute and indices.
  9074. *
  9075. * @param {BufferAttribute} attr - The attribute to interpolate.
  9076. * @param {number} i1 - Index of first vertex.
  9077. * @param {number} i2 - Index of second vertex.
  9078. * @param {number} i3 - Index of third vertex.
  9079. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  9080. * @param {Vector3} target - The target vector that is used to store the method's result.
  9081. * @return {Vector3} The interpolated attribute value.
  9082. */
  9083. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  9084. _v40.setScalar( 0 );
  9085. _v41.setScalar( 0 );
  9086. _v42.setScalar( 0 );
  9087. _v40.fromBufferAttribute( attr, i1 );
  9088. _v41.fromBufferAttribute( attr, i2 );
  9089. _v42.fromBufferAttribute( attr, i3 );
  9090. target.setScalar( 0 );
  9091. target.addScaledVector( _v40, barycoord.x );
  9092. target.addScaledVector( _v41, barycoord.y );
  9093. target.addScaledVector( _v42, barycoord.z );
  9094. return target;
  9095. }
  9096. /**
  9097. * Returns `true` if the triangle is oriented towards the given direction.
  9098. *
  9099. * @param {Vector3} a - The first corner of the triangle.
  9100. * @param {Vector3} b - The second corner of the triangle.
  9101. * @param {Vector3} c - The third corner of the triangle.
  9102. * @param {Vector3} direction - The (normalized) direction vector.
  9103. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  9104. */
  9105. static isFrontFacing( a, b, c, direction ) {
  9106. _v0$2.subVectors( c, b );
  9107. _v1$3.subVectors( a, b );
  9108. // strictly front facing
  9109. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  9110. }
  9111. /**
  9112. * Sets the triangle's vertices by copying the given values.
  9113. *
  9114. * @param {Vector3} a - The first corner of the triangle.
  9115. * @param {Vector3} b - The second corner of the triangle.
  9116. * @param {Vector3} c - The third corner of the triangle.
  9117. * @return {Triangle} A reference to this triangle.
  9118. */
  9119. set( a, b, c ) {
  9120. this.a.copy( a );
  9121. this.b.copy( b );
  9122. this.c.copy( c );
  9123. return this;
  9124. }
  9125. /**
  9126. * Sets the triangle's vertices by copying the given array values.
  9127. *
  9128. * @param {Array<Vector3>} points - An array with 3D points.
  9129. * @param {number} i0 - The array index representing the first corner of the triangle.
  9130. * @param {number} i1 - The array index representing the second corner of the triangle.
  9131. * @param {number} i2 - The array index representing the third corner of the triangle.
  9132. * @return {Triangle} A reference to this triangle.
  9133. */
  9134. setFromPointsAndIndices( points, i0, i1, i2 ) {
  9135. this.a.copy( points[ i0 ] );
  9136. this.b.copy( points[ i1 ] );
  9137. this.c.copy( points[ i2 ] );
  9138. return this;
  9139. }
  9140. /**
  9141. * Sets the triangle's vertices by copying the given attribute values.
  9142. *
  9143. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  9144. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  9145. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  9146. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  9147. * @return {Triangle} A reference to this triangle.
  9148. */
  9149. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  9150. this.a.fromBufferAttribute( attribute, i0 );
  9151. this.b.fromBufferAttribute( attribute, i1 );
  9152. this.c.fromBufferAttribute( attribute, i2 );
  9153. return this;
  9154. }
  9155. /**
  9156. * Returns a new triangle with copied values from this instance.
  9157. *
  9158. * @return {Triangle} A clone of this instance.
  9159. */
  9160. clone() {
  9161. return new this.constructor().copy( this );
  9162. }
  9163. /**
  9164. * Copies the values of the given triangle to this instance.
  9165. *
  9166. * @param {Triangle} triangle - The triangle to copy.
  9167. * @return {Triangle} A reference to this triangle.
  9168. */
  9169. copy( triangle ) {
  9170. this.a.copy( triangle.a );
  9171. this.b.copy( triangle.b );
  9172. this.c.copy( triangle.c );
  9173. return this;
  9174. }
  9175. /**
  9176. * Computes the area of the triangle.
  9177. *
  9178. * @return {number} The triangle's area.
  9179. */
  9180. getArea() {
  9181. _v0$2.subVectors( this.c, this.b );
  9182. _v1$3.subVectors( this.a, this.b );
  9183. return _v0$2.cross( _v1$3 ).length() * 0.5;
  9184. }
  9185. /**
  9186. * Computes the midpoint of the triangle.
  9187. *
  9188. * @param {Vector3} target - The target vector that is used to store the method's result.
  9189. * @return {Vector3} The triangle's midpoint.
  9190. */
  9191. getMidpoint( target ) {
  9192. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  9193. }
  9194. /**
  9195. * Computes the normal of the triangle.
  9196. *
  9197. * @param {Vector3} target - The target vector that is used to store the method's result.
  9198. * @return {Vector3} The triangle's normal.
  9199. */
  9200. getNormal( target ) {
  9201. return Triangle.getNormal( this.a, this.b, this.c, target );
  9202. }
  9203. /**
  9204. * Computes a plane the triangle lies within.
  9205. *
  9206. * @param {Plane} target - The target vector that is used to store the method's result.
  9207. * @return {Plane} The plane the triangle lies within.
  9208. */
  9209. getPlane( target ) {
  9210. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  9211. }
  9212. /**
  9213. * Computes a barycentric coordinates from the given vector.
  9214. * Returns `null` if the triangle is degenerate.
  9215. *
  9216. * @param {Vector3} point - A point in 3D space.
  9217. * @param {Vector3} target - The target vector that is used to store the method's result.
  9218. * @return {?Vector3} The barycentric coordinates for the given point
  9219. */
  9220. getBarycoord( point, target ) {
  9221. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  9222. }
  9223. /**
  9224. * Computes the value barycentrically interpolated for the given point on the
  9225. * triangle. Returns `null` if the triangle is degenerate.
  9226. *
  9227. * @param {Vector3} point - Position of interpolated point.
  9228. * @param {Vector3} v1 - Value to interpolate of first vertex.
  9229. * @param {Vector3} v2 - Value to interpolate of second vertex.
  9230. * @param {Vector3} v3 - Value to interpolate of third vertex.
  9231. * @param {Vector3} target - The target vector that is used to store the method's result.
  9232. * @return {?Vector3} The interpolated value.
  9233. */
  9234. getInterpolation( point, v1, v2, v3, target ) {
  9235. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  9236. }
  9237. /**
  9238. * Returns `true` if the given point, when projected onto the plane of the
  9239. * triangle, lies within the triangle.
  9240. *
  9241. * @param {Vector3} point - The point in 3D space to test.
  9242. * @return {boolean} Whether the given point, when projected onto the plane of the
  9243. * triangle, lies within the triangle or not.
  9244. */
  9245. containsPoint( point ) {
  9246. return Triangle.containsPoint( point, this.a, this.b, this.c );
  9247. }
  9248. /**
  9249. * Returns `true` if the triangle is oriented towards the given direction.
  9250. *
  9251. * @param {Vector3} direction - The (normalized) direction vector.
  9252. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  9253. */
  9254. isFrontFacing( direction ) {
  9255. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  9256. }
  9257. /**
  9258. * Returns `true` if this triangle intersects with the given box.
  9259. *
  9260. * @param {Box3} box - The box to intersect.
  9261. * @return {boolean} Whether this triangle intersects with the given box or not.
  9262. */
  9263. intersectsBox( box ) {
  9264. return box.intersectsTriangle( this );
  9265. }
  9266. /**
  9267. * Returns the closest point on the triangle to the given point.
  9268. *
  9269. * @param {Vector3} p - The point to compute the closest point for.
  9270. * @param {Vector3} target - The target vector that is used to store the method's result.
  9271. * @return {Vector3} The closest point on the triangle.
  9272. */
  9273. closestPointToPoint( p, target ) {
  9274. const a = this.a, b = this.b, c = this.c;
  9275. let v, w;
  9276. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  9277. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  9278. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  9279. // basically, we're distinguishing which of the voronoi regions of the triangle
  9280. // the point lies in with the minimum amount of redundant computation.
  9281. _vab.subVectors( b, a );
  9282. _vac.subVectors( c, a );
  9283. _vap.subVectors( p, a );
  9284. const d1 = _vab.dot( _vap );
  9285. const d2 = _vac.dot( _vap );
  9286. if ( d1 <= 0 && d2 <= 0 ) {
  9287. // vertex region of A; barycentric coords (1, 0, 0)
  9288. return target.copy( a );
  9289. }
  9290. _vbp.subVectors( p, b );
  9291. const d3 = _vab.dot( _vbp );
  9292. const d4 = _vac.dot( _vbp );
  9293. if ( d3 >= 0 && d4 <= d3 ) {
  9294. // vertex region of B; barycentric coords (0, 1, 0)
  9295. return target.copy( b );
  9296. }
  9297. const vc = d1 * d4 - d3 * d2;
  9298. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  9299. v = d1 / ( d1 - d3 );
  9300. // edge region of AB; barycentric coords (1-v, v, 0)
  9301. return target.copy( a ).addScaledVector( _vab, v );
  9302. }
  9303. _vcp.subVectors( p, c );
  9304. const d5 = _vab.dot( _vcp );
  9305. const d6 = _vac.dot( _vcp );
  9306. if ( d6 >= 0 && d5 <= d6 ) {
  9307. // vertex region of C; barycentric coords (0, 0, 1)
  9308. return target.copy( c );
  9309. }
  9310. const vb = d5 * d2 - d1 * d6;
  9311. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  9312. w = d2 / ( d2 - d6 );
  9313. // edge region of AC; barycentric coords (1-w, 0, w)
  9314. return target.copy( a ).addScaledVector( _vac, w );
  9315. }
  9316. const va = d3 * d6 - d5 * d4;
  9317. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  9318. _vbc.subVectors( c, b );
  9319. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  9320. // edge region of BC; barycentric coords (0, 1-w, w)
  9321. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  9322. }
  9323. // face region
  9324. const denom = 1 / ( va + vb + vc );
  9325. // u = va * denom
  9326. v = vb * denom;
  9327. w = vc * denom;
  9328. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  9329. }
  9330. /**
  9331. * Returns `true` if this triangle is equal with the given one.
  9332. *
  9333. * @param {Triangle} triangle - The triangle to test for equality.
  9334. * @return {boolean} Whether this triangle is equal with the given one.
  9335. */
  9336. equals( triangle ) {
  9337. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  9338. }
  9339. }
  9340. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  9341. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  9342. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  9343. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  9344. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  9345. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  9346. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  9347. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  9348. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  9349. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  9350. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  9351. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  9352. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  9353. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  9354. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  9355. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  9356. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  9357. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  9358. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  9359. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  9360. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  9361. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  9362. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  9363. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  9364. const _hslA = { h: 0, s: 0, l: 0 };
  9365. const _hslB = { h: 0, s: 0, l: 0 };
  9366. function hue2rgb( p, q, t ) {
  9367. if ( t < 0 ) t += 1;
  9368. if ( t > 1 ) t -= 1;
  9369. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  9370. if ( t < 1 / 2 ) return q;
  9371. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  9372. return p;
  9373. }
  9374. /**
  9375. * A Color instance is represented by RGB components in the linear <i>working
  9376. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  9377. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  9378. * strings) are converted to the working color space automatically.
  9379. *
  9380. * ```js
  9381. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  9382. * const color = new THREE.Color().setHex( 0x112233 );
  9383. * ```
  9384. * Source color spaces may be specified explicitly, to ensure correct conversions.
  9385. * ```js
  9386. * // assumed already LinearSRGBColorSpace; no conversion
  9387. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  9388. *
  9389. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  9390. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  9391. * ```
  9392. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  9393. * see <i>Color management</i>. Iterating through a Color instance will yield
  9394. * its components (r, g, b) in the corresponding order. A Color can be initialised
  9395. * in any of the following ways:
  9396. * ```js
  9397. * //empty constructor - will default white
  9398. * const color1 = new THREE.Color();
  9399. *
  9400. * //Hexadecimal color (recommended)
  9401. * const color2 = new THREE.Color( 0xff0000 );
  9402. *
  9403. * //RGB string
  9404. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  9405. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  9406. *
  9407. * //X11 color name - all 140 color names are supported.
  9408. * //Note the lack of CamelCase in the name
  9409. * const color5 = new THREE.Color( 'skyblue' );
  9410. * //HSL string
  9411. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  9412. *
  9413. * //Separate RGB values between 0 and 1
  9414. * const color7 = new THREE.Color( 1, 0, 0 );
  9415. * ```
  9416. */
  9417. class Color {
  9418. /**
  9419. * Constructs a new color.
  9420. *
  9421. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  9422. * and that method is used throughout the rest of the documentation.
  9423. *
  9424. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  9425. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  9426. * @param {number} [g] - The green component.
  9427. * @param {number} [b] - The blue component.
  9428. */
  9429. constructor( r, g, b ) {
  9430. /**
  9431. * This flag can be used for type testing.
  9432. *
  9433. * @type {boolean}
  9434. * @readonly
  9435. * @default true
  9436. */
  9437. this.isColor = true;
  9438. /**
  9439. * The red component.
  9440. *
  9441. * @type {number}
  9442. * @default 1
  9443. */
  9444. this.r = 1;
  9445. /**
  9446. * The green component.
  9447. *
  9448. * @type {number}
  9449. * @default 1
  9450. */
  9451. this.g = 1;
  9452. /**
  9453. * The blue component.
  9454. *
  9455. * @type {number}
  9456. * @default 1
  9457. */
  9458. this.b = 1;
  9459. return this.set( r, g, b );
  9460. }
  9461. /**
  9462. * Sets the colors's components from the given values.
  9463. *
  9464. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  9465. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  9466. * @param {number} [g] - The green component.
  9467. * @param {number} [b] - The blue component.
  9468. * @return {Color} A reference to this color.
  9469. */
  9470. set( r, g, b ) {
  9471. if ( g === undefined && b === undefined ) {
  9472. // r is THREE.Color, hex or string
  9473. const value = r;
  9474. if ( value && value.isColor ) {
  9475. this.copy( value );
  9476. } else if ( typeof value === 'number' ) {
  9477. this.setHex( value );
  9478. } else if ( typeof value === 'string' ) {
  9479. this.setStyle( value );
  9480. }
  9481. } else {
  9482. this.setRGB( r, g, b );
  9483. }
  9484. return this;
  9485. }
  9486. /**
  9487. * Sets the colors's components to the given scalar value.
  9488. *
  9489. * @param {number} scalar - The scalar value.
  9490. * @return {Color} A reference to this color.
  9491. */
  9492. setScalar( scalar ) {
  9493. this.r = scalar;
  9494. this.g = scalar;
  9495. this.b = scalar;
  9496. return this;
  9497. }
  9498. /**
  9499. * Sets this color from a hexadecimal value.
  9500. *
  9501. * @param {number} hex - The hexadecimal value.
  9502. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9503. * @return {Color} A reference to this color.
  9504. */
  9505. setHex( hex, colorSpace = SRGBColorSpace ) {
  9506. hex = Math.floor( hex );
  9507. this.r = ( hex >> 16 & 255 ) / 255;
  9508. this.g = ( hex >> 8 & 255 ) / 255;
  9509. this.b = ( hex & 255 ) / 255;
  9510. ColorManagement.toWorkingColorSpace( this, colorSpace );
  9511. return this;
  9512. }
  9513. /**
  9514. * Sets this color from RGB values.
  9515. *
  9516. * @param {number} r - Red channel value between `0.0` and `1.0`.
  9517. * @param {number} g - Green channel value between `0.0` and `1.0`.
  9518. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  9519. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9520. * @return {Color} A reference to this color.
  9521. */
  9522. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  9523. this.r = r;
  9524. this.g = g;
  9525. this.b = b;
  9526. ColorManagement.toWorkingColorSpace( this, colorSpace );
  9527. return this;
  9528. }
  9529. /**
  9530. * Sets this color from RGB values.
  9531. *
  9532. * @param {number} h - Hue value between `0.0` and `1.0`.
  9533. * @param {number} s - Saturation value between `0.0` and `1.0`.
  9534. * @param {number} l - Lightness value between `0.0` and `1.0`.
  9535. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9536. * @return {Color} A reference to this color.
  9537. */
  9538. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  9539. // h,s,l ranges are in 0.0 - 1.0
  9540. h = euclideanModulo( h, 1 );
  9541. s = clamp( s, 0, 1 );
  9542. l = clamp( l, 0, 1 );
  9543. if ( s === 0 ) {
  9544. this.r = this.g = this.b = l;
  9545. } else {
  9546. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  9547. const q = ( 2 * l ) - p;
  9548. this.r = hue2rgb( q, p, h + 1 / 3 );
  9549. this.g = hue2rgb( q, p, h );
  9550. this.b = hue2rgb( q, p, h - 1 / 3 );
  9551. }
  9552. ColorManagement.toWorkingColorSpace( this, colorSpace );
  9553. return this;
  9554. }
  9555. /**
  9556. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  9557. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  9558. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  9559. * all 140 color names are supported).
  9560. *
  9561. * @param {string} style - Color as a CSS-style string.
  9562. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9563. * @return {Color} A reference to this color.
  9564. */
  9565. setStyle( style, colorSpace = SRGBColorSpace ) {
  9566. function handleAlpha( string ) {
  9567. if ( string === undefined ) return;
  9568. if ( parseFloat( string ) < 1 ) {
  9569. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  9570. }
  9571. }
  9572. let m;
  9573. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  9574. // rgb / hsl
  9575. let color;
  9576. const name = m[ 1 ];
  9577. const components = m[ 2 ];
  9578. switch ( name ) {
  9579. case 'rgb':
  9580. case 'rgba':
  9581. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  9582. // rgb(255,0,0) rgba(255,0,0,0.5)
  9583. handleAlpha( color[ 4 ] );
  9584. return this.setRGB(
  9585. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  9586. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  9587. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  9588. colorSpace
  9589. );
  9590. }
  9591. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  9592. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  9593. handleAlpha( color[ 4 ] );
  9594. return this.setRGB(
  9595. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  9596. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  9597. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  9598. colorSpace
  9599. );
  9600. }
  9601. break;
  9602. case 'hsl':
  9603. case 'hsla':
  9604. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  9605. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  9606. handleAlpha( color[ 4 ] );
  9607. return this.setHSL(
  9608. parseFloat( color[ 1 ] ) / 360,
  9609. parseFloat( color[ 2 ] ) / 100,
  9610. parseFloat( color[ 3 ] ) / 100,
  9611. colorSpace
  9612. );
  9613. }
  9614. break;
  9615. default:
  9616. console.warn( 'THREE.Color: Unknown color model ' + style );
  9617. }
  9618. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  9619. // hex color
  9620. const hex = m[ 1 ];
  9621. const size = hex.length;
  9622. if ( size === 3 ) {
  9623. // #ff0
  9624. return this.setRGB(
  9625. parseInt( hex.charAt( 0 ), 16 ) / 15,
  9626. parseInt( hex.charAt( 1 ), 16 ) / 15,
  9627. parseInt( hex.charAt( 2 ), 16 ) / 15,
  9628. colorSpace
  9629. );
  9630. } else if ( size === 6 ) {
  9631. // #ff0000
  9632. return this.setHex( parseInt( hex, 16 ), colorSpace );
  9633. } else {
  9634. console.warn( 'THREE.Color: Invalid hex color ' + style );
  9635. }
  9636. } else if ( style && style.length > 0 ) {
  9637. return this.setColorName( style, colorSpace );
  9638. }
  9639. return this;
  9640. }
  9641. /**
  9642. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  9643. * you don't need the other CSS-style formats.
  9644. *
  9645. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  9646. * ```js
  9647. * Color.NAMES.aliceblue // returns 0xF0F8FF
  9648. * ```
  9649. *
  9650. * @param {string} style - The color name.
  9651. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9652. * @return {Color} A reference to this color.
  9653. */
  9654. setColorName( style, colorSpace = SRGBColorSpace ) {
  9655. // color keywords
  9656. const hex = _colorKeywords[ style.toLowerCase() ];
  9657. if ( hex !== undefined ) {
  9658. // red
  9659. this.setHex( hex, colorSpace );
  9660. } else {
  9661. // unknown color
  9662. console.warn( 'THREE.Color: Unknown color ' + style );
  9663. }
  9664. return this;
  9665. }
  9666. /**
  9667. * Returns a new color with copied values from this instance.
  9668. *
  9669. * @return {Color} A clone of this instance.
  9670. */
  9671. clone() {
  9672. return new this.constructor( this.r, this.g, this.b );
  9673. }
  9674. /**
  9675. * Copies the values of the given color to this instance.
  9676. *
  9677. * @param {Color} color - The color to copy.
  9678. * @return {Color} A reference to this color.
  9679. */
  9680. copy( color ) {
  9681. this.r = color.r;
  9682. this.g = color.g;
  9683. this.b = color.b;
  9684. return this;
  9685. }
  9686. /**
  9687. * Copies the given color into this color, and then converts this color from
  9688. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  9689. *
  9690. * @param {Color} color - The color to copy/convert.
  9691. * @return {Color} A reference to this color.
  9692. */
  9693. copySRGBToLinear( color ) {
  9694. this.r = SRGBToLinear( color.r );
  9695. this.g = SRGBToLinear( color.g );
  9696. this.b = SRGBToLinear( color.b );
  9697. return this;
  9698. }
  9699. /**
  9700. * Copies the given color into this color, and then converts this color from
  9701. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  9702. *
  9703. * @param {Color} color - The color to copy/convert.
  9704. * @return {Color} A reference to this color.
  9705. */
  9706. copyLinearToSRGB( color ) {
  9707. this.r = LinearToSRGB( color.r );
  9708. this.g = LinearToSRGB( color.g );
  9709. this.b = LinearToSRGB( color.b );
  9710. return this;
  9711. }
  9712. /**
  9713. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  9714. *
  9715. * @return {Color} A reference to this color.
  9716. */
  9717. convertSRGBToLinear() {
  9718. this.copySRGBToLinear( this );
  9719. return this;
  9720. }
  9721. /**
  9722. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  9723. *
  9724. * @return {Color} A reference to this color.
  9725. */
  9726. convertLinearToSRGB() {
  9727. this.copyLinearToSRGB( this );
  9728. return this;
  9729. }
  9730. /**
  9731. * Returns the hexadecimal value of this color.
  9732. *
  9733. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9734. * @return {number} The hexadecimal value.
  9735. */
  9736. getHex( colorSpace = SRGBColorSpace ) {
  9737. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9738. 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 ) );
  9739. }
  9740. /**
  9741. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  9742. *
  9743. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9744. * @return {string} The hexadecimal value as a string.
  9745. */
  9746. getHexString( colorSpace = SRGBColorSpace ) {
  9747. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  9748. }
  9749. /**
  9750. * Converts the colors RGB values into the HSL format and stores them into the
  9751. * given target object.
  9752. *
  9753. * @param {{h:0,s:0,l:0}} target - The target object that is used to store the method's result.
  9754. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9755. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  9756. */
  9757. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  9758. // h,s,l ranges are in 0.0 - 1.0
  9759. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9760. const r = _color.r, g = _color.g, b = _color.b;
  9761. const max = Math.max( r, g, b );
  9762. const min = Math.min( r, g, b );
  9763. let hue, saturation;
  9764. const lightness = ( min + max ) / 2.0;
  9765. if ( min === max ) {
  9766. hue = 0;
  9767. saturation = 0;
  9768. } else {
  9769. const delta = max - min;
  9770. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  9771. switch ( max ) {
  9772. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  9773. case g: hue = ( b - r ) / delta + 2; break;
  9774. case b: hue = ( r - g ) / delta + 4; break;
  9775. }
  9776. hue /= 6;
  9777. }
  9778. target.h = hue;
  9779. target.s = saturation;
  9780. target.l = lightness;
  9781. return target;
  9782. }
  9783. /**
  9784. * Returns the RGB values of this color and stores them into the given target object.
  9785. *
  9786. * @param {Color} target - The target color that is used to store the method's result.
  9787. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9788. * @return {Color} The RGB representation of this color.
  9789. */
  9790. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  9791. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9792. target.r = _color.r;
  9793. target.g = _color.g;
  9794. target.b = _color.b;
  9795. return target;
  9796. }
  9797. /**
  9798. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  9799. *
  9800. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9801. * @return {string} The CSS representation of this color.
  9802. */
  9803. getStyle( colorSpace = SRGBColorSpace ) {
  9804. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9805. const r = _color.r, g = _color.g, b = _color.b;
  9806. if ( colorSpace !== SRGBColorSpace ) {
  9807. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  9808. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  9809. }
  9810. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  9811. }
  9812. /**
  9813. * Adds the given HSL values to this color's values.
  9814. * Internally, this converts the color's RGB values to HSL, adds HSL
  9815. * and then converts the color back to RGB.
  9816. *
  9817. * @param {number} h - Hue value between `0.0` and `1.0`.
  9818. * @param {number} s - Saturation value between `0.0` and `1.0`.
  9819. * @param {number} l - Lightness value between `0.0` and `1.0`.
  9820. * @return {Color} A reference to this color.
  9821. */
  9822. offsetHSL( h, s, l ) {
  9823. this.getHSL( _hslA );
  9824. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  9825. }
  9826. /**
  9827. * Adds the RGB values of the given color to the RGB values of this color.
  9828. *
  9829. * @param {Color} color - The color to add.
  9830. * @return {Color} A reference to this color.
  9831. */
  9832. add( color ) {
  9833. this.r += color.r;
  9834. this.g += color.g;
  9835. this.b += color.b;
  9836. return this;
  9837. }
  9838. /**
  9839. * Adds the RGB values of the given colors and stores the result in this instance.
  9840. *
  9841. * @param {Color} color1 - The first color.
  9842. * @param {Color} color2 - The second color.
  9843. * @return {Color} A reference to this color.
  9844. */
  9845. addColors( color1, color2 ) {
  9846. this.r = color1.r + color2.r;
  9847. this.g = color1.g + color2.g;
  9848. this.b = color1.b + color2.b;
  9849. return this;
  9850. }
  9851. /**
  9852. * Adds the given scalar value to the RGB values of this color.
  9853. *
  9854. * @param {number} s - The scalar to add.
  9855. * @return {Color} A reference to this color.
  9856. */
  9857. addScalar( s ) {
  9858. this.r += s;
  9859. this.g += s;
  9860. this.b += s;
  9861. return this;
  9862. }
  9863. /**
  9864. * Subtracts the RGB values of the given color from the RGB values of this color.
  9865. *
  9866. * @param {Color} color - The color to subtract.
  9867. * @return {Color} A reference to this color.
  9868. */
  9869. sub( color ) {
  9870. this.r = Math.max( 0, this.r - color.r );
  9871. this.g = Math.max( 0, this.g - color.g );
  9872. this.b = Math.max( 0, this.b - color.b );
  9873. return this;
  9874. }
  9875. /**
  9876. * Multiplies the RGB values of the given color with the RGB values of this color.
  9877. *
  9878. * @param {Color} color - The color to multiply.
  9879. * @return {Color} A reference to this color.
  9880. */
  9881. multiply( color ) {
  9882. this.r *= color.r;
  9883. this.g *= color.g;
  9884. this.b *= color.b;
  9885. return this;
  9886. }
  9887. /**
  9888. * Multiplies the given scalar value with the RGB values of this color.
  9889. *
  9890. * @param {number} s - The scalar to multiply.
  9891. * @return {Color} A reference to this color.
  9892. */
  9893. multiplyScalar( s ) {
  9894. this.r *= s;
  9895. this.g *= s;
  9896. this.b *= s;
  9897. return this;
  9898. }
  9899. /**
  9900. * Linearly interpolates this color's RGB values toward the RGB values of the
  9901. * given color. The alpha argument can be thought of as the ratio between
  9902. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  9903. *
  9904. * @param {Color} color - The color to converge on.
  9905. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  9906. * @return {Color} A reference to this color.
  9907. */
  9908. lerp( color, alpha ) {
  9909. this.r += ( color.r - this.r ) * alpha;
  9910. this.g += ( color.g - this.g ) * alpha;
  9911. this.b += ( color.b - this.b ) * alpha;
  9912. return this;
  9913. }
  9914. /**
  9915. * Linearly interpolates between the given colors and stores the result in this instance.
  9916. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  9917. * is the first and `1.0` is the second color.
  9918. *
  9919. * @param {Color} color1 - The first color.
  9920. * @param {Color} color2 - The second color.
  9921. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  9922. * @return {Color} A reference to this color.
  9923. */
  9924. lerpColors( color1, color2, alpha ) {
  9925. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  9926. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  9927. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  9928. return this;
  9929. }
  9930. /**
  9931. * Linearly interpolates this color's HSL values toward the HSL values of the
  9932. * given color. It differs from {@link Color#lerp} by not interpolating straight
  9933. * from one color to the other, but instead going through all the hues in between
  9934. * those two colors. The alpha argument can be thought of as the ratio between
  9935. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  9936. *
  9937. * @param {Color} color - The color to converge on.
  9938. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  9939. * @return {Color} A reference to this color.
  9940. */
  9941. lerpHSL( color, alpha ) {
  9942. this.getHSL( _hslA );
  9943. color.getHSL( _hslB );
  9944. const h = lerp( _hslA.h, _hslB.h, alpha );
  9945. const s = lerp( _hslA.s, _hslB.s, alpha );
  9946. const l = lerp( _hslA.l, _hslB.l, alpha );
  9947. this.setHSL( h, s, l );
  9948. return this;
  9949. }
  9950. /**
  9951. * Sets the color's RGB components from the given 3D vector.
  9952. *
  9953. * @param {Vector3} v - The vector to set.
  9954. * @return {Color} A reference to this color.
  9955. */
  9956. setFromVector3( v ) {
  9957. this.r = v.x;
  9958. this.g = v.y;
  9959. this.b = v.z;
  9960. return this;
  9961. }
  9962. /**
  9963. * Transforms this color with the given 3x3 matrix.
  9964. *
  9965. * @param {Matrix3} m - The matrix.
  9966. * @return {Color} A reference to this color.
  9967. */
  9968. applyMatrix3( m ) {
  9969. const r = this.r, g = this.g, b = this.b;
  9970. const e = m.elements;
  9971. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  9972. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  9973. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  9974. return this;
  9975. }
  9976. /**
  9977. * Returns `true` if this color is equal with the given one.
  9978. *
  9979. * @param {Color} c - The color to test for equality.
  9980. * @return {boolean} Whether this bounding color is equal with the given one.
  9981. */
  9982. equals( c ) {
  9983. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  9984. }
  9985. /**
  9986. * Sets this color's RGB components from the given array.
  9987. *
  9988. * @param {Array<number>} array - An array holding the RGB values.
  9989. * @param {number} [offset=0] - The offset into the array.
  9990. * @return {Color} A reference to this color.
  9991. */
  9992. fromArray( array, offset = 0 ) {
  9993. this.r = array[ offset ];
  9994. this.g = array[ offset + 1 ];
  9995. this.b = array[ offset + 2 ];
  9996. return this;
  9997. }
  9998. /**
  9999. * Writes the RGB components of this color to the given array. If no array is provided,
  10000. * the method returns a new instance.
  10001. *
  10002. * @param {Array<number>} [array=[]] - The target array holding the color components.
  10003. * @param {number} [offset=0] - Index of the first element in the array.
  10004. * @return {Array<number>} The color components.
  10005. */
  10006. toArray( array = [], offset = 0 ) {
  10007. array[ offset ] = this.r;
  10008. array[ offset + 1 ] = this.g;
  10009. array[ offset + 2 ] = this.b;
  10010. return array;
  10011. }
  10012. /**
  10013. * Sets the components of this color from the given buffer attribute.
  10014. *
  10015. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  10016. * @param {number} index - The index into the attribute.
  10017. * @return {Color} A reference to this color.
  10018. */
  10019. fromBufferAttribute( attribute, index ) {
  10020. this.r = attribute.getX( index );
  10021. this.g = attribute.getY( index );
  10022. this.b = attribute.getZ( index );
  10023. return this;
  10024. }
  10025. /**
  10026. * This methods defines the serialization result of this class. Returns the color
  10027. * as a hexadecimal value.
  10028. *
  10029. * @return {number} The hexadecimal value.
  10030. */
  10031. toJSON() {
  10032. return this.getHex();
  10033. }
  10034. *[ Symbol.iterator ]() {
  10035. yield this.r;
  10036. yield this.g;
  10037. yield this.b;
  10038. }
  10039. }
  10040. const _color = /*@__PURE__*/ new Color();
  10041. /**
  10042. * A dictionary with X11 color names.
  10043. *
  10044. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  10045. *
  10046. * @static
  10047. * @type {Object}
  10048. */
  10049. Color.NAMES = _colorKeywords;
  10050. let _materialId = 0;
  10051. /**
  10052. * Abstract base class for materials.
  10053. *
  10054. * Materials define the appearance of renderable 3D objects.
  10055. *
  10056. * @abstract
  10057. * @augments EventDispatcher
  10058. */
  10059. class Material extends EventDispatcher {
  10060. /**
  10061. * Constructs a new material.
  10062. */
  10063. constructor() {
  10064. super();
  10065. /**
  10066. * This flag can be used for type testing.
  10067. *
  10068. * @type {boolean}
  10069. * @readonly
  10070. * @default true
  10071. */
  10072. this.isMaterial = true;
  10073. /**
  10074. * The ID of the material.
  10075. *
  10076. * @name Material#id
  10077. * @type {number}
  10078. * @readonly
  10079. */
  10080. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  10081. /**
  10082. * The UUID of the material.
  10083. *
  10084. * @type {string}
  10085. * @readonly
  10086. */
  10087. this.uuid = generateUUID();
  10088. /**
  10089. * The name of the material.
  10090. *
  10091. * @type {string}
  10092. */
  10093. this.name = '';
  10094. /**
  10095. * The type property is used for detecting the object type
  10096. * in context of serialization/deserialization.
  10097. *
  10098. * @type {string}
  10099. * @readonly
  10100. */
  10101. this.type = 'Material';
  10102. /**
  10103. * Defines the blending type of the material.
  10104. *
  10105. * It must be set to `CustomBlending` if custom blending properties like
  10106. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  10107. * should have any effect.
  10108. *
  10109. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  10110. * @default NormalBlending
  10111. */
  10112. this.blending = NormalBlending;
  10113. /**
  10114. * Defines which side of faces will be rendered - front, back or both.
  10115. *
  10116. * @type {(FrontSide|BackSide|DoubleSide)}
  10117. * @default FrontSide
  10118. */
  10119. this.side = FrontSide;
  10120. /**
  10121. * If set to `true`, vertex colors should be used.
  10122. *
  10123. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  10124. * four (RGBA) component color buffer attribute is used.
  10125. *
  10126. * @type {boolean}
  10127. * @default false
  10128. */
  10129. this.vertexColors = false;
  10130. /**
  10131. * Defines how transparent the material is.
  10132. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  10133. *
  10134. * If the {@link Material#transparent} is not set to `true`,
  10135. * the material will remain fully opaque and this value will only affect its color.
  10136. *
  10137. * @type {number}
  10138. * @default 1
  10139. */
  10140. this.opacity = 1;
  10141. /**
  10142. * Defines whether this material is transparent. This has an effect on
  10143. * rendering as transparent objects need special treatment and are rendered
  10144. * after non-transparent objects.
  10145. *
  10146. * When set to true, the extent to which the material is transparent is
  10147. * controlled by {@link Material#opacity}.
  10148. *
  10149. * @type {boolean}
  10150. * @default false
  10151. */
  10152. this.transparent = false;
  10153. /**
  10154. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  10155. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  10156. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  10157. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  10158. *
  10159. * @type {boolean}
  10160. * @default false
  10161. */
  10162. this.alphaHash = false;
  10163. /**
  10164. * Defines the blending source factor.
  10165. *
  10166. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10167. * @default SrcAlphaFactor
  10168. */
  10169. this.blendSrc = SrcAlphaFactor;
  10170. /**
  10171. * Defines the blending destination factor.
  10172. *
  10173. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10174. * @default OneMinusSrcAlphaFactor
  10175. */
  10176. this.blendDst = OneMinusSrcAlphaFactor;
  10177. /**
  10178. * Defines the blending equation.
  10179. *
  10180. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  10181. * @default OneMinusSrcAlphaFactor
  10182. */
  10183. this.blendEquation = AddEquation;
  10184. /**
  10185. * Defines the blending source alpha factor.
  10186. *
  10187. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10188. * @default null
  10189. */
  10190. this.blendSrcAlpha = null;
  10191. /**
  10192. * Defines the blending destination alpha factor.
  10193. *
  10194. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10195. * @default null
  10196. */
  10197. this.blendDstAlpha = null;
  10198. /**
  10199. * Defines the blending equation of the alpha channel.
  10200. *
  10201. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  10202. * @default OneMinusSrcAlphaFactor
  10203. */
  10204. this.blendEquationAlpha = null;
  10205. /**
  10206. * Represents the RGB values of the constant blend color.
  10207. *
  10208. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  10209. *
  10210. * @type {Color}
  10211. * @default (0,0,0)
  10212. */
  10213. this.blendColor = new Color( 0, 0, 0 );
  10214. /**
  10215. * Represents the alpha value of the constant blend color.
  10216. *
  10217. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  10218. *
  10219. * @type {number}
  10220. * @default 0
  10221. */
  10222. this.blendAlpha = 0;
  10223. /**
  10224. * Defines the depth function.
  10225. *
  10226. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  10227. * @default LessEqualDepth
  10228. */
  10229. this.depthFunc = LessEqualDepth;
  10230. /**
  10231. * Whether to have depth test enabled when rendering this material.
  10232. * When the depth test is disabled, the depth write will also be implicitly disabled.
  10233. *
  10234. * @type {boolean}
  10235. * @default true
  10236. */
  10237. this.depthTest = true;
  10238. /**
  10239. * Whether rendering this material has any effect on the depth buffer.
  10240. *
  10241. * When drawing 2D overlays it can be useful to disable the depth writing in
  10242. * order to layer several things together without creating z-index artifacts.
  10243. *
  10244. * @type {boolean}
  10245. * @default true
  10246. */
  10247. this.depthWrite = true;
  10248. /**
  10249. * The bit mask to use when writing to the stencil buffer.
  10250. *
  10251. * @type {number}
  10252. * @default 0xff
  10253. */
  10254. this.stencilWriteMask = 0xff;
  10255. /**
  10256. * The stencil comparison function to use.
  10257. *
  10258. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  10259. * @default AlwaysStencilFunc
  10260. */
  10261. this.stencilFunc = AlwaysStencilFunc;
  10262. /**
  10263. * The value to use when performing stencil comparisons or stencil operations.
  10264. *
  10265. * @type {number}
  10266. * @default 0
  10267. */
  10268. this.stencilRef = 0;
  10269. /**
  10270. * The bit mask to use when comparing against the stencil buffer.
  10271. *
  10272. * @type {number}
  10273. * @default 0xff
  10274. */
  10275. this.stencilFuncMask = 0xff;
  10276. /**
  10277. * Which stencil operation to perform when the comparison function returns `false`.
  10278. *
  10279. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  10280. * @default KeepStencilOp
  10281. */
  10282. this.stencilFail = KeepStencilOp;
  10283. /**
  10284. * Which stencil operation to perform when the comparison function returns
  10285. * `true` but the depth test fails.
  10286. *
  10287. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  10288. * @default KeepStencilOp
  10289. */
  10290. this.stencilZFail = KeepStencilOp;
  10291. /**
  10292. * Which stencil operation to perform when the comparison function returns
  10293. * `true` and the depth test passes.
  10294. *
  10295. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  10296. * @default KeepStencilOp
  10297. */
  10298. this.stencilZPass = KeepStencilOp;
  10299. /**
  10300. * Whether stencil operations are performed against the stencil buffer. In
  10301. * order to perform writes or comparisons against the stencil buffer this
  10302. * value must be `true`.
  10303. *
  10304. * @type {boolean}
  10305. * @default false
  10306. */
  10307. this.stencilWrite = false;
  10308. /**
  10309. * User-defined clipping planes specified as THREE.Plane objects in world
  10310. * space. These planes apply to the objects this material is attached to.
  10311. * Points in space whose signed distance to the plane is negative are clipped
  10312. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  10313. * be `true`.
  10314. *
  10315. * @type {?Array<Plane>}
  10316. * @default null
  10317. */
  10318. this.clippingPlanes = null;
  10319. /**
  10320. * Changes the behavior of clipping planes so that only their intersection is
  10321. * clipped, rather than their union.
  10322. *
  10323. * @type {boolean}
  10324. * @default false
  10325. */
  10326. this.clipIntersection = false;
  10327. /**
  10328. * Defines whether to clip shadows according to the clipping planes specified
  10329. * on this material.
  10330. *
  10331. * @type {boolean}
  10332. * @default false
  10333. */
  10334. this.clipShadows = false;
  10335. /**
  10336. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  10337. * is determined as follows:
  10338. *
  10339. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  10340. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  10341. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  10342. *
  10343. * @type {?(FrontSide|BackSide|DoubleSide)}
  10344. * @default null
  10345. */
  10346. this.shadowSide = null;
  10347. /**
  10348. * Whether to render the material's color.
  10349. *
  10350. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  10351. * objects that occlude other objects.
  10352. *
  10353. * @type {boolean}
  10354. * @default true
  10355. */
  10356. this.colorWrite = true;
  10357. /**
  10358. * Override the renderer's default precision for this material.
  10359. *
  10360. * @type {?('highp'|'mediump'|'lowp')}
  10361. * @default null
  10362. */
  10363. this.precision = null;
  10364. /**
  10365. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  10366. * be offset after it is interpolated from the depth values of the appropriate vertices.
  10367. * The offset is added before the depth test is performed and before the value is written
  10368. * into the depth buffer.
  10369. *
  10370. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  10371. * rendering solids with highlighted edges.
  10372. *
  10373. * @type {boolean}
  10374. * @default false
  10375. */
  10376. this.polygonOffset = false;
  10377. /**
  10378. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  10379. *
  10380. * @type {number}
  10381. * @default 0
  10382. */
  10383. this.polygonOffsetFactor = 0;
  10384. /**
  10385. * Is multiplied by an implementation-specific value to create a constant depth offset.
  10386. *
  10387. * @type {number}
  10388. * @default 0
  10389. */
  10390. this.polygonOffsetUnits = 0;
  10391. /**
  10392. * Whether to apply dithering to the color to remove the appearance of banding.
  10393. *
  10394. * @type {boolean}
  10395. * @default false
  10396. */
  10397. this.dithering = false;
  10398. /**
  10399. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  10400. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  10401. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  10402. *
  10403. * @type {boolean}
  10404. * @default false
  10405. */
  10406. this.alphaToCoverage = false;
  10407. /**
  10408. * Whether to premultiply the alpha (transparency) value.
  10409. *
  10410. * @type {boolean}
  10411. * @default false
  10412. */
  10413. this.premultipliedAlpha = false;
  10414. /**
  10415. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  10416. *
  10417. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  10418. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  10419. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  10420. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  10421. * disable the two pass rendering to avoid performance issues.
  10422. *
  10423. * @type {boolean}
  10424. * @default false
  10425. */
  10426. this.forceSinglePass = false;
  10427. /**
  10428. * Defines whether 3D objects using this material are visible.
  10429. *
  10430. * @type {boolean}
  10431. * @default true
  10432. */
  10433. this.visible = true;
  10434. /**
  10435. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  10436. *
  10437. * It is ignored when rendering to a render target or using post processing or when using
  10438. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  10439. *
  10440. * @type {boolean}
  10441. * @default true
  10442. */
  10443. this.toneMapped = true;
  10444. /**
  10445. * An object that can be used to store custom data about the Material. It
  10446. * should not hold references to functions as these will not be cloned.
  10447. *
  10448. * @type {Object}
  10449. */
  10450. this.userData = {};
  10451. /**
  10452. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  10453. *
  10454. * @type {number}
  10455. * @readonly
  10456. * @default 0
  10457. */
  10458. this.version = 0;
  10459. this._alphaTest = 0;
  10460. }
  10461. /**
  10462. * Sets the alpha value to be used when running an alpha test. The material
  10463. * will not be rendered if the opacity is lower than this value.
  10464. *
  10465. * @type {number}
  10466. * @readonly
  10467. * @default 0
  10468. */
  10469. get alphaTest() {
  10470. return this._alphaTest;
  10471. }
  10472. set alphaTest( value ) {
  10473. if ( this._alphaTest > 0 !== value > 0 ) {
  10474. this.version ++;
  10475. }
  10476. this._alphaTest = value;
  10477. }
  10478. /**
  10479. * An optional callback that is executed immediately before the material is used to render a 3D object.
  10480. *
  10481. * This method can only be used when rendering with {@link WebGLRenderer}.
  10482. *
  10483. * @param {WebGLRenderer} renderer - The renderer.
  10484. * @param {Scene} scene - The scene.
  10485. * @param {Camera} camera - The camera that is used to render the scene.
  10486. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10487. * @param {Object3D} object - The 3D object.
  10488. * @param {Object} group - The geometry group data.
  10489. */
  10490. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  10491. /**
  10492. * An optional callback that is executed immediately before the shader
  10493. * program is compiled. This function is called with the shader source code
  10494. * as a parameter. Useful for the modification of built-in materials.
  10495. *
  10496. * This method can only be used when rendering with {@link WebGLRenderer}. The
  10497. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  10498. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  10499. *
  10500. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  10501. * @param {WebGLRenderer} renderer - A reference to the renderer.
  10502. */
  10503. onBeforeCompile( /* shaderobject, renderer */ ) {}
  10504. /**
  10505. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  10506. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  10507. * shader or recompile the shader for this material as needed.
  10508. *
  10509. * This method can only be used when rendering with {@link WebGLRenderer}.
  10510. *
  10511. * @return {string} The custom program cache key.
  10512. */
  10513. customProgramCacheKey() {
  10514. return this.onBeforeCompile.toString();
  10515. }
  10516. setValues( values ) {
  10517. if ( values === undefined ) return;
  10518. for ( const key in values ) {
  10519. const newValue = values[ key ];
  10520. if ( newValue === undefined ) {
  10521. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  10522. continue;
  10523. }
  10524. const currentValue = this[ key ];
  10525. if ( currentValue === undefined ) {
  10526. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  10527. continue;
  10528. }
  10529. if ( currentValue && currentValue.isColor ) {
  10530. currentValue.set( newValue );
  10531. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  10532. currentValue.copy( newValue );
  10533. } else {
  10534. this[ key ] = newValue;
  10535. }
  10536. }
  10537. }
  10538. /**
  10539. * Serializes the material into JSON.
  10540. *
  10541. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10542. * @return {Object} A JSON object representing the serialized material.
  10543. * @see {@link ObjectLoader#parse}
  10544. */
  10545. toJSON( meta ) {
  10546. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10547. if ( isRootObject ) {
  10548. meta = {
  10549. textures: {},
  10550. images: {}
  10551. };
  10552. }
  10553. const data = {
  10554. metadata: {
  10555. version: 4.6,
  10556. type: 'Material',
  10557. generator: 'Material.toJSON'
  10558. }
  10559. };
  10560. // standard Material serialization
  10561. data.uuid = this.uuid;
  10562. data.type = this.type;
  10563. if ( this.name !== '' ) data.name = this.name;
  10564. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  10565. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  10566. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  10567. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  10568. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  10569. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  10570. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  10571. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  10572. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  10573. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  10574. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  10575. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  10576. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  10577. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  10578. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  10579. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  10580. }
  10581. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  10582. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  10583. }
  10584. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  10585. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  10586. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  10587. }
  10588. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  10589. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  10590. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  10591. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  10592. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  10593. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  10594. }
  10595. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  10596. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  10597. }
  10598. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  10599. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  10600. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  10601. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  10602. }
  10603. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  10604. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  10605. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  10606. if ( this.lightMap && this.lightMap.isTexture ) {
  10607. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  10608. data.lightMapIntensity = this.lightMapIntensity;
  10609. }
  10610. if ( this.aoMap && this.aoMap.isTexture ) {
  10611. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  10612. data.aoMapIntensity = this.aoMapIntensity;
  10613. }
  10614. if ( this.bumpMap && this.bumpMap.isTexture ) {
  10615. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  10616. data.bumpScale = this.bumpScale;
  10617. }
  10618. if ( this.normalMap && this.normalMap.isTexture ) {
  10619. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  10620. data.normalMapType = this.normalMapType;
  10621. data.normalScale = this.normalScale.toArray();
  10622. }
  10623. if ( this.displacementMap && this.displacementMap.isTexture ) {
  10624. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  10625. data.displacementScale = this.displacementScale;
  10626. data.displacementBias = this.displacementBias;
  10627. }
  10628. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  10629. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  10630. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  10631. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  10632. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  10633. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  10634. if ( this.envMap && this.envMap.isTexture ) {
  10635. data.envMap = this.envMap.toJSON( meta ).uuid;
  10636. if ( this.combine !== undefined ) data.combine = this.combine;
  10637. }
  10638. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  10639. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  10640. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  10641. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  10642. if ( this.gradientMap && this.gradientMap.isTexture ) {
  10643. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  10644. }
  10645. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  10646. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  10647. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  10648. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  10649. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  10650. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  10651. if ( this.size !== undefined ) data.size = this.size;
  10652. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  10653. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  10654. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  10655. if ( this.side !== FrontSide ) data.side = this.side;
  10656. if ( this.vertexColors === true ) data.vertexColors = true;
  10657. if ( this.opacity < 1 ) data.opacity = this.opacity;
  10658. if ( this.transparent === true ) data.transparent = true;
  10659. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  10660. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  10661. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  10662. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  10663. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  10664. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  10665. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  10666. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  10667. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  10668. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  10669. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  10670. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  10671. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  10672. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  10673. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  10674. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  10675. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  10676. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  10677. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  10678. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  10679. // rotation (SpriteMaterial)
  10680. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  10681. if ( this.polygonOffset === true ) data.polygonOffset = true;
  10682. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  10683. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  10684. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  10685. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  10686. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  10687. if ( this.scale !== undefined ) data.scale = this.scale;
  10688. if ( this.dithering === true ) data.dithering = true;
  10689. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  10690. if ( this.alphaHash === true ) data.alphaHash = true;
  10691. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  10692. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  10693. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  10694. if ( this.wireframe === true ) data.wireframe = true;
  10695. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  10696. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  10697. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  10698. if ( this.flatShading === true ) data.flatShading = true;
  10699. if ( this.visible === false ) data.visible = false;
  10700. if ( this.toneMapped === false ) data.toneMapped = false;
  10701. if ( this.fog === false ) data.fog = false;
  10702. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  10703. // TODO: Copied from Object3D.toJSON
  10704. function extractFromCache( cache ) {
  10705. const values = [];
  10706. for ( const key in cache ) {
  10707. const data = cache[ key ];
  10708. delete data.metadata;
  10709. values.push( data );
  10710. }
  10711. return values;
  10712. }
  10713. if ( isRootObject ) {
  10714. const textures = extractFromCache( meta.textures );
  10715. const images = extractFromCache( meta.images );
  10716. if ( textures.length > 0 ) data.textures = textures;
  10717. if ( images.length > 0 ) data.images = images;
  10718. }
  10719. return data;
  10720. }
  10721. /**
  10722. * Returns a new material with copied values from this instance.
  10723. *
  10724. * @return {Material} A clone of this instance.
  10725. */
  10726. clone() {
  10727. return new this.constructor().copy( this );
  10728. }
  10729. /**
  10730. * Copies the values of the given material to this instance.
  10731. *
  10732. * @param {Material} source - The material to copy.
  10733. * @return {Material} A reference to this instance.
  10734. */
  10735. copy( source ) {
  10736. this.name = source.name;
  10737. this.blending = source.blending;
  10738. this.side = source.side;
  10739. this.vertexColors = source.vertexColors;
  10740. this.opacity = source.opacity;
  10741. this.transparent = source.transparent;
  10742. this.blendSrc = source.blendSrc;
  10743. this.blendDst = source.blendDst;
  10744. this.blendEquation = source.blendEquation;
  10745. this.blendSrcAlpha = source.blendSrcAlpha;
  10746. this.blendDstAlpha = source.blendDstAlpha;
  10747. this.blendEquationAlpha = source.blendEquationAlpha;
  10748. this.blendColor.copy( source.blendColor );
  10749. this.blendAlpha = source.blendAlpha;
  10750. this.depthFunc = source.depthFunc;
  10751. this.depthTest = source.depthTest;
  10752. this.depthWrite = source.depthWrite;
  10753. this.stencilWriteMask = source.stencilWriteMask;
  10754. this.stencilFunc = source.stencilFunc;
  10755. this.stencilRef = source.stencilRef;
  10756. this.stencilFuncMask = source.stencilFuncMask;
  10757. this.stencilFail = source.stencilFail;
  10758. this.stencilZFail = source.stencilZFail;
  10759. this.stencilZPass = source.stencilZPass;
  10760. this.stencilWrite = source.stencilWrite;
  10761. const srcPlanes = source.clippingPlanes;
  10762. let dstPlanes = null;
  10763. if ( srcPlanes !== null ) {
  10764. const n = srcPlanes.length;
  10765. dstPlanes = new Array( n );
  10766. for ( let i = 0; i !== n; ++ i ) {
  10767. dstPlanes[ i ] = srcPlanes[ i ].clone();
  10768. }
  10769. }
  10770. this.clippingPlanes = dstPlanes;
  10771. this.clipIntersection = source.clipIntersection;
  10772. this.clipShadows = source.clipShadows;
  10773. this.shadowSide = source.shadowSide;
  10774. this.colorWrite = source.colorWrite;
  10775. this.precision = source.precision;
  10776. this.polygonOffset = source.polygonOffset;
  10777. this.polygonOffsetFactor = source.polygonOffsetFactor;
  10778. this.polygonOffsetUnits = source.polygonOffsetUnits;
  10779. this.dithering = source.dithering;
  10780. this.alphaTest = source.alphaTest;
  10781. this.alphaHash = source.alphaHash;
  10782. this.alphaToCoverage = source.alphaToCoverage;
  10783. this.premultipliedAlpha = source.premultipliedAlpha;
  10784. this.forceSinglePass = source.forceSinglePass;
  10785. this.visible = source.visible;
  10786. this.toneMapped = source.toneMapped;
  10787. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10788. return this;
  10789. }
  10790. /**
  10791. * Frees the GPU-related resources allocated by this instance. Call this
  10792. * method whenever this instance is no longer used in your app.
  10793. *
  10794. * @fires Material#dispose
  10795. */
  10796. dispose() {
  10797. /**
  10798. * Fires when the material has been disposed of.
  10799. *
  10800. * @event Material#dispose
  10801. * @type {Object}
  10802. */
  10803. this.dispatchEvent( { type: 'dispose' } );
  10804. }
  10805. /**
  10806. * Setting this property to `true` indicates the engine the material
  10807. * needs to be recompiled.
  10808. *
  10809. * @type {boolean}
  10810. * @default false
  10811. * @param {boolean} value
  10812. */
  10813. set needsUpdate( value ) {
  10814. if ( value === true ) this.version ++;
  10815. }
  10816. onBuild( /* shaderobject, renderer */ ) {
  10817. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  10818. }
  10819. }
  10820. class MeshBasicMaterial extends Material {
  10821. constructor( parameters ) {
  10822. super();
  10823. this.isMeshBasicMaterial = true;
  10824. this.type = 'MeshBasicMaterial';
  10825. this.color = new Color( 0xffffff ); // emissive
  10826. this.map = null;
  10827. this.lightMap = null;
  10828. this.lightMapIntensity = 1.0;
  10829. this.aoMap = null;
  10830. this.aoMapIntensity = 1.0;
  10831. this.specularMap = null;
  10832. this.alphaMap = null;
  10833. this.envMap = null;
  10834. this.envMapRotation = new Euler();
  10835. this.combine = MultiplyOperation;
  10836. this.reflectivity = 1;
  10837. this.refractionRatio = 0.98;
  10838. this.wireframe = false;
  10839. this.wireframeLinewidth = 1;
  10840. this.wireframeLinecap = 'round';
  10841. this.wireframeLinejoin = 'round';
  10842. this.fog = true;
  10843. this.setValues( parameters );
  10844. }
  10845. copy( source ) {
  10846. super.copy( source );
  10847. this.color.copy( source.color );
  10848. this.map = source.map;
  10849. this.lightMap = source.lightMap;
  10850. this.lightMapIntensity = source.lightMapIntensity;
  10851. this.aoMap = source.aoMap;
  10852. this.aoMapIntensity = source.aoMapIntensity;
  10853. this.specularMap = source.specularMap;
  10854. this.alphaMap = source.alphaMap;
  10855. this.envMap = source.envMap;
  10856. this.envMapRotation.copy( source.envMapRotation );
  10857. this.combine = source.combine;
  10858. this.reflectivity = source.reflectivity;
  10859. this.refractionRatio = source.refractionRatio;
  10860. this.wireframe = source.wireframe;
  10861. this.wireframeLinewidth = source.wireframeLinewidth;
  10862. this.wireframeLinecap = source.wireframeLinecap;
  10863. this.wireframeLinejoin = source.wireframeLinejoin;
  10864. this.fog = source.fog;
  10865. return this;
  10866. }
  10867. }
  10868. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  10869. const _tables = /*@__PURE__*/ _generateTables();
  10870. function _generateTables() {
  10871. // float32 to float16 helpers
  10872. const buffer = new ArrayBuffer( 4 );
  10873. const floatView = new Float32Array( buffer );
  10874. const uint32View = new Uint32Array( buffer );
  10875. const baseTable = new Uint32Array( 512 );
  10876. const shiftTable = new Uint32Array( 512 );
  10877. for ( let i = 0; i < 256; ++ i ) {
  10878. const e = i - 127;
  10879. // very small number (0, -0)
  10880. if ( e < -27 ) {
  10881. baseTable[ i ] = 0x0000;
  10882. baseTable[ i | 0x100 ] = 0x8000;
  10883. shiftTable[ i ] = 24;
  10884. shiftTable[ i | 0x100 ] = 24;
  10885. // small number (denorm)
  10886. } else if ( e < -14 ) {
  10887. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  10888. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  10889. shiftTable[ i ] = - e - 1;
  10890. shiftTable[ i | 0x100 ] = - e - 1;
  10891. // normal number
  10892. } else if ( e <= 15 ) {
  10893. baseTable[ i ] = ( e + 15 ) << 10;
  10894. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  10895. shiftTable[ i ] = 13;
  10896. shiftTable[ i | 0x100 ] = 13;
  10897. // large number (Infinity, -Infinity)
  10898. } else if ( e < 128 ) {
  10899. baseTable[ i ] = 0x7c00;
  10900. baseTable[ i | 0x100 ] = 0xfc00;
  10901. shiftTable[ i ] = 24;
  10902. shiftTable[ i | 0x100 ] = 24;
  10903. // stay (NaN, Infinity, -Infinity)
  10904. } else {
  10905. baseTable[ i ] = 0x7c00;
  10906. baseTable[ i | 0x100 ] = 0xfc00;
  10907. shiftTable[ i ] = 13;
  10908. shiftTable[ i | 0x100 ] = 13;
  10909. }
  10910. }
  10911. // float16 to float32 helpers
  10912. const mantissaTable = new Uint32Array( 2048 );
  10913. const exponentTable = new Uint32Array( 64 );
  10914. const offsetTable = new Uint32Array( 64 );
  10915. for ( let i = 1; i < 1024; ++ i ) {
  10916. let m = i << 13; // zero pad mantissa bits
  10917. let e = 0; // zero exponent
  10918. // normalized
  10919. while ( ( m & 0x00800000 ) === 0 ) {
  10920. m <<= 1;
  10921. e -= 0x00800000; // decrement exponent
  10922. }
  10923. m &= -8388609; // clear leading 1 bit
  10924. e += 0x38800000; // adjust bias
  10925. mantissaTable[ i ] = m | e;
  10926. }
  10927. for ( let i = 1024; i < 2048; ++ i ) {
  10928. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  10929. }
  10930. for ( let i = 1; i < 31; ++ i ) {
  10931. exponentTable[ i ] = i << 23;
  10932. }
  10933. exponentTable[ 31 ] = 0x47800000;
  10934. exponentTable[ 32 ] = 0x80000000;
  10935. for ( let i = 33; i < 63; ++ i ) {
  10936. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  10937. }
  10938. exponentTable[ 63 ] = 0xc7800000;
  10939. for ( let i = 1; i < 64; ++ i ) {
  10940. if ( i !== 32 ) {
  10941. offsetTable[ i ] = 1024;
  10942. }
  10943. }
  10944. return {
  10945. floatView: floatView,
  10946. uint32View: uint32View,
  10947. baseTable: baseTable,
  10948. shiftTable: shiftTable,
  10949. mantissaTable: mantissaTable,
  10950. exponentTable: exponentTable,
  10951. offsetTable: offsetTable
  10952. };
  10953. }
  10954. /**
  10955. * Returns a half precision floating point value (FP16) from the given single
  10956. * precision floating point value (FP32).
  10957. *
  10958. * @param {number} val - A single precision floating point value.
  10959. * @return {number} The FP16 value.
  10960. */
  10961. function toHalfFloat( val ) {
  10962. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  10963. val = clamp( val, -65504, 65504 );
  10964. _tables.floatView[ 0 ] = val;
  10965. const f = _tables.uint32View[ 0 ];
  10966. const e = ( f >> 23 ) & 0x1ff;
  10967. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  10968. }
  10969. /**
  10970. * Returns a single precision floating point value (FP32) from the given half
  10971. * precision floating point value (FP16).
  10972. *
  10973. * @param {number} val - A half precision floating point value.
  10974. * @return {number} The FP32 value.
  10975. */
  10976. function fromHalfFloat( val ) {
  10977. const m = val >> 10;
  10978. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  10979. return _tables.floatView[ 0 ];
  10980. }
  10981. /**
  10982. * A class containing utility functions for data.
  10983. *
  10984. * @hideconstructor
  10985. */
  10986. class DataUtils {
  10987. /**
  10988. * Returns a half precision floating point value (FP16) from the given single
  10989. * precision floating point value (FP32).
  10990. *
  10991. * @param {number} val - A single precision floating point value.
  10992. * @return {number} The FP16 value.
  10993. */
  10994. static toHalfFloat( val ) {
  10995. return toHalfFloat( val );
  10996. }
  10997. /**
  10998. * Returns a single precision floating point value (FP32) from the given half
  10999. * precision floating point value (FP16).
  11000. *
  11001. * @param {number} val - A half precision floating point value.
  11002. * @return {number} The FP32 value.
  11003. */
  11004. static fromHalfFloat( val ) {
  11005. return fromHalfFloat( val );
  11006. }
  11007. }
  11008. const _vector$9 = /*@__PURE__*/ new Vector3();
  11009. const _vector2$1 = /*@__PURE__*/ new Vector2();
  11010. let _id$3 = 0;
  11011. class BufferAttribute {
  11012. constructor( array, itemSize, normalized = false ) {
  11013. if ( Array.isArray( array ) ) {
  11014. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11015. }
  11016. this.isBufferAttribute = true;
  11017. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  11018. this.name = '';
  11019. this.array = array;
  11020. this.itemSize = itemSize;
  11021. this.count = array !== undefined ? array.length / itemSize : 0;
  11022. this.normalized = normalized;
  11023. this.usage = StaticDrawUsage;
  11024. this.updateRanges = [];
  11025. this.gpuType = FloatType;
  11026. this.version = 0;
  11027. }
  11028. onUploadCallback() {}
  11029. set needsUpdate( value ) {
  11030. if ( value === true ) this.version ++;
  11031. }
  11032. setUsage( value ) {
  11033. this.usage = value;
  11034. return this;
  11035. }
  11036. addUpdateRange( start, count ) {
  11037. this.updateRanges.push( { start, count } );
  11038. }
  11039. clearUpdateRanges() {
  11040. this.updateRanges.length = 0;
  11041. }
  11042. copy( source ) {
  11043. this.name = source.name;
  11044. this.array = new source.array.constructor( source.array );
  11045. this.itemSize = source.itemSize;
  11046. this.count = source.count;
  11047. this.normalized = source.normalized;
  11048. this.usage = source.usage;
  11049. this.gpuType = source.gpuType;
  11050. return this;
  11051. }
  11052. copyAt( index1, attribute, index2 ) {
  11053. index1 *= this.itemSize;
  11054. index2 *= attribute.itemSize;
  11055. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  11056. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  11057. }
  11058. return this;
  11059. }
  11060. copyArray( array ) {
  11061. this.array.set( array );
  11062. return this;
  11063. }
  11064. applyMatrix3( m ) {
  11065. if ( this.itemSize === 2 ) {
  11066. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11067. _vector2$1.fromBufferAttribute( this, i );
  11068. _vector2$1.applyMatrix3( m );
  11069. this.setXY( i, _vector2$1.x, _vector2$1.y );
  11070. }
  11071. } else if ( this.itemSize === 3 ) {
  11072. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11073. _vector$9.fromBufferAttribute( this, i );
  11074. _vector$9.applyMatrix3( m );
  11075. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11076. }
  11077. }
  11078. return this;
  11079. }
  11080. applyMatrix4( m ) {
  11081. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11082. _vector$9.fromBufferAttribute( this, i );
  11083. _vector$9.applyMatrix4( m );
  11084. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11085. }
  11086. return this;
  11087. }
  11088. applyNormalMatrix( m ) {
  11089. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11090. _vector$9.fromBufferAttribute( this, i );
  11091. _vector$9.applyNormalMatrix( m );
  11092. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11093. }
  11094. return this;
  11095. }
  11096. transformDirection( m ) {
  11097. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11098. _vector$9.fromBufferAttribute( this, i );
  11099. _vector$9.transformDirection( m );
  11100. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11101. }
  11102. return this;
  11103. }
  11104. set( value, offset = 0 ) {
  11105. // Matching BufferAttribute constructor, do not normalize the array.
  11106. this.array.set( value, offset );
  11107. return this;
  11108. }
  11109. getComponent( index, component ) {
  11110. let value = this.array[ index * this.itemSize + component ];
  11111. if ( this.normalized ) value = denormalize( value, this.array );
  11112. return value;
  11113. }
  11114. setComponent( index, component, value ) {
  11115. if ( this.normalized ) value = normalize( value, this.array );
  11116. this.array[ index * this.itemSize + component ] = value;
  11117. return this;
  11118. }
  11119. getX( index ) {
  11120. let x = this.array[ index * this.itemSize ];
  11121. if ( this.normalized ) x = denormalize( x, this.array );
  11122. return x;
  11123. }
  11124. setX( index, x ) {
  11125. if ( this.normalized ) x = normalize( x, this.array );
  11126. this.array[ index * this.itemSize ] = x;
  11127. return this;
  11128. }
  11129. getY( index ) {
  11130. let y = this.array[ index * this.itemSize + 1 ];
  11131. if ( this.normalized ) y = denormalize( y, this.array );
  11132. return y;
  11133. }
  11134. setY( index, y ) {
  11135. if ( this.normalized ) y = normalize( y, this.array );
  11136. this.array[ index * this.itemSize + 1 ] = y;
  11137. return this;
  11138. }
  11139. getZ( index ) {
  11140. let z = this.array[ index * this.itemSize + 2 ];
  11141. if ( this.normalized ) z = denormalize( z, this.array );
  11142. return z;
  11143. }
  11144. setZ( index, z ) {
  11145. if ( this.normalized ) z = normalize( z, this.array );
  11146. this.array[ index * this.itemSize + 2 ] = z;
  11147. return this;
  11148. }
  11149. getW( index ) {
  11150. let w = this.array[ index * this.itemSize + 3 ];
  11151. if ( this.normalized ) w = denormalize( w, this.array );
  11152. return w;
  11153. }
  11154. setW( index, w ) {
  11155. if ( this.normalized ) w = normalize( w, this.array );
  11156. this.array[ index * this.itemSize + 3 ] = w;
  11157. return this;
  11158. }
  11159. setXY( index, x, y ) {
  11160. index *= this.itemSize;
  11161. if ( this.normalized ) {
  11162. x = normalize( x, this.array );
  11163. y = normalize( y, this.array );
  11164. }
  11165. this.array[ index + 0 ] = x;
  11166. this.array[ index + 1 ] = y;
  11167. return this;
  11168. }
  11169. setXYZ( index, x, y, z ) {
  11170. index *= this.itemSize;
  11171. if ( this.normalized ) {
  11172. x = normalize( x, this.array );
  11173. y = normalize( y, this.array );
  11174. z = normalize( z, this.array );
  11175. }
  11176. this.array[ index + 0 ] = x;
  11177. this.array[ index + 1 ] = y;
  11178. this.array[ index + 2 ] = z;
  11179. return this;
  11180. }
  11181. setXYZW( index, x, y, z, w ) {
  11182. index *= this.itemSize;
  11183. if ( this.normalized ) {
  11184. x = normalize( x, this.array );
  11185. y = normalize( y, this.array );
  11186. z = normalize( z, this.array );
  11187. w = normalize( w, this.array );
  11188. }
  11189. this.array[ index + 0 ] = x;
  11190. this.array[ index + 1 ] = y;
  11191. this.array[ index + 2 ] = z;
  11192. this.array[ index + 3 ] = w;
  11193. return this;
  11194. }
  11195. onUpload( callback ) {
  11196. this.onUploadCallback = callback;
  11197. return this;
  11198. }
  11199. clone() {
  11200. return new this.constructor( this.array, this.itemSize ).copy( this );
  11201. }
  11202. toJSON() {
  11203. const data = {
  11204. itemSize: this.itemSize,
  11205. type: this.array.constructor.name,
  11206. array: Array.from( this.array ),
  11207. normalized: this.normalized
  11208. };
  11209. if ( this.name !== '' ) data.name = this.name;
  11210. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  11211. return data;
  11212. }
  11213. }
  11214. //
  11215. class Int8BufferAttribute extends BufferAttribute {
  11216. constructor( array, itemSize, normalized ) {
  11217. super( new Int8Array( array ), itemSize, normalized );
  11218. }
  11219. }
  11220. class Uint8BufferAttribute extends BufferAttribute {
  11221. constructor( array, itemSize, normalized ) {
  11222. super( new Uint8Array( array ), itemSize, normalized );
  11223. }
  11224. }
  11225. class Uint8ClampedBufferAttribute extends BufferAttribute {
  11226. constructor( array, itemSize, normalized ) {
  11227. super( new Uint8ClampedArray( array ), itemSize, normalized );
  11228. }
  11229. }
  11230. class Int16BufferAttribute extends BufferAttribute {
  11231. constructor( array, itemSize, normalized ) {
  11232. super( new Int16Array( array ), itemSize, normalized );
  11233. }
  11234. }
  11235. class Uint16BufferAttribute extends BufferAttribute {
  11236. constructor( array, itemSize, normalized ) {
  11237. super( new Uint16Array( array ), itemSize, normalized );
  11238. }
  11239. }
  11240. class Int32BufferAttribute extends BufferAttribute {
  11241. constructor( array, itemSize, normalized ) {
  11242. super( new Int32Array( array ), itemSize, normalized );
  11243. }
  11244. }
  11245. class Uint32BufferAttribute extends BufferAttribute {
  11246. constructor( array, itemSize, normalized ) {
  11247. super( new Uint32Array( array ), itemSize, normalized );
  11248. }
  11249. }
  11250. class Float16BufferAttribute extends BufferAttribute {
  11251. constructor( array, itemSize, normalized ) {
  11252. super( new Uint16Array( array ), itemSize, normalized );
  11253. this.isFloat16BufferAttribute = true;
  11254. }
  11255. getX( index ) {
  11256. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  11257. if ( this.normalized ) x = denormalize( x, this.array );
  11258. return x;
  11259. }
  11260. setX( index, x ) {
  11261. if ( this.normalized ) x = normalize( x, this.array );
  11262. this.array[ index * this.itemSize ] = toHalfFloat( x );
  11263. return this;
  11264. }
  11265. getY( index ) {
  11266. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  11267. if ( this.normalized ) y = denormalize( y, this.array );
  11268. return y;
  11269. }
  11270. setY( index, y ) {
  11271. if ( this.normalized ) y = normalize( y, this.array );
  11272. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  11273. return this;
  11274. }
  11275. getZ( index ) {
  11276. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  11277. if ( this.normalized ) z = denormalize( z, this.array );
  11278. return z;
  11279. }
  11280. setZ( index, z ) {
  11281. if ( this.normalized ) z = normalize( z, this.array );
  11282. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  11283. return this;
  11284. }
  11285. getW( index ) {
  11286. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  11287. if ( this.normalized ) w = denormalize( w, this.array );
  11288. return w;
  11289. }
  11290. setW( index, w ) {
  11291. if ( this.normalized ) w = normalize( w, this.array );
  11292. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  11293. return this;
  11294. }
  11295. setXY( index, x, y ) {
  11296. index *= this.itemSize;
  11297. if ( this.normalized ) {
  11298. x = normalize( x, this.array );
  11299. y = normalize( y, this.array );
  11300. }
  11301. this.array[ index + 0 ] = toHalfFloat( x );
  11302. this.array[ index + 1 ] = toHalfFloat( y );
  11303. return this;
  11304. }
  11305. setXYZ( index, x, y, z ) {
  11306. index *= this.itemSize;
  11307. if ( this.normalized ) {
  11308. x = normalize( x, this.array );
  11309. y = normalize( y, this.array );
  11310. z = normalize( z, this.array );
  11311. }
  11312. this.array[ index + 0 ] = toHalfFloat( x );
  11313. this.array[ index + 1 ] = toHalfFloat( y );
  11314. this.array[ index + 2 ] = toHalfFloat( z );
  11315. return this;
  11316. }
  11317. setXYZW( index, x, y, z, w ) {
  11318. index *= this.itemSize;
  11319. if ( this.normalized ) {
  11320. x = normalize( x, this.array );
  11321. y = normalize( y, this.array );
  11322. z = normalize( z, this.array );
  11323. w = normalize( w, this.array );
  11324. }
  11325. this.array[ index + 0 ] = toHalfFloat( x );
  11326. this.array[ index + 1 ] = toHalfFloat( y );
  11327. this.array[ index + 2 ] = toHalfFloat( z );
  11328. this.array[ index + 3 ] = toHalfFloat( w );
  11329. return this;
  11330. }
  11331. }
  11332. class Float32BufferAttribute extends BufferAttribute {
  11333. constructor( array, itemSize, normalized ) {
  11334. super( new Float32Array( array ), itemSize, normalized );
  11335. }
  11336. }
  11337. let _id$2 = 0;
  11338. const _m1$2 = /*@__PURE__*/ new Matrix4();
  11339. const _obj = /*@__PURE__*/ new Object3D();
  11340. const _offset = /*@__PURE__*/ new Vector3();
  11341. const _box$2 = /*@__PURE__*/ new Box3();
  11342. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  11343. const _vector$8 = /*@__PURE__*/ new Vector3();
  11344. class BufferGeometry extends EventDispatcher {
  11345. constructor() {
  11346. super();
  11347. this.isBufferGeometry = true;
  11348. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  11349. this.uuid = generateUUID();
  11350. this.name = '';
  11351. this.type = 'BufferGeometry';
  11352. this.index = null;
  11353. this.indirect = null;
  11354. this.attributes = {};
  11355. this.morphAttributes = {};
  11356. this.morphTargetsRelative = false;
  11357. this.groups = [];
  11358. this.boundingBox = null;
  11359. this.boundingSphere = null;
  11360. this.drawRange = { start: 0, count: Infinity };
  11361. this.userData = {};
  11362. }
  11363. getIndex() {
  11364. return this.index;
  11365. }
  11366. setIndex( index ) {
  11367. if ( Array.isArray( index ) ) {
  11368. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  11369. } else {
  11370. this.index = index;
  11371. }
  11372. return this;
  11373. }
  11374. setIndirect( indirect ) {
  11375. this.indirect = indirect;
  11376. return this;
  11377. }
  11378. getIndirect() {
  11379. return this.indirect;
  11380. }
  11381. getAttribute( name ) {
  11382. return this.attributes[ name ];
  11383. }
  11384. setAttribute( name, attribute ) {
  11385. this.attributes[ name ] = attribute;
  11386. return this;
  11387. }
  11388. deleteAttribute( name ) {
  11389. delete this.attributes[ name ];
  11390. return this;
  11391. }
  11392. hasAttribute( name ) {
  11393. return this.attributes[ name ] !== undefined;
  11394. }
  11395. addGroup( start, count, materialIndex = 0 ) {
  11396. this.groups.push( {
  11397. start: start,
  11398. count: count,
  11399. materialIndex: materialIndex
  11400. } );
  11401. }
  11402. clearGroups() {
  11403. this.groups = [];
  11404. }
  11405. setDrawRange( start, count ) {
  11406. this.drawRange.start = start;
  11407. this.drawRange.count = count;
  11408. }
  11409. applyMatrix4( matrix ) {
  11410. const position = this.attributes.position;
  11411. if ( position !== undefined ) {
  11412. position.applyMatrix4( matrix );
  11413. position.needsUpdate = true;
  11414. }
  11415. const normal = this.attributes.normal;
  11416. if ( normal !== undefined ) {
  11417. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11418. normal.applyNormalMatrix( normalMatrix );
  11419. normal.needsUpdate = true;
  11420. }
  11421. const tangent = this.attributes.tangent;
  11422. if ( tangent !== undefined ) {
  11423. tangent.transformDirection( matrix );
  11424. tangent.needsUpdate = true;
  11425. }
  11426. if ( this.boundingBox !== null ) {
  11427. this.computeBoundingBox();
  11428. }
  11429. if ( this.boundingSphere !== null ) {
  11430. this.computeBoundingSphere();
  11431. }
  11432. return this;
  11433. }
  11434. applyQuaternion( q ) {
  11435. _m1$2.makeRotationFromQuaternion( q );
  11436. this.applyMatrix4( _m1$2 );
  11437. return this;
  11438. }
  11439. rotateX( angle ) {
  11440. // rotate geometry around world x-axis
  11441. _m1$2.makeRotationX( angle );
  11442. this.applyMatrix4( _m1$2 );
  11443. return this;
  11444. }
  11445. rotateY( angle ) {
  11446. // rotate geometry around world y-axis
  11447. _m1$2.makeRotationY( angle );
  11448. this.applyMatrix4( _m1$2 );
  11449. return this;
  11450. }
  11451. rotateZ( angle ) {
  11452. // rotate geometry around world z-axis
  11453. _m1$2.makeRotationZ( angle );
  11454. this.applyMatrix4( _m1$2 );
  11455. return this;
  11456. }
  11457. translate( x, y, z ) {
  11458. // translate geometry
  11459. _m1$2.makeTranslation( x, y, z );
  11460. this.applyMatrix4( _m1$2 );
  11461. return this;
  11462. }
  11463. scale( x, y, z ) {
  11464. // scale geometry
  11465. _m1$2.makeScale( x, y, z );
  11466. this.applyMatrix4( _m1$2 );
  11467. return this;
  11468. }
  11469. lookAt( vector ) {
  11470. _obj.lookAt( vector );
  11471. _obj.updateMatrix();
  11472. this.applyMatrix4( _obj.matrix );
  11473. return this;
  11474. }
  11475. center() {
  11476. this.computeBoundingBox();
  11477. this.boundingBox.getCenter( _offset ).negate();
  11478. this.translate( _offset.x, _offset.y, _offset.z );
  11479. return this;
  11480. }
  11481. setFromPoints( points ) {
  11482. const positionAttribute = this.getAttribute( 'position' );
  11483. if ( positionAttribute === undefined ) {
  11484. const position = [];
  11485. for ( let i = 0, l = points.length; i < l; i ++ ) {
  11486. const point = points[ i ];
  11487. position.push( point.x, point.y, point.z || 0 );
  11488. }
  11489. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  11490. } else {
  11491. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  11492. for ( let i = 0; i < l; i ++ ) {
  11493. const point = points[ i ];
  11494. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  11495. }
  11496. if ( points.length > positionAttribute.count ) {
  11497. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  11498. }
  11499. positionAttribute.needsUpdate = true;
  11500. }
  11501. return this;
  11502. }
  11503. computeBoundingBox() {
  11504. if ( this.boundingBox === null ) {
  11505. this.boundingBox = new Box3();
  11506. }
  11507. const position = this.attributes.position;
  11508. const morphAttributesPosition = this.morphAttributes.position;
  11509. if ( position && position.isGLBufferAttribute ) {
  11510. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  11511. this.boundingBox.set(
  11512. new Vector3( - Infinity, - Infinity, - Infinity ),
  11513. new Vector3( + Infinity, + Infinity, + Infinity )
  11514. );
  11515. return;
  11516. }
  11517. if ( position !== undefined ) {
  11518. this.boundingBox.setFromBufferAttribute( position );
  11519. // process morph attributes if present
  11520. if ( morphAttributesPosition ) {
  11521. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11522. const morphAttribute = morphAttributesPosition[ i ];
  11523. _box$2.setFromBufferAttribute( morphAttribute );
  11524. if ( this.morphTargetsRelative ) {
  11525. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  11526. this.boundingBox.expandByPoint( _vector$8 );
  11527. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  11528. this.boundingBox.expandByPoint( _vector$8 );
  11529. } else {
  11530. this.boundingBox.expandByPoint( _box$2.min );
  11531. this.boundingBox.expandByPoint( _box$2.max );
  11532. }
  11533. }
  11534. }
  11535. } else {
  11536. this.boundingBox.makeEmpty();
  11537. }
  11538. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  11539. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  11540. }
  11541. }
  11542. computeBoundingSphere() {
  11543. if ( this.boundingSphere === null ) {
  11544. this.boundingSphere = new Sphere();
  11545. }
  11546. const position = this.attributes.position;
  11547. const morphAttributesPosition = this.morphAttributes.position;
  11548. if ( position && position.isGLBufferAttribute ) {
  11549. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  11550. this.boundingSphere.set( new Vector3(), Infinity );
  11551. return;
  11552. }
  11553. if ( position ) {
  11554. // first, find the center of the bounding sphere
  11555. const center = this.boundingSphere.center;
  11556. _box$2.setFromBufferAttribute( position );
  11557. // process morph attributes if present
  11558. if ( morphAttributesPosition ) {
  11559. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11560. const morphAttribute = morphAttributesPosition[ i ];
  11561. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  11562. if ( this.morphTargetsRelative ) {
  11563. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  11564. _box$2.expandByPoint( _vector$8 );
  11565. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  11566. _box$2.expandByPoint( _vector$8 );
  11567. } else {
  11568. _box$2.expandByPoint( _boxMorphTargets.min );
  11569. _box$2.expandByPoint( _boxMorphTargets.max );
  11570. }
  11571. }
  11572. }
  11573. _box$2.getCenter( center );
  11574. // second, try to find a boundingSphere with a radius smaller than the
  11575. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  11576. let maxRadiusSq = 0;
  11577. for ( let i = 0, il = position.count; i < il; i ++ ) {
  11578. _vector$8.fromBufferAttribute( position, i );
  11579. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  11580. }
  11581. // process morph attributes if present
  11582. if ( morphAttributesPosition ) {
  11583. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11584. const morphAttribute = morphAttributesPosition[ i ];
  11585. const morphTargetsRelative = this.morphTargetsRelative;
  11586. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  11587. _vector$8.fromBufferAttribute( morphAttribute, j );
  11588. if ( morphTargetsRelative ) {
  11589. _offset.fromBufferAttribute( position, j );
  11590. _vector$8.add( _offset );
  11591. }
  11592. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  11593. }
  11594. }
  11595. }
  11596. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  11597. if ( isNaN( this.boundingSphere.radius ) ) {
  11598. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  11599. }
  11600. }
  11601. }
  11602. computeTangents() {
  11603. const index = this.index;
  11604. const attributes = this.attributes;
  11605. // based on http://www.terathon.com/code/tangent.html
  11606. // (per vertex tangents)
  11607. if ( index === null ||
  11608. attributes.position === undefined ||
  11609. attributes.normal === undefined ||
  11610. attributes.uv === undefined ) {
  11611. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  11612. return;
  11613. }
  11614. const positionAttribute = attributes.position;
  11615. const normalAttribute = attributes.normal;
  11616. const uvAttribute = attributes.uv;
  11617. if ( this.hasAttribute( 'tangent' ) === false ) {
  11618. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  11619. }
  11620. const tangentAttribute = this.getAttribute( 'tangent' );
  11621. const tan1 = [], tan2 = [];
  11622. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  11623. tan1[ i ] = new Vector3();
  11624. tan2[ i ] = new Vector3();
  11625. }
  11626. const vA = new Vector3(),
  11627. vB = new Vector3(),
  11628. vC = new Vector3(),
  11629. uvA = new Vector2(),
  11630. uvB = new Vector2(),
  11631. uvC = new Vector2(),
  11632. sdir = new Vector3(),
  11633. tdir = new Vector3();
  11634. function handleTriangle( a, b, c ) {
  11635. vA.fromBufferAttribute( positionAttribute, a );
  11636. vB.fromBufferAttribute( positionAttribute, b );
  11637. vC.fromBufferAttribute( positionAttribute, c );
  11638. uvA.fromBufferAttribute( uvAttribute, a );
  11639. uvB.fromBufferAttribute( uvAttribute, b );
  11640. uvC.fromBufferAttribute( uvAttribute, c );
  11641. vB.sub( vA );
  11642. vC.sub( vA );
  11643. uvB.sub( uvA );
  11644. uvC.sub( uvA );
  11645. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  11646. // silently ignore degenerate uv triangles having coincident or colinear vertices
  11647. if ( ! isFinite( r ) ) return;
  11648. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  11649. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  11650. tan1[ a ].add( sdir );
  11651. tan1[ b ].add( sdir );
  11652. tan1[ c ].add( sdir );
  11653. tan2[ a ].add( tdir );
  11654. tan2[ b ].add( tdir );
  11655. tan2[ c ].add( tdir );
  11656. }
  11657. let groups = this.groups;
  11658. if ( groups.length === 0 ) {
  11659. groups = [ {
  11660. start: 0,
  11661. count: index.count
  11662. } ];
  11663. }
  11664. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  11665. const group = groups[ i ];
  11666. const start = group.start;
  11667. const count = group.count;
  11668. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  11669. handleTriangle(
  11670. index.getX( j + 0 ),
  11671. index.getX( j + 1 ),
  11672. index.getX( j + 2 )
  11673. );
  11674. }
  11675. }
  11676. const tmp = new Vector3(), tmp2 = new Vector3();
  11677. const n = new Vector3(), n2 = new Vector3();
  11678. function handleVertex( v ) {
  11679. n.fromBufferAttribute( normalAttribute, v );
  11680. n2.copy( n );
  11681. const t = tan1[ v ];
  11682. // Gram-Schmidt orthogonalize
  11683. tmp.copy( t );
  11684. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  11685. // Calculate handedness
  11686. tmp2.crossVectors( n2, t );
  11687. const test = tmp2.dot( tan2[ v ] );
  11688. const w = ( test < 0.0 ) ? -1 : 1.0;
  11689. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  11690. }
  11691. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  11692. const group = groups[ i ];
  11693. const start = group.start;
  11694. const count = group.count;
  11695. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  11696. handleVertex( index.getX( j + 0 ) );
  11697. handleVertex( index.getX( j + 1 ) );
  11698. handleVertex( index.getX( j + 2 ) );
  11699. }
  11700. }
  11701. }
  11702. computeVertexNormals() {
  11703. const index = this.index;
  11704. const positionAttribute = this.getAttribute( 'position' );
  11705. if ( positionAttribute !== undefined ) {
  11706. let normalAttribute = this.getAttribute( 'normal' );
  11707. if ( normalAttribute === undefined ) {
  11708. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  11709. this.setAttribute( 'normal', normalAttribute );
  11710. } else {
  11711. // reset existing normals to zero
  11712. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  11713. normalAttribute.setXYZ( i, 0, 0, 0 );
  11714. }
  11715. }
  11716. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  11717. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  11718. const cb = new Vector3(), ab = new Vector3();
  11719. // indexed elements
  11720. if ( index ) {
  11721. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  11722. const vA = index.getX( i + 0 );
  11723. const vB = index.getX( i + 1 );
  11724. const vC = index.getX( i + 2 );
  11725. pA.fromBufferAttribute( positionAttribute, vA );
  11726. pB.fromBufferAttribute( positionAttribute, vB );
  11727. pC.fromBufferAttribute( positionAttribute, vC );
  11728. cb.subVectors( pC, pB );
  11729. ab.subVectors( pA, pB );
  11730. cb.cross( ab );
  11731. nA.fromBufferAttribute( normalAttribute, vA );
  11732. nB.fromBufferAttribute( normalAttribute, vB );
  11733. nC.fromBufferAttribute( normalAttribute, vC );
  11734. nA.add( cb );
  11735. nB.add( cb );
  11736. nC.add( cb );
  11737. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  11738. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  11739. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  11740. }
  11741. } else {
  11742. // non-indexed elements (unconnected triangle soup)
  11743. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  11744. pA.fromBufferAttribute( positionAttribute, i + 0 );
  11745. pB.fromBufferAttribute( positionAttribute, i + 1 );
  11746. pC.fromBufferAttribute( positionAttribute, i + 2 );
  11747. cb.subVectors( pC, pB );
  11748. ab.subVectors( pA, pB );
  11749. cb.cross( ab );
  11750. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  11751. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  11752. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  11753. }
  11754. }
  11755. this.normalizeNormals();
  11756. normalAttribute.needsUpdate = true;
  11757. }
  11758. }
  11759. normalizeNormals() {
  11760. const normals = this.attributes.normal;
  11761. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  11762. _vector$8.fromBufferAttribute( normals, i );
  11763. _vector$8.normalize();
  11764. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  11765. }
  11766. }
  11767. toNonIndexed() {
  11768. function convertBufferAttribute( attribute, indices ) {
  11769. const array = attribute.array;
  11770. const itemSize = attribute.itemSize;
  11771. const normalized = attribute.normalized;
  11772. const array2 = new array.constructor( indices.length * itemSize );
  11773. let index = 0, index2 = 0;
  11774. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  11775. if ( attribute.isInterleavedBufferAttribute ) {
  11776. index = indices[ i ] * attribute.data.stride + attribute.offset;
  11777. } else {
  11778. index = indices[ i ] * itemSize;
  11779. }
  11780. for ( let j = 0; j < itemSize; j ++ ) {
  11781. array2[ index2 ++ ] = array[ index ++ ];
  11782. }
  11783. }
  11784. return new BufferAttribute( array2, itemSize, normalized );
  11785. }
  11786. //
  11787. if ( this.index === null ) {
  11788. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  11789. return this;
  11790. }
  11791. const geometry2 = new BufferGeometry();
  11792. const indices = this.index.array;
  11793. const attributes = this.attributes;
  11794. // attributes
  11795. for ( const name in attributes ) {
  11796. const attribute = attributes[ name ];
  11797. const newAttribute = convertBufferAttribute( attribute, indices );
  11798. geometry2.setAttribute( name, newAttribute );
  11799. }
  11800. // morph attributes
  11801. const morphAttributes = this.morphAttributes;
  11802. for ( const name in morphAttributes ) {
  11803. const morphArray = [];
  11804. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11805. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  11806. const attribute = morphAttribute[ i ];
  11807. const newAttribute = convertBufferAttribute( attribute, indices );
  11808. morphArray.push( newAttribute );
  11809. }
  11810. geometry2.morphAttributes[ name ] = morphArray;
  11811. }
  11812. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  11813. // groups
  11814. const groups = this.groups;
  11815. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  11816. const group = groups[ i ];
  11817. geometry2.addGroup( group.start, group.count, group.materialIndex );
  11818. }
  11819. return geometry2;
  11820. }
  11821. toJSON() {
  11822. const data = {
  11823. metadata: {
  11824. version: 4.6,
  11825. type: 'BufferGeometry',
  11826. generator: 'BufferGeometry.toJSON'
  11827. }
  11828. };
  11829. // standard BufferGeometry serialization
  11830. data.uuid = this.uuid;
  11831. data.type = this.type;
  11832. if ( this.name !== '' ) data.name = this.name;
  11833. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  11834. if ( this.parameters !== undefined ) {
  11835. const parameters = this.parameters;
  11836. for ( const key in parameters ) {
  11837. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  11838. }
  11839. return data;
  11840. }
  11841. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  11842. data.data = { attributes: {} };
  11843. const index = this.index;
  11844. if ( index !== null ) {
  11845. data.data.index = {
  11846. type: index.array.constructor.name,
  11847. array: Array.prototype.slice.call( index.array )
  11848. };
  11849. }
  11850. const attributes = this.attributes;
  11851. for ( const key in attributes ) {
  11852. const attribute = attributes[ key ];
  11853. data.data.attributes[ key ] = attribute.toJSON( data.data );
  11854. }
  11855. const morphAttributes = {};
  11856. let hasMorphAttributes = false;
  11857. for ( const key in this.morphAttributes ) {
  11858. const attributeArray = this.morphAttributes[ key ];
  11859. const array = [];
  11860. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  11861. const attribute = attributeArray[ i ];
  11862. array.push( attribute.toJSON( data.data ) );
  11863. }
  11864. if ( array.length > 0 ) {
  11865. morphAttributes[ key ] = array;
  11866. hasMorphAttributes = true;
  11867. }
  11868. }
  11869. if ( hasMorphAttributes ) {
  11870. data.data.morphAttributes = morphAttributes;
  11871. data.data.morphTargetsRelative = this.morphTargetsRelative;
  11872. }
  11873. const groups = this.groups;
  11874. if ( groups.length > 0 ) {
  11875. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  11876. }
  11877. const boundingSphere = this.boundingSphere;
  11878. if ( boundingSphere !== null ) {
  11879. data.data.boundingSphere = {
  11880. center: boundingSphere.center.toArray(),
  11881. radius: boundingSphere.radius
  11882. };
  11883. }
  11884. return data;
  11885. }
  11886. clone() {
  11887. return new this.constructor().copy( this );
  11888. }
  11889. copy( source ) {
  11890. // reset
  11891. this.index = null;
  11892. this.attributes = {};
  11893. this.morphAttributes = {};
  11894. this.groups = [];
  11895. this.boundingBox = null;
  11896. this.boundingSphere = null;
  11897. // used for storing cloned, shared data
  11898. const data = {};
  11899. // name
  11900. this.name = source.name;
  11901. // index
  11902. const index = source.index;
  11903. if ( index !== null ) {
  11904. this.setIndex( index.clone( data ) );
  11905. }
  11906. // attributes
  11907. const attributes = source.attributes;
  11908. for ( const name in attributes ) {
  11909. const attribute = attributes[ name ];
  11910. this.setAttribute( name, attribute.clone( data ) );
  11911. }
  11912. // morph attributes
  11913. const morphAttributes = source.morphAttributes;
  11914. for ( const name in morphAttributes ) {
  11915. const array = [];
  11916. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11917. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  11918. array.push( morphAttribute[ i ].clone( data ) );
  11919. }
  11920. this.morphAttributes[ name ] = array;
  11921. }
  11922. this.morphTargetsRelative = source.morphTargetsRelative;
  11923. // groups
  11924. const groups = source.groups;
  11925. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  11926. const group = groups[ i ];
  11927. this.addGroup( group.start, group.count, group.materialIndex );
  11928. }
  11929. // bounding box
  11930. const boundingBox = source.boundingBox;
  11931. if ( boundingBox !== null ) {
  11932. this.boundingBox = boundingBox.clone();
  11933. }
  11934. // bounding sphere
  11935. const boundingSphere = source.boundingSphere;
  11936. if ( boundingSphere !== null ) {
  11937. this.boundingSphere = boundingSphere.clone();
  11938. }
  11939. // draw range
  11940. this.drawRange.start = source.drawRange.start;
  11941. this.drawRange.count = source.drawRange.count;
  11942. // user data
  11943. this.userData = source.userData;
  11944. return this;
  11945. }
  11946. dispose() {
  11947. this.dispatchEvent( { type: 'dispose' } );
  11948. }
  11949. }
  11950. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  11951. const _ray$3 = /*@__PURE__*/ new Ray();
  11952. const _sphere$6 = /*@__PURE__*/ new Sphere();
  11953. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  11954. const _vA$1 = /*@__PURE__*/ new Vector3();
  11955. const _vB$1 = /*@__PURE__*/ new Vector3();
  11956. const _vC$1 = /*@__PURE__*/ new Vector3();
  11957. const _tempA = /*@__PURE__*/ new Vector3();
  11958. const _morphA = /*@__PURE__*/ new Vector3();
  11959. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  11960. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  11961. /**
  11962. * Class representing triangular polygon mesh based objects.
  11963. *
  11964. * ```js
  11965. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  11966. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  11967. * const mesh = new THREE.Mesh( geometry, material );
  11968. * scene.add( mesh );
  11969. * ```
  11970. *
  11971. * @augments Object3D
  11972. */
  11973. class Mesh extends Object3D {
  11974. /**
  11975. * Constructs a new mesh.
  11976. *
  11977. * @param {BufferGeometry} [geometry] - The mesh geometry.
  11978. * @param {Material|Array<Material>} [material] - The mesh material.
  11979. */
  11980. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  11981. super();
  11982. /**
  11983. * This flag can be used for type testing.
  11984. *
  11985. * @type {boolean}
  11986. * @readonly
  11987. * @default true
  11988. */
  11989. this.isMesh = true;
  11990. this.type = 'Mesh';
  11991. /**
  11992. * The mesh geometry.
  11993. *
  11994. * @type {BufferGeometry}
  11995. */
  11996. this.geometry = geometry;
  11997. /**
  11998. * The mesh material.
  11999. *
  12000. * @type {Material|Array<Material>}
  12001. * @default MeshBasicMaterial
  12002. */
  12003. this.material = material;
  12004. /**
  12005. * A dictionary representing the morph targets in the geometry. The key is the
  12006. * morph targets name, the value its attribute index. This member is `undefined`
  12007. * by default and only set when morph targets are detected in the geometry.
  12008. *
  12009. * @type {Object<String,number>|undefined}
  12010. * @default undefined
  12011. */
  12012. this.morphTargetDictionary = undefined;
  12013. /**
  12014. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  12015. * is applied. This member is `undefined` by default and only set when morph targets are
  12016. * detected in the geometry.
  12017. *
  12018. * @type {Array<number>|undefined}
  12019. * @default undefined
  12020. */
  12021. this.morphTargetInfluences = undefined;
  12022. this.updateMorphTargets();
  12023. }
  12024. copy( source, recursive ) {
  12025. super.copy( source, recursive );
  12026. if ( source.morphTargetInfluences !== undefined ) {
  12027. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  12028. }
  12029. if ( source.morphTargetDictionary !== undefined ) {
  12030. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  12031. }
  12032. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  12033. this.geometry = source.geometry;
  12034. return this;
  12035. }
  12036. /**
  12037. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  12038. * to make sure existing morph targets can influence this 3D object.
  12039. */
  12040. updateMorphTargets() {
  12041. const geometry = this.geometry;
  12042. const morphAttributes = geometry.morphAttributes;
  12043. const keys = Object.keys( morphAttributes );
  12044. if ( keys.length > 0 ) {
  12045. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  12046. if ( morphAttribute !== undefined ) {
  12047. this.morphTargetInfluences = [];
  12048. this.morphTargetDictionary = {};
  12049. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  12050. const name = morphAttribute[ m ].name || String( m );
  12051. this.morphTargetInfluences.push( 0 );
  12052. this.morphTargetDictionary[ name ] = m;
  12053. }
  12054. }
  12055. }
  12056. }
  12057. /**
  12058. * Returns the local-space position of the vertex at the given index, taking into
  12059. * account the current animation state of both morph targets and skinning.
  12060. *
  12061. * @param {number} index - The vertex index.
  12062. * @param {Vector3} target - The target object that is used to store the method's result.
  12063. * @return {Vector3} The vertex position in local space.
  12064. */
  12065. getVertexPosition( index, target ) {
  12066. const geometry = this.geometry;
  12067. const position = geometry.attributes.position;
  12068. const morphPosition = geometry.morphAttributes.position;
  12069. const morphTargetsRelative = geometry.morphTargetsRelative;
  12070. target.fromBufferAttribute( position, index );
  12071. const morphInfluences = this.morphTargetInfluences;
  12072. if ( morphPosition && morphInfluences ) {
  12073. _morphA.set( 0, 0, 0 );
  12074. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  12075. const influence = morphInfluences[ i ];
  12076. const morphAttribute = morphPosition[ i ];
  12077. if ( influence === 0 ) continue;
  12078. _tempA.fromBufferAttribute( morphAttribute, index );
  12079. if ( morphTargetsRelative ) {
  12080. _morphA.addScaledVector( _tempA, influence );
  12081. } else {
  12082. _morphA.addScaledVector( _tempA.sub( target ), influence );
  12083. }
  12084. }
  12085. target.add( _morphA );
  12086. }
  12087. return target;
  12088. }
  12089. /**
  12090. * Computes intersection points between a casted ray and this line.
  12091. *
  12092. * @param {Raycaster} raycaster - The raycaster.
  12093. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  12094. */
  12095. raycast( raycaster, intersects ) {
  12096. const geometry = this.geometry;
  12097. const material = this.material;
  12098. const matrixWorld = this.matrixWorld;
  12099. if ( material === undefined ) return;
  12100. // test with bounding sphere in world space
  12101. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12102. _sphere$6.copy( geometry.boundingSphere );
  12103. _sphere$6.applyMatrix4( matrixWorld );
  12104. // check distance from ray origin to bounding sphere
  12105. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  12106. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  12107. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  12108. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  12109. }
  12110. // convert ray to local space of mesh
  12111. _inverseMatrix$3.copy( matrixWorld ).invert();
  12112. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  12113. // test with bounding box in local space
  12114. if ( geometry.boundingBox !== null ) {
  12115. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  12116. }
  12117. // test for intersections with geometry
  12118. this._computeIntersections( raycaster, intersects, _ray$3 );
  12119. }
  12120. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  12121. let intersection;
  12122. const geometry = this.geometry;
  12123. const material = this.material;
  12124. const index = geometry.index;
  12125. const position = geometry.attributes.position;
  12126. const uv = geometry.attributes.uv;
  12127. const uv1 = geometry.attributes.uv1;
  12128. const normal = geometry.attributes.normal;
  12129. const groups = geometry.groups;
  12130. const drawRange = geometry.drawRange;
  12131. if ( index !== null ) {
  12132. // indexed buffer geometry
  12133. if ( Array.isArray( material ) ) {
  12134. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  12135. const group = groups[ i ];
  12136. const groupMaterial = material[ group.materialIndex ];
  12137. const start = Math.max( group.start, drawRange.start );
  12138. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  12139. for ( let j = start, jl = end; j < jl; j += 3 ) {
  12140. const a = index.getX( j );
  12141. const b = index.getX( j + 1 );
  12142. const c = index.getX( j + 2 );
  12143. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12144. if ( intersection ) {
  12145. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  12146. intersection.face.materialIndex = group.materialIndex;
  12147. intersects.push( intersection );
  12148. }
  12149. }
  12150. }
  12151. } else {
  12152. const start = Math.max( 0, drawRange.start );
  12153. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  12154. for ( let i = start, il = end; i < il; i += 3 ) {
  12155. const a = index.getX( i );
  12156. const b = index.getX( i + 1 );
  12157. const c = index.getX( i + 2 );
  12158. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12159. if ( intersection ) {
  12160. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  12161. intersects.push( intersection );
  12162. }
  12163. }
  12164. }
  12165. } else if ( position !== undefined ) {
  12166. // non-indexed buffer geometry
  12167. if ( Array.isArray( material ) ) {
  12168. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  12169. const group = groups[ i ];
  12170. const groupMaterial = material[ group.materialIndex ];
  12171. const start = Math.max( group.start, drawRange.start );
  12172. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  12173. for ( let j = start, jl = end; j < jl; j += 3 ) {
  12174. const a = j;
  12175. const b = j + 1;
  12176. const c = j + 2;
  12177. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12178. if ( intersection ) {
  12179. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  12180. intersection.face.materialIndex = group.materialIndex;
  12181. intersects.push( intersection );
  12182. }
  12183. }
  12184. }
  12185. } else {
  12186. const start = Math.max( 0, drawRange.start );
  12187. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  12188. for ( let i = start, il = end; i < il; i += 3 ) {
  12189. const a = i;
  12190. const b = i + 1;
  12191. const c = i + 2;
  12192. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12193. if ( intersection ) {
  12194. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  12195. intersects.push( intersection );
  12196. }
  12197. }
  12198. }
  12199. }
  12200. }
  12201. }
  12202. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  12203. let intersect;
  12204. if ( material.side === BackSide ) {
  12205. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  12206. } else {
  12207. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  12208. }
  12209. if ( intersect === null ) return null;
  12210. _intersectionPointWorld.copy( point );
  12211. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  12212. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  12213. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  12214. return {
  12215. distance: distance,
  12216. point: _intersectionPointWorld.clone(),
  12217. object: object
  12218. };
  12219. }
  12220. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  12221. object.getVertexPosition( a, _vA$1 );
  12222. object.getVertexPosition( b, _vB$1 );
  12223. object.getVertexPosition( c, _vC$1 );
  12224. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  12225. if ( intersection ) {
  12226. const barycoord = new Vector3();
  12227. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  12228. if ( uv ) {
  12229. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  12230. }
  12231. if ( uv1 ) {
  12232. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  12233. }
  12234. if ( normal ) {
  12235. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  12236. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  12237. intersection.normal.multiplyScalar( -1 );
  12238. }
  12239. }
  12240. const face = {
  12241. a: a,
  12242. b: b,
  12243. c: c,
  12244. normal: new Vector3(),
  12245. materialIndex: 0
  12246. };
  12247. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  12248. intersection.face = face;
  12249. intersection.barycoord = barycoord;
  12250. }
  12251. return intersection;
  12252. }
  12253. /**
  12254. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  12255. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  12256. * of the axes.
  12257. *
  12258. * ```js
  12259. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  12260. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  12261. * const cube = new THREE.Mesh( geometry, material );
  12262. * scene.add( cube );
  12263. * ```
  12264. *
  12265. * @augments BufferGeometry
  12266. */
  12267. class BoxGeometry extends BufferGeometry {
  12268. /**
  12269. * Constructs a new box geometry.
  12270. *
  12271. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  12272. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  12273. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  12274. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  12275. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  12276. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  12277. */
  12278. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  12279. super();
  12280. this.type = 'BoxGeometry';
  12281. /**
  12282. * Holds the constructor parameters that have been
  12283. * used to generate the geometry. Any modification
  12284. * after instantiation does not change the geometry.
  12285. *
  12286. * @type {Object}
  12287. */
  12288. this.parameters = {
  12289. width: width,
  12290. height: height,
  12291. depth: depth,
  12292. widthSegments: widthSegments,
  12293. heightSegments: heightSegments,
  12294. depthSegments: depthSegments
  12295. };
  12296. const scope = this;
  12297. // segments
  12298. widthSegments = Math.floor( widthSegments );
  12299. heightSegments = Math.floor( heightSegments );
  12300. depthSegments = Math.floor( depthSegments );
  12301. // buffers
  12302. const indices = [];
  12303. const vertices = [];
  12304. const normals = [];
  12305. const uvs = [];
  12306. // helper variables
  12307. let numberOfVertices = 0;
  12308. let groupStart = 0;
  12309. // build each side of the box geometry
  12310. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  12311. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  12312. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  12313. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  12314. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  12315. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  12316. // build geometry
  12317. this.setIndex( indices );
  12318. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12319. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  12320. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  12321. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  12322. const segmentWidth = width / gridX;
  12323. const segmentHeight = height / gridY;
  12324. const widthHalf = width / 2;
  12325. const heightHalf = height / 2;
  12326. const depthHalf = depth / 2;
  12327. const gridX1 = gridX + 1;
  12328. const gridY1 = gridY + 1;
  12329. let vertexCounter = 0;
  12330. let groupCount = 0;
  12331. const vector = new Vector3();
  12332. // generate vertices, normals and uvs
  12333. for ( let iy = 0; iy < gridY1; iy ++ ) {
  12334. const y = iy * segmentHeight - heightHalf;
  12335. for ( let ix = 0; ix < gridX1; ix ++ ) {
  12336. const x = ix * segmentWidth - widthHalf;
  12337. // set values to correct vector component
  12338. vector[ u ] = x * udir;
  12339. vector[ v ] = y * vdir;
  12340. vector[ w ] = depthHalf;
  12341. // now apply vector to vertex buffer
  12342. vertices.push( vector.x, vector.y, vector.z );
  12343. // set values to correct vector component
  12344. vector[ u ] = 0;
  12345. vector[ v ] = 0;
  12346. vector[ w ] = depth > 0 ? 1 : -1;
  12347. // now apply vector to normal buffer
  12348. normals.push( vector.x, vector.y, vector.z );
  12349. // uvs
  12350. uvs.push( ix / gridX );
  12351. uvs.push( 1 - ( iy / gridY ) );
  12352. // counters
  12353. vertexCounter += 1;
  12354. }
  12355. }
  12356. // indices
  12357. // 1. you need three indices to draw a single face
  12358. // 2. a single segment consists of two faces
  12359. // 3. so we need to generate six (2*3) indices per segment
  12360. for ( let iy = 0; iy < gridY; iy ++ ) {
  12361. for ( let ix = 0; ix < gridX; ix ++ ) {
  12362. const a = numberOfVertices + ix + gridX1 * iy;
  12363. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  12364. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  12365. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  12366. // faces
  12367. indices.push( a, b, d );
  12368. indices.push( b, c, d );
  12369. // increase counter
  12370. groupCount += 6;
  12371. }
  12372. }
  12373. // add a group to the geometry. this will ensure multi material support
  12374. scope.addGroup( groupStart, groupCount, materialIndex );
  12375. // calculate new start value for groups
  12376. groupStart += groupCount;
  12377. // update total number of vertices
  12378. numberOfVertices += vertexCounter;
  12379. }
  12380. }
  12381. copy( source ) {
  12382. super.copy( source );
  12383. this.parameters = Object.assign( {}, source.parameters );
  12384. return this;
  12385. }
  12386. /**
  12387. * Factory method for creating an instance of this class from the given
  12388. * JSON object.
  12389. *
  12390. * @param {Object} data - A JSON object representing the serialized geometry.
  12391. * @return {BoxGeometry} A new instance.
  12392. */
  12393. static fromJSON( data ) {
  12394. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  12395. }
  12396. }
  12397. /**
  12398. * Uniform Utilities
  12399. */
  12400. function cloneUniforms( src ) {
  12401. const dst = {};
  12402. for ( const u in src ) {
  12403. dst[ u ] = {};
  12404. for ( const p in src[ u ] ) {
  12405. const property = src[ u ][ p ];
  12406. if ( property && ( property.isColor ||
  12407. property.isMatrix3 || property.isMatrix4 ||
  12408. property.isVector2 || property.isVector3 || property.isVector4 ||
  12409. property.isTexture || property.isQuaternion ) ) {
  12410. if ( property.isRenderTargetTexture ) {
  12411. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  12412. dst[ u ][ p ] = null;
  12413. } else {
  12414. dst[ u ][ p ] = property.clone();
  12415. }
  12416. } else if ( Array.isArray( property ) ) {
  12417. dst[ u ][ p ] = property.slice();
  12418. } else {
  12419. dst[ u ][ p ] = property;
  12420. }
  12421. }
  12422. }
  12423. return dst;
  12424. }
  12425. function mergeUniforms( uniforms ) {
  12426. const merged = {};
  12427. for ( let u = 0; u < uniforms.length; u ++ ) {
  12428. const tmp = cloneUniforms( uniforms[ u ] );
  12429. for ( const p in tmp ) {
  12430. merged[ p ] = tmp[ p ];
  12431. }
  12432. }
  12433. return merged;
  12434. }
  12435. function cloneUniformsGroups( src ) {
  12436. const dst = [];
  12437. for ( let u = 0; u < src.length; u ++ ) {
  12438. dst.push( src[ u ].clone() );
  12439. }
  12440. return dst;
  12441. }
  12442. function getUnlitUniformColorSpace( renderer ) {
  12443. const currentRenderTarget = renderer.getRenderTarget();
  12444. if ( currentRenderTarget === null ) {
  12445. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  12446. return renderer.outputColorSpace;
  12447. }
  12448. // https://github.com/mrdoob/three.js/issues/27868
  12449. if ( currentRenderTarget.isXRRenderTarget === true ) {
  12450. return currentRenderTarget.texture.colorSpace;
  12451. }
  12452. return ColorManagement.workingColorSpace;
  12453. }
  12454. // Legacy
  12455. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  12456. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  12457. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  12458. class ShaderMaterial extends Material {
  12459. constructor( parameters ) {
  12460. super();
  12461. this.isShaderMaterial = true;
  12462. this.type = 'ShaderMaterial';
  12463. this.defines = {};
  12464. this.uniforms = {};
  12465. this.uniformsGroups = [];
  12466. this.vertexShader = default_vertex;
  12467. this.fragmentShader = default_fragment;
  12468. this.linewidth = 1;
  12469. this.wireframe = false;
  12470. this.wireframeLinewidth = 1;
  12471. this.fog = false; // set to use scene fog
  12472. this.lights = false; // set to use scene lights
  12473. this.clipping = false; // set to use user-defined clipping planes
  12474. this.forceSinglePass = true;
  12475. this.extensions = {
  12476. clipCullDistance: false, // set to use vertex shader clipping
  12477. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  12478. };
  12479. // When rendered geometry doesn't include these attributes but the material does,
  12480. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12481. this.defaultAttributeValues = {
  12482. 'color': [ 1, 1, 1 ],
  12483. 'uv': [ 0, 0 ],
  12484. 'uv1': [ 0, 0 ]
  12485. };
  12486. this.index0AttributeName = undefined;
  12487. this.uniformsNeedUpdate = false;
  12488. this.glslVersion = null;
  12489. if ( parameters !== undefined ) {
  12490. this.setValues( parameters );
  12491. }
  12492. }
  12493. copy( source ) {
  12494. super.copy( source );
  12495. this.fragmentShader = source.fragmentShader;
  12496. this.vertexShader = source.vertexShader;
  12497. this.uniforms = cloneUniforms( source.uniforms );
  12498. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  12499. this.defines = Object.assign( {}, source.defines );
  12500. this.wireframe = source.wireframe;
  12501. this.wireframeLinewidth = source.wireframeLinewidth;
  12502. this.fog = source.fog;
  12503. this.lights = source.lights;
  12504. this.clipping = source.clipping;
  12505. this.extensions = Object.assign( {}, source.extensions );
  12506. this.glslVersion = source.glslVersion;
  12507. return this;
  12508. }
  12509. toJSON( meta ) {
  12510. const data = super.toJSON( meta );
  12511. data.glslVersion = this.glslVersion;
  12512. data.uniforms = {};
  12513. for ( const name in this.uniforms ) {
  12514. const uniform = this.uniforms[ name ];
  12515. const value = uniform.value;
  12516. if ( value && value.isTexture ) {
  12517. data.uniforms[ name ] = {
  12518. type: 't',
  12519. value: value.toJSON( meta ).uuid
  12520. };
  12521. } else if ( value && value.isColor ) {
  12522. data.uniforms[ name ] = {
  12523. type: 'c',
  12524. value: value.getHex()
  12525. };
  12526. } else if ( value && value.isVector2 ) {
  12527. data.uniforms[ name ] = {
  12528. type: 'v2',
  12529. value: value.toArray()
  12530. };
  12531. } else if ( value && value.isVector3 ) {
  12532. data.uniforms[ name ] = {
  12533. type: 'v3',
  12534. value: value.toArray()
  12535. };
  12536. } else if ( value && value.isVector4 ) {
  12537. data.uniforms[ name ] = {
  12538. type: 'v4',
  12539. value: value.toArray()
  12540. };
  12541. } else if ( value && value.isMatrix3 ) {
  12542. data.uniforms[ name ] = {
  12543. type: 'm3',
  12544. value: value.toArray()
  12545. };
  12546. } else if ( value && value.isMatrix4 ) {
  12547. data.uniforms[ name ] = {
  12548. type: 'm4',
  12549. value: value.toArray()
  12550. };
  12551. } else {
  12552. data.uniforms[ name ] = {
  12553. value: value
  12554. };
  12555. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  12556. }
  12557. }
  12558. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  12559. data.vertexShader = this.vertexShader;
  12560. data.fragmentShader = this.fragmentShader;
  12561. data.lights = this.lights;
  12562. data.clipping = this.clipping;
  12563. const extensions = {};
  12564. for ( const key in this.extensions ) {
  12565. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  12566. }
  12567. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  12568. return data;
  12569. }
  12570. }
  12571. /**
  12572. * Abstract base class for cameras. This class should always be inherited
  12573. * when you build a new camera.
  12574. *
  12575. * @abstract
  12576. * @augments Object3D
  12577. */
  12578. class Camera extends Object3D {
  12579. /**
  12580. * Constructs a new camera.
  12581. */
  12582. constructor() {
  12583. super();
  12584. /**
  12585. * This flag can be used for type testing.
  12586. *
  12587. * @type {boolean}
  12588. * @readonly
  12589. * @default true
  12590. */
  12591. this.isCamera = true;
  12592. this.type = 'Camera';
  12593. /**
  12594. * The inverse of the camera's world matrix.
  12595. *
  12596. * @type {Matrix4}
  12597. */
  12598. this.matrixWorldInverse = new Matrix4();
  12599. /**
  12600. * The camera's projection matrix.
  12601. *
  12602. * @type {Matrix4}
  12603. */
  12604. this.projectionMatrix = new Matrix4();
  12605. /**
  12606. * The inverse of the camera's projection matrix.
  12607. *
  12608. * @type {Matrix4}
  12609. */
  12610. this.projectionMatrixInverse = new Matrix4();
  12611. /**
  12612. * The coordinate system in which the camera is used.
  12613. *
  12614. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  12615. */
  12616. this.coordinateSystem = WebGLCoordinateSystem;
  12617. }
  12618. copy( source, recursive ) {
  12619. super.copy( source, recursive );
  12620. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  12621. this.projectionMatrix.copy( source.projectionMatrix );
  12622. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  12623. this.coordinateSystem = source.coordinateSystem;
  12624. return this;
  12625. }
  12626. /**
  12627. * Returns a vector representing the ("look") direction of the 3D object in world space.
  12628. *
  12629. * This method is overwritten since cameras have a different forward vector compared to other
  12630. * 3D objects. A camera looks down its local, negative z-axis by default.
  12631. *
  12632. * @param {Vector3} target - The target vector the result is stored to.
  12633. * @return {Vector3} The 3D object's direction in world space.
  12634. */
  12635. getWorldDirection( target ) {
  12636. return super.getWorldDirection( target ).negate();
  12637. }
  12638. updateMatrixWorld( force ) {
  12639. super.updateMatrixWorld( force );
  12640. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  12641. }
  12642. updateWorldMatrix( updateParents, updateChildren ) {
  12643. super.updateWorldMatrix( updateParents, updateChildren );
  12644. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  12645. }
  12646. clone() {
  12647. return new this.constructor().copy( this );
  12648. }
  12649. }
  12650. const _v3$1 = /*@__PURE__*/ new Vector3();
  12651. const _minTarget = /*@__PURE__*/ new Vector2();
  12652. const _maxTarget = /*@__PURE__*/ new Vector2();
  12653. /**
  12654. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  12655. *
  12656. * This projection mode is designed to mimic the way the human eye sees. It
  12657. * is the most common projection mode used for rendering a 3D scene.
  12658. *
  12659. * ```js
  12660. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  12661. * scene.add( camera );
  12662. * ```
  12663. *
  12664. * @augments Camera
  12665. */
  12666. class PerspectiveCamera extends Camera {
  12667. /**
  12668. * Constructs a new perspective camera.
  12669. *
  12670. * @param {number} [fov=50] - The vertical field of view.
  12671. * @param {number} [aspect=1] - The aspect ratio.
  12672. * @param {number} [near=0.1] - The camera's near plane.
  12673. * @param {number} [far=2000] - The camera's far plane.
  12674. */
  12675. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  12676. super();
  12677. /**
  12678. * This flag can be used for type testing.
  12679. *
  12680. * @type {boolean}
  12681. * @readonly
  12682. * @default true
  12683. */
  12684. this.isPerspectiveCamera = true;
  12685. this.type = 'PerspectiveCamera';
  12686. /**
  12687. * The vertical field of view, from bottom to top of view,
  12688. * in degrees.
  12689. *
  12690. * @type {number}
  12691. * @default 50
  12692. */
  12693. this.fov = fov;
  12694. /**
  12695. * The zoom factor of the camera.
  12696. *
  12697. * @type {number}
  12698. * @default 1
  12699. */
  12700. this.zoom = 1;
  12701. /**
  12702. * The camera's near plane. The valid range is greater than `0`
  12703. * and less than the current value of {@link PerspectiveCamera#far}.
  12704. *
  12705. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  12706. * valid value for a perspective camera's near plane.
  12707. *
  12708. * @type {number}
  12709. * @default 0.1
  12710. */
  12711. this.near = near;
  12712. /**
  12713. * The camera's far plane. Must be greater than the
  12714. * current value of {@link PerspectiveCamera#near}.
  12715. *
  12716. * @type {number}
  12717. * @default 2000
  12718. */
  12719. this.far = far;
  12720. /**
  12721. * Object distance used for stereoscopy and depth-of-field effects. This
  12722. * parameter does not influence the projection matrix unless a
  12723. * {@link StereoCamera} is being used.
  12724. *
  12725. * @type {number}
  12726. * @default 10
  12727. */
  12728. this.focus = 10;
  12729. /**
  12730. * The aspect ratio, usually the canvas width / canvas height.
  12731. *
  12732. * @type {number}
  12733. * @default 1
  12734. */
  12735. this.aspect = aspect;
  12736. /**
  12737. * Represents the frustum window specification. This property should not be edited
  12738. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  12739. *
  12740. * @type {?Object}
  12741. * @default null
  12742. */
  12743. this.view = null;
  12744. /**
  12745. * Film size used for the larger axis. Default is `35` (millimeters). This
  12746. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  12747. * is set to a nonzero value.
  12748. *
  12749. * @type {number}
  12750. * @default 35
  12751. */
  12752. this.filmGauge = 35;
  12753. /**
  12754. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  12755. *
  12756. * @type {number}
  12757. * @default 0
  12758. */
  12759. this.filmOffset = 0;
  12760. this.updateProjectionMatrix();
  12761. }
  12762. copy( source, recursive ) {
  12763. super.copy( source, recursive );
  12764. this.fov = source.fov;
  12765. this.zoom = source.zoom;
  12766. this.near = source.near;
  12767. this.far = source.far;
  12768. this.focus = source.focus;
  12769. this.aspect = source.aspect;
  12770. this.view = source.view === null ? null : Object.assign( {}, source.view );
  12771. this.filmGauge = source.filmGauge;
  12772. this.filmOffset = source.filmOffset;
  12773. return this;
  12774. }
  12775. /**
  12776. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  12777. *
  12778. * The default film gauge is 35, so that the focal length can be specified for
  12779. * a 35mm (full frame) camera.
  12780. *
  12781. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  12782. */
  12783. setFocalLength( focalLength ) {
  12784. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  12785. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  12786. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  12787. this.updateProjectionMatrix();
  12788. }
  12789. /**
  12790. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  12791. * {@link PerspectiveCamera#filmGauge}.
  12792. *
  12793. * @return {number} The computed focal length.
  12794. */
  12795. getFocalLength() {
  12796. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  12797. return 0.5 * this.getFilmHeight() / vExtentSlope;
  12798. }
  12799. /**
  12800. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  12801. *
  12802. * @return {number} The effective FOV.
  12803. */
  12804. getEffectiveFOV() {
  12805. return RAD2DEG * 2 * Math.atan(
  12806. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  12807. }
  12808. /**
  12809. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  12810. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  12811. *
  12812. * @return {number} The film width.
  12813. */
  12814. getFilmWidth() {
  12815. // film not completely covered in portrait format (aspect < 1)
  12816. return this.filmGauge * Math.min( this.aspect, 1 );
  12817. }
  12818. /**
  12819. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  12820. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  12821. *
  12822. * @return {number} The film width.
  12823. */
  12824. getFilmHeight() {
  12825. // film not completely covered in landscape format (aspect > 1)
  12826. return this.filmGauge / Math.max( this.aspect, 1 );
  12827. }
  12828. /**
  12829. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  12830. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  12831. *
  12832. * @param {number} distance - The viewing distance.
  12833. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  12834. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  12835. */
  12836. getViewBounds( distance, minTarget, maxTarget ) {
  12837. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  12838. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  12839. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  12840. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  12841. }
  12842. /**
  12843. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  12844. *
  12845. * @param {number} distance - The viewing distance.
  12846. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  12847. * @returns {Vector2} The view size.
  12848. */
  12849. getViewSize( distance, target ) {
  12850. this.getViewBounds( distance, _minTarget, _maxTarget );
  12851. return target.subVectors( _maxTarget, _minTarget );
  12852. }
  12853. /**
  12854. * Sets an offset in a larger frustum. This is useful for multi-window or
  12855. * multi-monitor/multi-machine setups.
  12856. *
  12857. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  12858. * the monitors are in grid like this
  12859. *```
  12860. * +---+---+---+
  12861. * | A | B | C |
  12862. * +---+---+---+
  12863. * | D | E | F |
  12864. * +---+---+---+
  12865. *```
  12866. * then for each monitor you would call it like this:
  12867. *```js
  12868. * const w = 1920;
  12869. * const h = 1080;
  12870. * const fullWidth = w * 3;
  12871. * const fullHeight = h * 2;
  12872. *
  12873. * // --A--
  12874. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  12875. * // --B--
  12876. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  12877. * // --C--
  12878. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  12879. * // --D--
  12880. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  12881. * // --E--
  12882. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  12883. * // --F--
  12884. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  12885. * ```
  12886. *
  12887. * Note there is no reason monitors have to be the same size or in a grid.
  12888. *
  12889. * @param {number} fullWidth - The full width of multiview setup.
  12890. * @param {number} fullHeight - The full height of multiview setup.
  12891. * @param {number} x - The horizontal offset of the subcamera.
  12892. * @param {number} y - The vertical offset of the subcamera.
  12893. * @param {number} width - The width of subcamera.
  12894. * @param {number} height - The height of subcamera.
  12895. */
  12896. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  12897. this.aspect = fullWidth / fullHeight;
  12898. if ( this.view === null ) {
  12899. this.view = {
  12900. enabled: true,
  12901. fullWidth: 1,
  12902. fullHeight: 1,
  12903. offsetX: 0,
  12904. offsetY: 0,
  12905. width: 1,
  12906. height: 1
  12907. };
  12908. }
  12909. this.view.enabled = true;
  12910. this.view.fullWidth = fullWidth;
  12911. this.view.fullHeight = fullHeight;
  12912. this.view.offsetX = x;
  12913. this.view.offsetY = y;
  12914. this.view.width = width;
  12915. this.view.height = height;
  12916. this.updateProjectionMatrix();
  12917. }
  12918. /**
  12919. * Removes the view offset from the projection matrix.
  12920. */
  12921. clearViewOffset() {
  12922. if ( this.view !== null ) {
  12923. this.view.enabled = false;
  12924. }
  12925. this.updateProjectionMatrix();
  12926. }
  12927. /**
  12928. * Updates the camera's projection matrix. Must be called after any change of
  12929. * camera properties.
  12930. */
  12931. updateProjectionMatrix() {
  12932. const near = this.near;
  12933. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  12934. let height = 2 * top;
  12935. let width = this.aspect * height;
  12936. let left = -0.5 * width;
  12937. const view = this.view;
  12938. if ( this.view !== null && this.view.enabled ) {
  12939. const fullWidth = view.fullWidth,
  12940. fullHeight = view.fullHeight;
  12941. left += view.offsetX * width / fullWidth;
  12942. top -= view.offsetY * height / fullHeight;
  12943. width *= view.width / fullWidth;
  12944. height *= view.height / fullHeight;
  12945. }
  12946. const skew = this.filmOffset;
  12947. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  12948. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  12949. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  12950. }
  12951. toJSON( meta ) {
  12952. const data = super.toJSON( meta );
  12953. data.object.fov = this.fov;
  12954. data.object.zoom = this.zoom;
  12955. data.object.near = this.near;
  12956. data.object.far = this.far;
  12957. data.object.focus = this.focus;
  12958. data.object.aspect = this.aspect;
  12959. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  12960. data.object.filmGauge = this.filmGauge;
  12961. data.object.filmOffset = this.filmOffset;
  12962. return data;
  12963. }
  12964. }
  12965. const fov = -90; // negative fov is not an error
  12966. const aspect = 1;
  12967. /**
  12968. * A special type of camera that is positioned in 3D space to render its surroundings into a
  12969. * cube render target. The render target can then be used as an environment map for rendering
  12970. * realtime reflections in your scene.
  12971. *
  12972. * ```js
  12973. * // Create cube render target
  12974. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  12975. *
  12976. * // Create cube camera
  12977. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  12978. * scene.add( cubeCamera );
  12979. *
  12980. * // Create car
  12981. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  12982. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  12983. * scene.add( car );
  12984. *
  12985. * // Update the render target cube
  12986. * car.visible = false;
  12987. * cubeCamera.position.copy( car.position );
  12988. * cubeCamera.update( renderer, scene );
  12989. *
  12990. * // Render the scene
  12991. * car.visible = true;
  12992. * renderer.render( scene, camera );
  12993. * ```
  12994. *
  12995. * @augments Object3D
  12996. */
  12997. class CubeCamera extends Object3D {
  12998. /**
  12999. * Constructs a new cube camera.
  13000. *
  13001. * @param {number} near - The camera's near plane.
  13002. * @param {number} far - The camera's far plane.
  13003. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  13004. */
  13005. constructor( near, far, renderTarget ) {
  13006. super();
  13007. this.type = 'CubeCamera';
  13008. /**
  13009. * A reference to the cube render target.
  13010. *
  13011. * @type {WebGLCubeRenderTarget}
  13012. */
  13013. this.renderTarget = renderTarget;
  13014. /**
  13015. * The current active coordinate system.
  13016. *
  13017. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  13018. * @default null
  13019. */
  13020. this.coordinateSystem = null;
  13021. /**
  13022. * The current active mipmap level
  13023. *
  13024. * @type {number}
  13025. * @default 0
  13026. */
  13027. this.activeMipmapLevel = 0;
  13028. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  13029. cameraPX.layers = this.layers;
  13030. this.add( cameraPX );
  13031. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  13032. cameraNX.layers = this.layers;
  13033. this.add( cameraNX );
  13034. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  13035. cameraPY.layers = this.layers;
  13036. this.add( cameraPY );
  13037. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  13038. cameraNY.layers = this.layers;
  13039. this.add( cameraNY );
  13040. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  13041. cameraPZ.layers = this.layers;
  13042. this.add( cameraPZ );
  13043. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  13044. cameraNZ.layers = this.layers;
  13045. this.add( cameraNZ );
  13046. }
  13047. /**
  13048. * Must be called when the coordinate system of the cube camera is changed.
  13049. */
  13050. updateCoordinateSystem() {
  13051. const coordinateSystem = this.coordinateSystem;
  13052. const cameras = this.children.concat();
  13053. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  13054. for ( const camera of cameras ) this.remove( camera );
  13055. if ( coordinateSystem === WebGLCoordinateSystem ) {
  13056. cameraPX.up.set( 0, 1, 0 );
  13057. cameraPX.lookAt( 1, 0, 0 );
  13058. cameraNX.up.set( 0, 1, 0 );
  13059. cameraNX.lookAt( -1, 0, 0 );
  13060. cameraPY.up.set( 0, 0, -1 );
  13061. cameraPY.lookAt( 0, 1, 0 );
  13062. cameraNY.up.set( 0, 0, 1 );
  13063. cameraNY.lookAt( 0, -1, 0 );
  13064. cameraPZ.up.set( 0, 1, 0 );
  13065. cameraPZ.lookAt( 0, 0, 1 );
  13066. cameraNZ.up.set( 0, 1, 0 );
  13067. cameraNZ.lookAt( 0, 0, -1 );
  13068. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  13069. cameraPX.up.set( 0, -1, 0 );
  13070. cameraPX.lookAt( -1, 0, 0 );
  13071. cameraNX.up.set( 0, -1, 0 );
  13072. cameraNX.lookAt( 1, 0, 0 );
  13073. cameraPY.up.set( 0, 0, 1 );
  13074. cameraPY.lookAt( 0, 1, 0 );
  13075. cameraNY.up.set( 0, 0, -1 );
  13076. cameraNY.lookAt( 0, -1, 0 );
  13077. cameraPZ.up.set( 0, -1, 0 );
  13078. cameraPZ.lookAt( 0, 0, 1 );
  13079. cameraNZ.up.set( 0, -1, 0 );
  13080. cameraNZ.lookAt( 0, 0, -1 );
  13081. } else {
  13082. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  13083. }
  13084. for ( const camera of cameras ) {
  13085. this.add( camera );
  13086. camera.updateMatrixWorld();
  13087. }
  13088. }
  13089. /**
  13090. * Calling this method will render the given scene with the given renderer
  13091. * into the cube render target of the camera.
  13092. *
  13093. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  13094. * @param {Scene} scene - The scene to render.
  13095. */
  13096. update( renderer, scene ) {
  13097. if ( this.parent === null ) this.updateMatrixWorld();
  13098. const { renderTarget, activeMipmapLevel } = this;
  13099. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  13100. this.coordinateSystem = renderer.coordinateSystem;
  13101. this.updateCoordinateSystem();
  13102. }
  13103. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  13104. const currentRenderTarget = renderer.getRenderTarget();
  13105. const currentActiveCubeFace = renderer.getActiveCubeFace();
  13106. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  13107. const currentXrEnabled = renderer.xr.enabled;
  13108. renderer.xr.enabled = false;
  13109. const generateMipmaps = renderTarget.texture.generateMipmaps;
  13110. renderTarget.texture.generateMipmaps = false;
  13111. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  13112. renderer.render( scene, cameraPX );
  13113. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  13114. renderer.render( scene, cameraNX );
  13115. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  13116. renderer.render( scene, cameraPY );
  13117. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  13118. renderer.render( scene, cameraNY );
  13119. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  13120. renderer.render( scene, cameraPZ );
  13121. // mipmaps are generated during the last call of render()
  13122. // at this point, all sides of the cube render target are defined
  13123. renderTarget.texture.generateMipmaps = generateMipmaps;
  13124. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  13125. renderer.render( scene, cameraNZ );
  13126. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  13127. renderer.xr.enabled = currentXrEnabled;
  13128. renderTarget.texture.needsPMREMUpdate = true;
  13129. }
  13130. }
  13131. class CubeTexture extends Texture {
  13132. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  13133. images = images !== undefined ? images : [];
  13134. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  13135. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  13136. this.isCubeTexture = true;
  13137. this.flipY = false;
  13138. }
  13139. get images() {
  13140. return this.image;
  13141. }
  13142. set images( value ) {
  13143. this.image = value;
  13144. }
  13145. }
  13146. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  13147. constructor( size = 1, options = {} ) {
  13148. super( size, size, options );
  13149. this.isWebGLCubeRenderTarget = true;
  13150. const image = { width: size, height: size, depth: 1 };
  13151. const images = [ image, image, image, image, image, image ];
  13152. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  13153. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  13154. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  13155. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  13156. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  13157. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  13158. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  13159. this.texture.isRenderTargetTexture = true;
  13160. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  13161. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  13162. }
  13163. fromEquirectangularTexture( renderer, texture ) {
  13164. this.texture.type = texture.type;
  13165. this.texture.colorSpace = texture.colorSpace;
  13166. this.texture.generateMipmaps = texture.generateMipmaps;
  13167. this.texture.minFilter = texture.minFilter;
  13168. this.texture.magFilter = texture.magFilter;
  13169. const shader = {
  13170. uniforms: {
  13171. tEquirect: { value: null },
  13172. },
  13173. vertexShader: /* glsl */`
  13174. varying vec3 vWorldDirection;
  13175. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  13176. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  13177. }
  13178. void main() {
  13179. vWorldDirection = transformDirection( position, modelMatrix );
  13180. #include <begin_vertex>
  13181. #include <project_vertex>
  13182. }
  13183. `,
  13184. fragmentShader: /* glsl */`
  13185. uniform sampler2D tEquirect;
  13186. varying vec3 vWorldDirection;
  13187. #include <common>
  13188. void main() {
  13189. vec3 direction = normalize( vWorldDirection );
  13190. vec2 sampleUV = equirectUv( direction );
  13191. gl_FragColor = texture2D( tEquirect, sampleUV );
  13192. }
  13193. `
  13194. };
  13195. const geometry = new BoxGeometry( 5, 5, 5 );
  13196. const material = new ShaderMaterial( {
  13197. name: 'CubemapFromEquirect',
  13198. uniforms: cloneUniforms( shader.uniforms ),
  13199. vertexShader: shader.vertexShader,
  13200. fragmentShader: shader.fragmentShader,
  13201. side: BackSide,
  13202. blending: NoBlending
  13203. } );
  13204. material.uniforms.tEquirect.value = texture;
  13205. const mesh = new Mesh( geometry, material );
  13206. const currentMinFilter = texture.minFilter;
  13207. // Avoid blurred poles
  13208. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  13209. const camera = new CubeCamera( 1, 10, this );
  13210. camera.update( renderer, mesh );
  13211. texture.minFilter = currentMinFilter;
  13212. mesh.geometry.dispose();
  13213. mesh.material.dispose();
  13214. return this;
  13215. }
  13216. clear( renderer, color, depth, stencil ) {
  13217. const currentRenderTarget = renderer.getRenderTarget();
  13218. for ( let i = 0; i < 6; i ++ ) {
  13219. renderer.setRenderTarget( this, i );
  13220. renderer.clear( color, depth, stencil );
  13221. }
  13222. renderer.setRenderTarget( currentRenderTarget );
  13223. }
  13224. }
  13225. /**
  13226. * This is almost identical to an {@link Object3D}. Its purpose is to
  13227. * make working with groups of objects syntactically clearer.
  13228. *
  13229. * ```js
  13230. * // Create a group and add the two cubes.
  13231. * // These cubes can now be rotated / scaled etc as a group.
  13232. * const group = new THREE.Group();
  13233. *
  13234. * group.add( meshA );
  13235. * group.add( meshB );
  13236. *
  13237. * scene.add( group );
  13238. * ```
  13239. *
  13240. * @augments Object3D
  13241. */
  13242. class Group extends Object3D {
  13243. constructor() {
  13244. super();
  13245. /**
  13246. * This flag can be used for type testing.
  13247. *
  13248. * @type {boolean}
  13249. * @readonly
  13250. * @default true
  13251. */
  13252. this.isGroup = true;
  13253. this.type = 'Group';
  13254. }
  13255. }
  13256. const _moveEvent = { type: 'move' };
  13257. class WebXRController {
  13258. constructor() {
  13259. this._targetRay = null;
  13260. this._grip = null;
  13261. this._hand = null;
  13262. }
  13263. getHandSpace() {
  13264. if ( this._hand === null ) {
  13265. this._hand = new Group();
  13266. this._hand.matrixAutoUpdate = false;
  13267. this._hand.visible = false;
  13268. this._hand.joints = {};
  13269. this._hand.inputState = { pinching: false };
  13270. }
  13271. return this._hand;
  13272. }
  13273. getTargetRaySpace() {
  13274. if ( this._targetRay === null ) {
  13275. this._targetRay = new Group();
  13276. this._targetRay.matrixAutoUpdate = false;
  13277. this._targetRay.visible = false;
  13278. this._targetRay.hasLinearVelocity = false;
  13279. this._targetRay.linearVelocity = new Vector3();
  13280. this._targetRay.hasAngularVelocity = false;
  13281. this._targetRay.angularVelocity = new Vector3();
  13282. }
  13283. return this._targetRay;
  13284. }
  13285. getGripSpace() {
  13286. if ( this._grip === null ) {
  13287. this._grip = new Group();
  13288. this._grip.matrixAutoUpdate = false;
  13289. this._grip.visible = false;
  13290. this._grip.hasLinearVelocity = false;
  13291. this._grip.linearVelocity = new Vector3();
  13292. this._grip.hasAngularVelocity = false;
  13293. this._grip.angularVelocity = new Vector3();
  13294. }
  13295. return this._grip;
  13296. }
  13297. dispatchEvent( event ) {
  13298. if ( this._targetRay !== null ) {
  13299. this._targetRay.dispatchEvent( event );
  13300. }
  13301. if ( this._grip !== null ) {
  13302. this._grip.dispatchEvent( event );
  13303. }
  13304. if ( this._hand !== null ) {
  13305. this._hand.dispatchEvent( event );
  13306. }
  13307. return this;
  13308. }
  13309. connect( inputSource ) {
  13310. if ( inputSource && inputSource.hand ) {
  13311. const hand = this._hand;
  13312. if ( hand ) {
  13313. for ( const inputjoint of inputSource.hand.values() ) {
  13314. // Initialize hand with joints when connected
  13315. this._getHandJoint( hand, inputjoint );
  13316. }
  13317. }
  13318. }
  13319. this.dispatchEvent( { type: 'connected', data: inputSource } );
  13320. return this;
  13321. }
  13322. disconnect( inputSource ) {
  13323. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13324. if ( this._targetRay !== null ) {
  13325. this._targetRay.visible = false;
  13326. }
  13327. if ( this._grip !== null ) {
  13328. this._grip.visible = false;
  13329. }
  13330. if ( this._hand !== null ) {
  13331. this._hand.visible = false;
  13332. }
  13333. return this;
  13334. }
  13335. update( inputSource, frame, referenceSpace ) {
  13336. let inputPose = null;
  13337. let gripPose = null;
  13338. let handPose = null;
  13339. const targetRay = this._targetRay;
  13340. const grip = this._grip;
  13341. const hand = this._hand;
  13342. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  13343. if ( hand && inputSource.hand ) {
  13344. handPose = true;
  13345. for ( const inputjoint of inputSource.hand.values() ) {
  13346. // Update the joints groups with the XRJoint poses
  13347. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  13348. // The transform of this joint will be updated with the joint pose on each frame
  13349. const joint = this._getHandJoint( hand, inputjoint );
  13350. if ( jointPose !== null ) {
  13351. joint.matrix.fromArray( jointPose.transform.matrix );
  13352. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  13353. joint.matrixWorldNeedsUpdate = true;
  13354. joint.jointRadius = jointPose.radius;
  13355. }
  13356. joint.visible = jointPose !== null;
  13357. }
  13358. // Custom events
  13359. // Check pinchz
  13360. const indexTip = hand.joints[ 'index-finger-tip' ];
  13361. const thumbTip = hand.joints[ 'thumb-tip' ];
  13362. const distance = indexTip.position.distanceTo( thumbTip.position );
  13363. const distanceToPinch = 0.02;
  13364. const threshold = 0.005;
  13365. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  13366. hand.inputState.pinching = false;
  13367. this.dispatchEvent( {
  13368. type: 'pinchend',
  13369. handedness: inputSource.handedness,
  13370. target: this
  13371. } );
  13372. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  13373. hand.inputState.pinching = true;
  13374. this.dispatchEvent( {
  13375. type: 'pinchstart',
  13376. handedness: inputSource.handedness,
  13377. target: this
  13378. } );
  13379. }
  13380. } else {
  13381. if ( grip !== null && inputSource.gripSpace ) {
  13382. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  13383. if ( gripPose !== null ) {
  13384. grip.matrix.fromArray( gripPose.transform.matrix );
  13385. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  13386. grip.matrixWorldNeedsUpdate = true;
  13387. if ( gripPose.linearVelocity ) {
  13388. grip.hasLinearVelocity = true;
  13389. grip.linearVelocity.copy( gripPose.linearVelocity );
  13390. } else {
  13391. grip.hasLinearVelocity = false;
  13392. }
  13393. if ( gripPose.angularVelocity ) {
  13394. grip.hasAngularVelocity = true;
  13395. grip.angularVelocity.copy( gripPose.angularVelocity );
  13396. } else {
  13397. grip.hasAngularVelocity = false;
  13398. }
  13399. }
  13400. }
  13401. }
  13402. if ( targetRay !== null ) {
  13403. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13404. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  13405. if ( inputPose === null && gripPose !== null ) {
  13406. inputPose = gripPose;
  13407. }
  13408. if ( inputPose !== null ) {
  13409. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13410. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13411. targetRay.matrixWorldNeedsUpdate = true;
  13412. if ( inputPose.linearVelocity ) {
  13413. targetRay.hasLinearVelocity = true;
  13414. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  13415. } else {
  13416. targetRay.hasLinearVelocity = false;
  13417. }
  13418. if ( inputPose.angularVelocity ) {
  13419. targetRay.hasAngularVelocity = true;
  13420. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  13421. } else {
  13422. targetRay.hasAngularVelocity = false;
  13423. }
  13424. this.dispatchEvent( _moveEvent );
  13425. }
  13426. }
  13427. }
  13428. if ( targetRay !== null ) {
  13429. targetRay.visible = ( inputPose !== null );
  13430. }
  13431. if ( grip !== null ) {
  13432. grip.visible = ( gripPose !== null );
  13433. }
  13434. if ( hand !== null ) {
  13435. hand.visible = ( handPose !== null );
  13436. }
  13437. return this;
  13438. }
  13439. // private method
  13440. _getHandJoint( hand, inputjoint ) {
  13441. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  13442. const joint = new Group();
  13443. joint.matrixAutoUpdate = false;
  13444. joint.visible = false;
  13445. hand.joints[ inputjoint.jointName ] = joint;
  13446. hand.add( joint );
  13447. }
  13448. return hand.joints[ inputjoint.jointName ];
  13449. }
  13450. }
  13451. /**
  13452. * This class can be used to define an exponential squared fog,
  13453. * which gives a clear view near the camera and a faster than exponentially
  13454. * densening fog farther from the camera.
  13455. *
  13456. * ```js
  13457. * const scene = new THREE.Scene();
  13458. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  13459. * ```
  13460. */
  13461. class FogExp2 {
  13462. /**
  13463. * Constructs a new fog.
  13464. *
  13465. * @param {number|Color} color - The fog's color.
  13466. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  13467. */
  13468. constructor( color, density = 0.00025 ) {
  13469. /**
  13470. * This flag can be used for type testing.
  13471. *
  13472. * @type {boolean}
  13473. * @readonly
  13474. * @default true
  13475. */
  13476. this.isFogExp2 = true;
  13477. /**
  13478. * The name of the fog.
  13479. *
  13480. * @type {string}
  13481. */
  13482. this.name = '';
  13483. /**
  13484. * The fog's color.
  13485. *
  13486. * @type {Color}
  13487. */
  13488. this.color = new Color( color );
  13489. /**
  13490. * Defines how fast the fog will grow dense.
  13491. *
  13492. * @type {number}
  13493. * @default 0.00025
  13494. */
  13495. this.density = density;
  13496. }
  13497. /**
  13498. * Returns a new fog with copied values from this instance.
  13499. *
  13500. * @return {FogExp2} A clone of this instance.
  13501. */
  13502. clone() {
  13503. return new FogExp2( this.color, this.density );
  13504. }
  13505. /**
  13506. * Serializes the fog into JSON.
  13507. *
  13508. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  13509. * @return {Object} A JSON object representing the serialized fog
  13510. */
  13511. toJSON( /* meta */ ) {
  13512. return {
  13513. type: 'FogExp2',
  13514. name: this.name,
  13515. color: this.color.getHex(),
  13516. density: this.density
  13517. };
  13518. }
  13519. }
  13520. /**
  13521. * This class can be used to define a linear fog that grows linearly denser
  13522. * with the distance.
  13523. *
  13524. * ```js
  13525. * const scene = new THREE.Scene();
  13526. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  13527. * ```
  13528. */
  13529. class Fog {
  13530. /**
  13531. * Constructs a new fog.
  13532. *
  13533. * @param {number|Color} color - The fog's color.
  13534. * @param {number} [near=1] - The minimum distance to start applying fog.
  13535. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  13536. */
  13537. constructor( color, near = 1, far = 1000 ) {
  13538. /**
  13539. * This flag can be used for type testing.
  13540. *
  13541. * @type {boolean}
  13542. * @readonly
  13543. * @default true
  13544. */
  13545. this.isFog = true;
  13546. /**
  13547. * The name of the fog.
  13548. *
  13549. * @type {string}
  13550. */
  13551. this.name = '';
  13552. /**
  13553. * The fog's color.
  13554. *
  13555. * @type {Color}
  13556. */
  13557. this.color = new Color( color );
  13558. /**
  13559. * The minimum distance to start applying fog. Objects that are less than
  13560. * `near` units from the active camera won't be affected by fog.
  13561. *
  13562. * @type {number}
  13563. * @default 1
  13564. */
  13565. this.near = near;
  13566. /**
  13567. * The maximum distance at which fog stops being calculated and applied.
  13568. * Objects that are more than `far` units away from the active camera won't
  13569. * be affected by fog.
  13570. *
  13571. * @type {number}
  13572. * @default 1000
  13573. */
  13574. this.far = far;
  13575. }
  13576. /**
  13577. * Returns a new fog with copied values from this instance.
  13578. *
  13579. * @return {Fog} A clone of this instance.
  13580. */
  13581. clone() {
  13582. return new Fog( this.color, this.near, this.far );
  13583. }
  13584. /**
  13585. * Serializes the fog into JSON.
  13586. *
  13587. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  13588. * @return {Object} A JSON object representing the serialized fog
  13589. */
  13590. toJSON( /* meta */ ) {
  13591. return {
  13592. type: 'Fog',
  13593. name: this.name,
  13594. color: this.color.getHex(),
  13595. near: this.near,
  13596. far: this.far
  13597. };
  13598. }
  13599. }
  13600. /**
  13601. * Scenes allow you to set up what is to be rendered and where by three.js.
  13602. * This is where you place 3D objects like meshes, lines or lights.
  13603. *
  13604. * @augments Object3D
  13605. */
  13606. class Scene extends Object3D {
  13607. /**
  13608. * Constructs a new scene.
  13609. */
  13610. constructor() {
  13611. super();
  13612. /**
  13613. * This flag can be used for type testing.
  13614. *
  13615. * @type {boolean}
  13616. * @readonly
  13617. * @default true
  13618. */
  13619. this.isScene = true;
  13620. this.type = 'Scene';
  13621. /**
  13622. * Defines the background of the scene. Valid inputs are:
  13623. *
  13624. * - A color for defining a uniform colored background.
  13625. * - A texture for defining a (flat) textured background.
  13626. * - Cube textures or equirectangular textures for defining a skybox.
  13627. *
  13628. * @type {?(Color|Texture)}
  13629. * @default null
  13630. */
  13631. this.background = null;
  13632. /**
  13633. * Sets the environment map for all physical materials in the scene. However,
  13634. * it's not possible to overwrite an existing texture assigned to the `envMap`
  13635. * material property.
  13636. *
  13637. * @type {?Texture}
  13638. * @default null
  13639. */
  13640. this.environment = null;
  13641. /**
  13642. * A fog instance defining the type of fog that affects everything
  13643. * rendered in the scene.
  13644. *
  13645. * @type {?(Fog|FogExp2)}
  13646. * @default null
  13647. */
  13648. this.fog = null;
  13649. /**
  13650. * Sets the blurriness of the background. Only influences environment maps
  13651. * assigned to {@link Scene#background}. Valid input is a float between `0`
  13652. * and `1`.
  13653. *
  13654. * @type {number}
  13655. * @default 0
  13656. */
  13657. this.backgroundBlurriness = 0;
  13658. /**
  13659. * Attenuates the color of the background. Only applies to background textures.
  13660. *
  13661. * @type {number}
  13662. * @default 1
  13663. */
  13664. this.backgroundIntensity = 1;
  13665. /**
  13666. * The rotation of the background in radians. Only influences environment maps
  13667. * assigned to {@link Scene#background}.
  13668. *
  13669. * @type {Euler}
  13670. * @default (0,0,0)
  13671. */
  13672. this.backgroundRotation = new Euler();
  13673. /**
  13674. * Attenuates the color of the environment. Only influences environment maps
  13675. * assigned to {@link Scene#environment}.
  13676. *
  13677. * @type {number}
  13678. * @default 1
  13679. */
  13680. this.environmentIntensity = 1;
  13681. /**
  13682. * The rotation of the environment map in radians. Only influences physical materials
  13683. * in the scene when {@link Scene#environment} is used.
  13684. *
  13685. * @type {Euler}
  13686. * @default (0,0,0)
  13687. */
  13688. this.environmentRotation = new Euler();
  13689. /**
  13690. * Forces everything in the scene to be rendered with the defined material.
  13691. *
  13692. * @type {?Material}
  13693. * @default null
  13694. */
  13695. this.overrideMaterial = null;
  13696. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  13697. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  13698. }
  13699. }
  13700. copy( source, recursive ) {
  13701. super.copy( source, recursive );
  13702. if ( source.background !== null ) this.background = source.background.clone();
  13703. if ( source.environment !== null ) this.environment = source.environment.clone();
  13704. if ( source.fog !== null ) this.fog = source.fog.clone();
  13705. this.backgroundBlurriness = source.backgroundBlurriness;
  13706. this.backgroundIntensity = source.backgroundIntensity;
  13707. this.backgroundRotation.copy( source.backgroundRotation );
  13708. this.environmentIntensity = source.environmentIntensity;
  13709. this.environmentRotation.copy( source.environmentRotation );
  13710. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13711. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13712. return this;
  13713. }
  13714. toJSON( meta ) {
  13715. const data = super.toJSON( meta );
  13716. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13717. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  13718. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  13719. data.object.backgroundRotation = this.backgroundRotation.toArray();
  13720. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  13721. data.object.environmentRotation = this.environmentRotation.toArray();
  13722. return data;
  13723. }
  13724. }
  13725. class InterleavedBuffer {
  13726. constructor( array, stride ) {
  13727. this.isInterleavedBuffer = true;
  13728. this.array = array;
  13729. this.stride = stride;
  13730. this.count = array !== undefined ? array.length / stride : 0;
  13731. this.usage = StaticDrawUsage;
  13732. this.updateRanges = [];
  13733. this.version = 0;
  13734. this.uuid = generateUUID();
  13735. }
  13736. onUploadCallback() {}
  13737. set needsUpdate( value ) {
  13738. if ( value === true ) this.version ++;
  13739. }
  13740. setUsage( value ) {
  13741. this.usage = value;
  13742. return this;
  13743. }
  13744. addUpdateRange( start, count ) {
  13745. this.updateRanges.push( { start, count } );
  13746. }
  13747. clearUpdateRanges() {
  13748. this.updateRanges.length = 0;
  13749. }
  13750. copy( source ) {
  13751. this.array = new source.array.constructor( source.array );
  13752. this.count = source.count;
  13753. this.stride = source.stride;
  13754. this.usage = source.usage;
  13755. return this;
  13756. }
  13757. copyAt( index1, attribute, index2 ) {
  13758. index1 *= this.stride;
  13759. index2 *= attribute.stride;
  13760. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  13761. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13762. }
  13763. return this;
  13764. }
  13765. set( value, offset = 0 ) {
  13766. this.array.set( value, offset );
  13767. return this;
  13768. }
  13769. clone( data ) {
  13770. if ( data.arrayBuffers === undefined ) {
  13771. data.arrayBuffers = {};
  13772. }
  13773. if ( this.array.buffer._uuid === undefined ) {
  13774. this.array.buffer._uuid = generateUUID();
  13775. }
  13776. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  13777. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  13778. }
  13779. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  13780. const ib = new this.constructor( array, this.stride );
  13781. ib.setUsage( this.usage );
  13782. return ib;
  13783. }
  13784. onUpload( callback ) {
  13785. this.onUploadCallback = callback;
  13786. return this;
  13787. }
  13788. toJSON( data ) {
  13789. if ( data.arrayBuffers === undefined ) {
  13790. data.arrayBuffers = {};
  13791. }
  13792. // generate UUID for array buffer if necessary
  13793. if ( this.array.buffer._uuid === undefined ) {
  13794. this.array.buffer._uuid = generateUUID();
  13795. }
  13796. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  13797. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  13798. }
  13799. //
  13800. return {
  13801. uuid: this.uuid,
  13802. buffer: this.array.buffer._uuid,
  13803. type: this.array.constructor.name,
  13804. stride: this.stride
  13805. };
  13806. }
  13807. }
  13808. const _vector$7 = /*@__PURE__*/ new Vector3();
  13809. class InterleavedBufferAttribute {
  13810. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  13811. this.isInterleavedBufferAttribute = true;
  13812. this.name = '';
  13813. this.data = interleavedBuffer;
  13814. this.itemSize = itemSize;
  13815. this.offset = offset;
  13816. this.normalized = normalized;
  13817. }
  13818. get count() {
  13819. return this.data.count;
  13820. }
  13821. get array() {
  13822. return this.data.array;
  13823. }
  13824. set needsUpdate( value ) {
  13825. this.data.needsUpdate = value;
  13826. }
  13827. applyMatrix4( m ) {
  13828. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  13829. _vector$7.fromBufferAttribute( this, i );
  13830. _vector$7.applyMatrix4( m );
  13831. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  13832. }
  13833. return this;
  13834. }
  13835. applyNormalMatrix( m ) {
  13836. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13837. _vector$7.fromBufferAttribute( this, i );
  13838. _vector$7.applyNormalMatrix( m );
  13839. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  13840. }
  13841. return this;
  13842. }
  13843. transformDirection( m ) {
  13844. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13845. _vector$7.fromBufferAttribute( this, i );
  13846. _vector$7.transformDirection( m );
  13847. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  13848. }
  13849. return this;
  13850. }
  13851. getComponent( index, component ) {
  13852. let value = this.array[ index * this.data.stride + this.offset + component ];
  13853. if ( this.normalized ) value = denormalize( value, this.array );
  13854. return value;
  13855. }
  13856. setComponent( index, component, value ) {
  13857. if ( this.normalized ) value = normalize( value, this.array );
  13858. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  13859. return this;
  13860. }
  13861. setX( index, x ) {
  13862. if ( this.normalized ) x = normalize( x, this.array );
  13863. this.data.array[ index * this.data.stride + this.offset ] = x;
  13864. return this;
  13865. }
  13866. setY( index, y ) {
  13867. if ( this.normalized ) y = normalize( y, this.array );
  13868. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  13869. return this;
  13870. }
  13871. setZ( index, z ) {
  13872. if ( this.normalized ) z = normalize( z, this.array );
  13873. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  13874. return this;
  13875. }
  13876. setW( index, w ) {
  13877. if ( this.normalized ) w = normalize( w, this.array );
  13878. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  13879. return this;
  13880. }
  13881. getX( index ) {
  13882. let x = this.data.array[ index * this.data.stride + this.offset ];
  13883. if ( this.normalized ) x = denormalize( x, this.array );
  13884. return x;
  13885. }
  13886. getY( index ) {
  13887. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  13888. if ( this.normalized ) y = denormalize( y, this.array );
  13889. return y;
  13890. }
  13891. getZ( index ) {
  13892. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  13893. if ( this.normalized ) z = denormalize( z, this.array );
  13894. return z;
  13895. }
  13896. getW( index ) {
  13897. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  13898. if ( this.normalized ) w = denormalize( w, this.array );
  13899. return w;
  13900. }
  13901. setXY( index, x, y ) {
  13902. index = index * this.data.stride + this.offset;
  13903. if ( this.normalized ) {
  13904. x = normalize( x, this.array );
  13905. y = normalize( y, this.array );
  13906. }
  13907. this.data.array[ index + 0 ] = x;
  13908. this.data.array[ index + 1 ] = y;
  13909. return this;
  13910. }
  13911. setXYZ( index, x, y, z ) {
  13912. index = index * this.data.stride + this.offset;
  13913. if ( this.normalized ) {
  13914. x = normalize( x, this.array );
  13915. y = normalize( y, this.array );
  13916. z = normalize( z, this.array );
  13917. }
  13918. this.data.array[ index + 0 ] = x;
  13919. this.data.array[ index + 1 ] = y;
  13920. this.data.array[ index + 2 ] = z;
  13921. return this;
  13922. }
  13923. setXYZW( index, x, y, z, w ) {
  13924. index = index * this.data.stride + this.offset;
  13925. if ( this.normalized ) {
  13926. x = normalize( x, this.array );
  13927. y = normalize( y, this.array );
  13928. z = normalize( z, this.array );
  13929. w = normalize( w, this.array );
  13930. }
  13931. this.data.array[ index + 0 ] = x;
  13932. this.data.array[ index + 1 ] = y;
  13933. this.data.array[ index + 2 ] = z;
  13934. this.data.array[ index + 3 ] = w;
  13935. return this;
  13936. }
  13937. clone( data ) {
  13938. if ( data === undefined ) {
  13939. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  13940. const array = [];
  13941. for ( let i = 0; i < this.count; i ++ ) {
  13942. const index = i * this.data.stride + this.offset;
  13943. for ( let j = 0; j < this.itemSize; j ++ ) {
  13944. array.push( this.data.array[ index + j ] );
  13945. }
  13946. }
  13947. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  13948. } else {
  13949. if ( data.interleavedBuffers === undefined ) {
  13950. data.interleavedBuffers = {};
  13951. }
  13952. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  13953. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  13954. }
  13955. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  13956. }
  13957. }
  13958. toJSON( data ) {
  13959. if ( data === undefined ) {
  13960. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  13961. const array = [];
  13962. for ( let i = 0; i < this.count; i ++ ) {
  13963. const index = i * this.data.stride + this.offset;
  13964. for ( let j = 0; j < this.itemSize; j ++ ) {
  13965. array.push( this.data.array[ index + j ] );
  13966. }
  13967. }
  13968. // de-interleave data and save it as an ordinary buffer attribute for now
  13969. return {
  13970. itemSize: this.itemSize,
  13971. type: this.array.constructor.name,
  13972. array: array,
  13973. normalized: this.normalized
  13974. };
  13975. } else {
  13976. // save as true interleaved attribute
  13977. if ( data.interleavedBuffers === undefined ) {
  13978. data.interleavedBuffers = {};
  13979. }
  13980. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  13981. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  13982. }
  13983. return {
  13984. isInterleavedBufferAttribute: true,
  13985. itemSize: this.itemSize,
  13986. data: this.data.uuid,
  13987. offset: this.offset,
  13988. normalized: this.normalized
  13989. };
  13990. }
  13991. }
  13992. }
  13993. class SpriteMaterial extends Material {
  13994. constructor( parameters ) {
  13995. super();
  13996. this.isSpriteMaterial = true;
  13997. this.type = 'SpriteMaterial';
  13998. this.color = new Color( 0xffffff );
  13999. this.map = null;
  14000. this.alphaMap = null;
  14001. this.rotation = 0;
  14002. this.sizeAttenuation = true;
  14003. this.transparent = true;
  14004. this.fog = true;
  14005. this.setValues( parameters );
  14006. }
  14007. copy( source ) {
  14008. super.copy( source );
  14009. this.color.copy( source.color );
  14010. this.map = source.map;
  14011. this.alphaMap = source.alphaMap;
  14012. this.rotation = source.rotation;
  14013. this.sizeAttenuation = source.sizeAttenuation;
  14014. this.fog = source.fog;
  14015. return this;
  14016. }
  14017. }
  14018. let _geometry;
  14019. const _intersectPoint = /*@__PURE__*/ new Vector3();
  14020. const _worldScale = /*@__PURE__*/ new Vector3();
  14021. const _mvPosition = /*@__PURE__*/ new Vector3();
  14022. const _alignedPosition = /*@__PURE__*/ new Vector2();
  14023. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  14024. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  14025. const _vA = /*@__PURE__*/ new Vector3();
  14026. const _vB = /*@__PURE__*/ new Vector3();
  14027. const _vC = /*@__PURE__*/ new Vector3();
  14028. const _uvA = /*@__PURE__*/ new Vector2();
  14029. const _uvB = /*@__PURE__*/ new Vector2();
  14030. const _uvC = /*@__PURE__*/ new Vector2();
  14031. /**
  14032. * A sprite is a plane that always faces towards the camera, generally with a
  14033. * partially transparent texture applied.
  14034. *
  14035. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  14036. * have no effect.
  14037. *
  14038. * ```js
  14039. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  14040. * const material = new THREE.SpriteMaterial( { map: map } );
  14041. *
  14042. * const sprite = new THREE.Sprite( material );
  14043. * scene.add( sprite );
  14044. * ```
  14045. *
  14046. * @augments Object3D
  14047. */
  14048. class Sprite extends Object3D {
  14049. /**
  14050. * Constructs a new sprite.
  14051. *
  14052. * @param {SpriteMaterial} [material] - The sprite material.
  14053. */
  14054. constructor( material = new SpriteMaterial() ) {
  14055. super();
  14056. /**
  14057. * This flag can be used for type testing.
  14058. *
  14059. * @type {boolean}
  14060. * @readonly
  14061. * @default true
  14062. */
  14063. this.isSprite = true;
  14064. this.type = 'Sprite';
  14065. if ( _geometry === undefined ) {
  14066. _geometry = new BufferGeometry();
  14067. const float32Array = new Float32Array( [
  14068. -0.5, -0.5, 0, 0, 0,
  14069. 0.5, -0.5, 0, 1, 0,
  14070. 0.5, 0.5, 0, 1, 1,
  14071. -0.5, 0.5, 0, 0, 1
  14072. ] );
  14073. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  14074. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  14075. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  14076. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  14077. }
  14078. /**
  14079. * The sprite geometry.
  14080. *
  14081. * @type {BufferGeometry}
  14082. */
  14083. this.geometry = _geometry;
  14084. /**
  14085. * The sprite material.
  14086. *
  14087. * @type {SpriteMaterial}
  14088. */
  14089. this.material = material;
  14090. /**
  14091. * The sprite's anchor point, and the point around which the sprite rotates.
  14092. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  14093. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  14094. *
  14095. * @type {Vector2}
  14096. * @default (0.5,0.5)
  14097. */
  14098. this.center = new Vector2( 0.5, 0.5 );
  14099. }
  14100. /**
  14101. * Computes intersection points between a casted ray and this sprite.
  14102. *
  14103. * @param {Raycaster} raycaster - The raycaster.
  14104. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  14105. */
  14106. raycast( raycaster, intersects ) {
  14107. if ( raycaster.camera === null ) {
  14108. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  14109. }
  14110. _worldScale.setFromMatrixScale( this.matrixWorld );
  14111. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  14112. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  14113. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  14114. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  14115. _worldScale.multiplyScalar( - _mvPosition.z );
  14116. }
  14117. const rotation = this.material.rotation;
  14118. let sin, cos;
  14119. if ( rotation !== 0 ) {
  14120. cos = Math.cos( rotation );
  14121. sin = Math.sin( rotation );
  14122. }
  14123. const center = this.center;
  14124. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  14125. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  14126. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  14127. _uvA.set( 0, 0 );
  14128. _uvB.set( 1, 0 );
  14129. _uvC.set( 1, 1 );
  14130. // check first triangle
  14131. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  14132. if ( intersect === null ) {
  14133. // check second triangle
  14134. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  14135. _uvB.set( 0, 1 );
  14136. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  14137. if ( intersect === null ) {
  14138. return;
  14139. }
  14140. }
  14141. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  14142. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14143. intersects.push( {
  14144. distance: distance,
  14145. point: _intersectPoint.clone(),
  14146. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  14147. face: null,
  14148. object: this
  14149. } );
  14150. }
  14151. copy( source, recursive ) {
  14152. super.copy( source, recursive );
  14153. if ( source.center !== undefined ) this.center.copy( source.center );
  14154. this.material = source.material;
  14155. return this;
  14156. }
  14157. }
  14158. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  14159. // compute position in camera space
  14160. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  14161. // to check if rotation is not zero
  14162. if ( sin !== undefined ) {
  14163. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  14164. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  14165. } else {
  14166. _rotatedPosition.copy( _alignedPosition );
  14167. }
  14168. vertexPosition.copy( mvPosition );
  14169. vertexPosition.x += _rotatedPosition.x;
  14170. vertexPosition.y += _rotatedPosition.y;
  14171. // transform to world space
  14172. vertexPosition.applyMatrix4( _viewWorldMatrix );
  14173. }
  14174. const _v1$2 = /*@__PURE__*/ new Vector3();
  14175. const _v2$1 = /*@__PURE__*/ new Vector3();
  14176. /**
  14177. * A component for providing a basic Level of Detail (LOD) mechanism.
  14178. *
  14179. * Every LOD level is associated with an object, and rendering can be switched
  14180. * between them at the distances specified. Typically you would create, say,
  14181. * three meshes, one for far away (low detail), one for mid range (medium
  14182. * detail) and one for close up (high detail).
  14183. *
  14184. * ```js
  14185. * const lod = new THREE.LOD();
  14186. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  14187. *
  14188. * //Create spheres with 3 levels of detail and create new LOD levels for them
  14189. * for( let i = 0; i < 3; i++ ) {
  14190. *
  14191. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  14192. * const mesh = new THREE.Mesh( geometry, material );
  14193. * lod.addLevel( mesh, i * 75 );
  14194. *
  14195. * }
  14196. *
  14197. * scene.add( lod );
  14198. * ```
  14199. *
  14200. * @augments Object3D
  14201. */
  14202. class LOD extends Object3D {
  14203. /**
  14204. * Constructs a new LOD.
  14205. */
  14206. constructor() {
  14207. super();
  14208. /**
  14209. * This flag can be used for type testing.
  14210. *
  14211. * @type {boolean}
  14212. * @readonly
  14213. * @default true
  14214. */
  14215. this.isLOD = true;
  14216. /**
  14217. * The current LOD index.
  14218. *
  14219. * @private
  14220. * @type {number}
  14221. * @default 0
  14222. */
  14223. this._currentLevel = 0;
  14224. this.type = 'LOD';
  14225. Object.defineProperties( this, {
  14226. /**
  14227. * This array holds the LOD levels.
  14228. *
  14229. * @name LOD#levels
  14230. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  14231. */
  14232. levels: {
  14233. enumerable: true,
  14234. value: []
  14235. }
  14236. } );
  14237. /**
  14238. * Whether the LOD object is updated automatically by the renderer per frame
  14239. * or not. If set to `false`, you have to call {@link LOD#update} in the
  14240. * render loop by yourself.
  14241. *
  14242. * @type {boolean}
  14243. * @default true
  14244. */
  14245. this.autoUpdate = true;
  14246. }
  14247. copy( source ) {
  14248. super.copy( source, false );
  14249. const levels = source.levels;
  14250. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  14251. const level = levels[ i ];
  14252. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  14253. }
  14254. this.autoUpdate = source.autoUpdate;
  14255. return this;
  14256. }
  14257. /**
  14258. * Adds a mesh that will display at a certain distance and greater. Typically
  14259. * the further away the distance, the lower the detail on the mesh.
  14260. *
  14261. * @param {Object3D} object - The 3D object to display at this level.
  14262. * @param {number} [distance=0] - The distance at which to display this level of detail.
  14263. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  14264. * @return {LOD} A reference to this instance.
  14265. */
  14266. addLevel( object, distance = 0, hysteresis = 0 ) {
  14267. distance = Math.abs( distance );
  14268. const levels = this.levels;
  14269. let l;
  14270. for ( l = 0; l < levels.length; l ++ ) {
  14271. if ( distance < levels[ l ].distance ) {
  14272. break;
  14273. }
  14274. }
  14275. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  14276. this.add( object );
  14277. return this;
  14278. }
  14279. /**
  14280. * Removes an existing level, based on the distance from the camera.
  14281. * Returns `true` when the level has been removed. Otherwise `false`.
  14282. *
  14283. * @param {number} distance - Distance of the level to remove.
  14284. * @return {boolean} Whether the level has been removed or not.
  14285. */
  14286. removeLevel( distance ) {
  14287. const levels = this.levels;
  14288. for ( let i = 0; i < levels.length; i ++ ) {
  14289. if ( levels[ i ].distance === distance ) {
  14290. const removedElements = levels.splice( i, 1 );
  14291. this.remove( removedElements[ 0 ].object );
  14292. return true;
  14293. }
  14294. }
  14295. return false;
  14296. }
  14297. /**
  14298. * Returns the currently active LOD level index.
  14299. *
  14300. * @return {number} The current active LOD level index.
  14301. */
  14302. getCurrentLevel() {
  14303. return this._currentLevel;
  14304. }
  14305. /**
  14306. * Returns a reference to the first 3D object that is greater than
  14307. * the given distance.
  14308. *
  14309. * @param {number} distance - The LOD distance.
  14310. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  14311. */
  14312. getObjectForDistance( distance ) {
  14313. const levels = this.levels;
  14314. if ( levels.length > 0 ) {
  14315. let i, l;
  14316. for ( i = 1, l = levels.length; i < l; i ++ ) {
  14317. let levelDistance = levels[ i ].distance;
  14318. if ( levels[ i ].object.visible ) {
  14319. levelDistance -= levelDistance * levels[ i ].hysteresis;
  14320. }
  14321. if ( distance < levelDistance ) {
  14322. break;
  14323. }
  14324. }
  14325. return levels[ i - 1 ].object;
  14326. }
  14327. return null;
  14328. }
  14329. /**
  14330. * Computes intersection points between a casted ray and this LOD.
  14331. *
  14332. * @param {Raycaster} raycaster - The raycaster.
  14333. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  14334. */
  14335. raycast( raycaster, intersects ) {
  14336. const levels = this.levels;
  14337. if ( levels.length > 0 ) {
  14338. _v1$2.setFromMatrixPosition( this.matrixWorld );
  14339. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  14340. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  14341. }
  14342. }
  14343. /**
  14344. * Updates the LOD by computing which LOD level should be visible according
  14345. * to the current distance of the given camera.
  14346. *
  14347. * @param {Camera} camera - The camera the scene is renderd with.
  14348. */
  14349. update( camera ) {
  14350. const levels = this.levels;
  14351. if ( levels.length > 1 ) {
  14352. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  14353. _v2$1.setFromMatrixPosition( this.matrixWorld );
  14354. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  14355. levels[ 0 ].object.visible = true;
  14356. let i, l;
  14357. for ( i = 1, l = levels.length; i < l; i ++ ) {
  14358. let levelDistance = levels[ i ].distance;
  14359. if ( levels[ i ].object.visible ) {
  14360. levelDistance -= levelDistance * levels[ i ].hysteresis;
  14361. }
  14362. if ( distance >= levelDistance ) {
  14363. levels[ i - 1 ].object.visible = false;
  14364. levels[ i ].object.visible = true;
  14365. } else {
  14366. break;
  14367. }
  14368. }
  14369. this._currentLevel = i - 1;
  14370. for ( ; i < l; i ++ ) {
  14371. levels[ i ].object.visible = false;
  14372. }
  14373. }
  14374. }
  14375. toJSON( meta ) {
  14376. const data = super.toJSON( meta );
  14377. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  14378. data.object.levels = [];
  14379. const levels = this.levels;
  14380. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  14381. const level = levels[ i ];
  14382. data.object.levels.push( {
  14383. object: level.object.uuid,
  14384. distance: level.distance,
  14385. hysteresis: level.hysteresis
  14386. } );
  14387. }
  14388. return data;
  14389. }
  14390. }
  14391. const _basePosition = /*@__PURE__*/ new Vector3();
  14392. const _skinIndex = /*@__PURE__*/ new Vector4();
  14393. const _skinWeight = /*@__PURE__*/ new Vector4();
  14394. const _vector3 = /*@__PURE__*/ new Vector3();
  14395. const _matrix4 = /*@__PURE__*/ new Matrix4();
  14396. const _vertex = /*@__PURE__*/ new Vector3();
  14397. const _sphere$5 = /*@__PURE__*/ new Sphere();
  14398. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  14399. const _ray$2 = /*@__PURE__*/ new Ray();
  14400. /**
  14401. * A mesh that has a {@link Skeleton} that can then be used to animate the
  14402. * vertices of the geometry with skinning/skeleton animation.
  14403. *
  14404. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  14405. * as buffer attributes in its geometry. These attribute define which bones affect a single
  14406. * vertex to a certain extend.
  14407. *
  14408. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  14409. * or {@link FBXLoader } import respective models.
  14410. *
  14411. * @augments Mesh
  14412. */
  14413. class SkinnedMesh extends Mesh {
  14414. /**
  14415. * Constructs a new skinned mesh.
  14416. *
  14417. * @param {BufferGeometry} [geometry] - The mesh geometry.
  14418. * @param {Material|Array<Material>} [material] - The mesh material.
  14419. */
  14420. constructor( geometry, material ) {
  14421. super( geometry, material );
  14422. /**
  14423. * This flag can be used for type testing.
  14424. *
  14425. * @type {boolean}
  14426. * @readonly
  14427. * @default true
  14428. */
  14429. this.isSkinnedMesh = true;
  14430. this.type = 'SkinnedMesh';
  14431. /**
  14432. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  14433. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  14434. * across multiple skinned meshes.
  14435. *
  14436. * @type {(AttachedBindMode|DetachedBindMode)}
  14437. * @default AttachedBindMode
  14438. */
  14439. this.bindMode = AttachedBindMode;
  14440. /**
  14441. * The base matrix that is used for the bound bone transforms.
  14442. *
  14443. * @type {Matrix4}
  14444. */
  14445. this.bindMatrix = new Matrix4();
  14446. /**
  14447. * The base matrix that is used for resetting the bound bone transforms.
  14448. *
  14449. * @type {Matrix4}
  14450. */
  14451. this.bindMatrixInverse = new Matrix4();
  14452. /**
  14453. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  14454. *
  14455. * @type {?Box3}
  14456. * @default null
  14457. */
  14458. this.boundingBox = null;
  14459. /**
  14460. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  14461. *
  14462. * @type {?Sphere}
  14463. * @default null
  14464. */
  14465. this.boundingSphere = null;
  14466. }
  14467. /**
  14468. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  14469. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  14470. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  14471. * the current animation state.
  14472. */
  14473. computeBoundingBox() {
  14474. const geometry = this.geometry;
  14475. if ( this.boundingBox === null ) {
  14476. this.boundingBox = new Box3();
  14477. }
  14478. this.boundingBox.makeEmpty();
  14479. const positionAttribute = geometry.getAttribute( 'position' );
  14480. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14481. this.getVertexPosition( i, _vertex );
  14482. this.boundingBox.expandByPoint( _vertex );
  14483. }
  14484. }
  14485. /**
  14486. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  14487. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  14488. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  14489. * per frame in order to reflect the current animation state.
  14490. */
  14491. computeBoundingSphere() {
  14492. const geometry = this.geometry;
  14493. if ( this.boundingSphere === null ) {
  14494. this.boundingSphere = new Sphere();
  14495. }
  14496. this.boundingSphere.makeEmpty();
  14497. const positionAttribute = geometry.getAttribute( 'position' );
  14498. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14499. this.getVertexPosition( i, _vertex );
  14500. this.boundingSphere.expandByPoint( _vertex );
  14501. }
  14502. }
  14503. copy( source, recursive ) {
  14504. super.copy( source, recursive );
  14505. this.bindMode = source.bindMode;
  14506. this.bindMatrix.copy( source.bindMatrix );
  14507. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  14508. this.skeleton = source.skeleton;
  14509. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  14510. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  14511. return this;
  14512. }
  14513. raycast( raycaster, intersects ) {
  14514. const material = this.material;
  14515. const matrixWorld = this.matrixWorld;
  14516. if ( material === undefined ) return;
  14517. // test with bounding sphere in world space
  14518. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  14519. _sphere$5.copy( this.boundingSphere );
  14520. _sphere$5.applyMatrix4( matrixWorld );
  14521. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  14522. // convert ray to local space of skinned mesh
  14523. _inverseMatrix$2.copy( matrixWorld ).invert();
  14524. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  14525. // test with bounding box in local space
  14526. if ( this.boundingBox !== null ) {
  14527. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  14528. }
  14529. // test for intersections with geometry
  14530. this._computeIntersections( raycaster, intersects, _ray$2 );
  14531. }
  14532. getVertexPosition( index, target ) {
  14533. super.getVertexPosition( index, target );
  14534. this.applyBoneTransform( index, target );
  14535. return target;
  14536. }
  14537. /**
  14538. * Binds the given skeleton to the skinned mesh.
  14539. *
  14540. * @param {Skeleton} skeleton - The skeleton to bind.
  14541. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  14542. * the skinned mesh's world matrix will be used instead.
  14543. */
  14544. bind( skeleton, bindMatrix ) {
  14545. this.skeleton = skeleton;
  14546. if ( bindMatrix === undefined ) {
  14547. this.updateMatrixWorld( true );
  14548. this.skeleton.calculateInverses();
  14549. bindMatrix = this.matrixWorld;
  14550. }
  14551. this.bindMatrix.copy( bindMatrix );
  14552. this.bindMatrixInverse.copy( bindMatrix ).invert();
  14553. }
  14554. /**
  14555. * This method sets the skinned mesh in the rest pose).
  14556. */
  14557. pose() {
  14558. this.skeleton.pose();
  14559. }
  14560. /**
  14561. * Normalizes the skin weights which are defined as a buffer attribute
  14562. * in the skinned mesh's geometry.
  14563. */
  14564. normalizeSkinWeights() {
  14565. const vector = new Vector4();
  14566. const skinWeight = this.geometry.attributes.skinWeight;
  14567. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  14568. vector.fromBufferAttribute( skinWeight, i );
  14569. const scale = 1.0 / vector.manhattanLength();
  14570. if ( scale !== Infinity ) {
  14571. vector.multiplyScalar( scale );
  14572. } else {
  14573. vector.set( 1, 0, 0, 0 ); // do something reasonable
  14574. }
  14575. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  14576. }
  14577. }
  14578. updateMatrixWorld( force ) {
  14579. super.updateMatrixWorld( force );
  14580. if ( this.bindMode === AttachedBindMode ) {
  14581. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  14582. } else if ( this.bindMode === DetachedBindMode ) {
  14583. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  14584. } else {
  14585. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  14586. }
  14587. }
  14588. /**
  14589. * Applies the bone transform associated with the given index to the given
  14590. * vertex position. Returns the updated vector.
  14591. *
  14592. * @param {number} index - The vertex index.
  14593. * @param {Vector3} target - The target object that is used to store the method's result.
  14594. * the skinned mesh's world matrix will be used instead.
  14595. * @return {Vector3} The updated vertex position.
  14596. */
  14597. applyBoneTransform( index, target ) {
  14598. const skeleton = this.skeleton;
  14599. const geometry = this.geometry;
  14600. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  14601. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  14602. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  14603. target.set( 0, 0, 0 );
  14604. for ( let i = 0; i < 4; i ++ ) {
  14605. const weight = _skinWeight.getComponent( i );
  14606. if ( weight !== 0 ) {
  14607. const boneIndex = _skinIndex.getComponent( i );
  14608. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  14609. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  14610. }
  14611. }
  14612. return target.applyMatrix4( this.bindMatrixInverse );
  14613. }
  14614. }
  14615. /**
  14616. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  14617. * the {@link SkinnedMesh}.
  14618. *
  14619. * ```js
  14620. * const root = new THREE.Bone();
  14621. * const child = new THREE.Bone();
  14622. *
  14623. * root.add( child );
  14624. * child.position.y = 5;
  14625. * ```
  14626. *
  14627. * @augments Object3D
  14628. */
  14629. class Bone extends Object3D {
  14630. /**
  14631. * Constructs a new bone.
  14632. */
  14633. constructor() {
  14634. super();
  14635. /**
  14636. * This flag can be used for type testing.
  14637. *
  14638. * @type {boolean}
  14639. * @readonly
  14640. * @default true
  14641. */
  14642. this.isBone = true;
  14643. this.type = 'Bone';
  14644. }
  14645. }
  14646. class DataTexture extends Texture {
  14647. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  14648. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  14649. this.isDataTexture = true;
  14650. this.image = { data: data, width: width, height: height };
  14651. this.generateMipmaps = false;
  14652. this.flipY = false;
  14653. this.unpackAlignment = 1;
  14654. }
  14655. }
  14656. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  14657. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  14658. /**
  14659. * Class for representing the armatures in `three.js`. The skeleton
  14660. * is defined by a hierarchy of bones.
  14661. *
  14662. * ```js
  14663. * const bones = [];
  14664. *
  14665. * const shoulder = new THREE.Bone();
  14666. * const elbow = new THREE.Bone();
  14667. * const hand = new THREE.Bone();
  14668. *
  14669. * shoulder.add( elbow );
  14670. * elbow.add( hand );
  14671. *
  14672. * bones.push( shoulder , elbow, hand);
  14673. *
  14674. * shoulder.position.y = -5;
  14675. * elbow.position.y = 0;
  14676. * hand.position.y = 5;
  14677. *
  14678. * const armSkeleton = new THREE.Skeleton( bones );
  14679. * ```
  14680. */
  14681. class Skeleton {
  14682. /**
  14683. * Constructs a new skeleton.
  14684. *
  14685. * @param {Array<Bone>} [bones] - An array of bones.
  14686. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  14687. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  14688. */
  14689. constructor( bones = [], boneInverses = [] ) {
  14690. this.uuid = generateUUID();
  14691. /**
  14692. * An array of bones defining the skeleton.
  14693. *
  14694. * @type {Array<Bone>}
  14695. */
  14696. this.bones = bones.slice( 0 );
  14697. /**
  14698. * An array of bone inverse matrices.
  14699. *
  14700. * @type {Array<Matrix4>}
  14701. */
  14702. this.boneInverses = boneInverses;
  14703. /**
  14704. * An array buffer holding the bone data.
  14705. * Input data for {@link Skeleton#boneTexture}.
  14706. *
  14707. * @type {?Float32Array}
  14708. * @default null
  14709. */
  14710. this.boneMatrices = null;
  14711. /**
  14712. * A texture holding the bone data for use
  14713. * in the vertex shader.
  14714. *
  14715. * @type {?DataTexture}
  14716. * @default null
  14717. */
  14718. this.boneTexture = null;
  14719. this.init();
  14720. }
  14721. /**
  14722. * Initializes the skeleton. This method gets automatically called by the constructor
  14723. * but depending on how the skeleton is created it might be necessary to call this method
  14724. * manually.
  14725. */
  14726. init() {
  14727. const bones = this.bones;
  14728. const boneInverses = this.boneInverses;
  14729. this.boneMatrices = new Float32Array( bones.length * 16 );
  14730. // calculate inverse bone matrices if necessary
  14731. if ( boneInverses.length === 0 ) {
  14732. this.calculateInverses();
  14733. } else {
  14734. // handle special case
  14735. if ( bones.length !== boneInverses.length ) {
  14736. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  14737. this.boneInverses = [];
  14738. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14739. this.boneInverses.push( new Matrix4() );
  14740. }
  14741. }
  14742. }
  14743. }
  14744. /**
  14745. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  14746. * and fills it with new matrices.
  14747. */
  14748. calculateInverses() {
  14749. this.boneInverses.length = 0;
  14750. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14751. const inverse = new Matrix4();
  14752. if ( this.bones[ i ] ) {
  14753. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  14754. }
  14755. this.boneInverses.push( inverse );
  14756. }
  14757. }
  14758. /**
  14759. * Resets the skeleton to the base pose.
  14760. */
  14761. pose() {
  14762. // recover the bind-time world matrices
  14763. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14764. const bone = this.bones[ i ];
  14765. if ( bone ) {
  14766. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  14767. }
  14768. }
  14769. // compute the local matrices, positions, rotations and scales
  14770. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14771. const bone = this.bones[ i ];
  14772. if ( bone ) {
  14773. if ( bone.parent && bone.parent.isBone ) {
  14774. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  14775. bone.matrix.multiply( bone.matrixWorld );
  14776. } else {
  14777. bone.matrix.copy( bone.matrixWorld );
  14778. }
  14779. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  14780. }
  14781. }
  14782. }
  14783. /**
  14784. * Resets the skeleton to the base pose.
  14785. */
  14786. update() {
  14787. const bones = this.bones;
  14788. const boneInverses = this.boneInverses;
  14789. const boneMatrices = this.boneMatrices;
  14790. const boneTexture = this.boneTexture;
  14791. // flatten bone matrices to array
  14792. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  14793. // compute the offset between the current and the original transform
  14794. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  14795. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  14796. _offsetMatrix.toArray( boneMatrices, i * 16 );
  14797. }
  14798. if ( boneTexture !== null ) {
  14799. boneTexture.needsUpdate = true;
  14800. }
  14801. }
  14802. /**
  14803. * Returns a new skeleton with copied values from this instance.
  14804. *
  14805. * @return {Skeleton} A clone of this instance.
  14806. */
  14807. clone() {
  14808. return new Skeleton( this.bones, this.boneInverses );
  14809. }
  14810. /**
  14811. * Computes a data texture for passing bone data to the vertex shader.
  14812. *
  14813. * @return {Skeleton} A reference of this instance.
  14814. */
  14815. computeBoneTexture() {
  14816. // layout (1 matrix = 4 pixels)
  14817. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  14818. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  14819. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  14820. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  14821. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  14822. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  14823. size = Math.ceil( size / 4 ) * 4;
  14824. size = Math.max( size, 4 );
  14825. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  14826. boneMatrices.set( this.boneMatrices ); // copy current values
  14827. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  14828. boneTexture.needsUpdate = true;
  14829. this.boneMatrices = boneMatrices;
  14830. this.boneTexture = boneTexture;
  14831. return this;
  14832. }
  14833. /**
  14834. * Searches through the skeleton's bone array and returns the first with a
  14835. * matching name.
  14836. *
  14837. * @param {string} name - The name of the bone.
  14838. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  14839. */
  14840. getBoneByName( name ) {
  14841. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14842. const bone = this.bones[ i ];
  14843. if ( bone.name === name ) {
  14844. return bone;
  14845. }
  14846. }
  14847. return undefined;
  14848. }
  14849. /**
  14850. * Frees the GPU-related resources allocated by this instance. Call this
  14851. * method whenever this instance is no longer used in your app.
  14852. */
  14853. dispose( ) {
  14854. if ( this.boneTexture !== null ) {
  14855. this.boneTexture.dispose();
  14856. this.boneTexture = null;
  14857. }
  14858. }
  14859. /**
  14860. * Setups the skeleton by the given JSON and bones.
  14861. *
  14862. * @param {Object} json - The skeleton as serialized JSON.
  14863. * @param {Array<Bone>} bones - An array of bones.
  14864. * @return {Skeleton} A reference of this instance.
  14865. */
  14866. fromJSON( json, bones ) {
  14867. this.uuid = json.uuid;
  14868. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  14869. const uuid = json.bones[ i ];
  14870. let bone = bones[ uuid ];
  14871. if ( bone === undefined ) {
  14872. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  14873. bone = new Bone();
  14874. }
  14875. this.bones.push( bone );
  14876. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  14877. }
  14878. this.init();
  14879. return this;
  14880. }
  14881. /**
  14882. * Serializes the skeleton into JSON.
  14883. *
  14884. * @return {Object} A JSON object representing the serialized skeleton.
  14885. * @see {@link ObjectLoader#parse}
  14886. */
  14887. toJSON() {
  14888. const data = {
  14889. metadata: {
  14890. version: 4.6,
  14891. type: 'Skeleton',
  14892. generator: 'Skeleton.toJSON'
  14893. },
  14894. bones: [],
  14895. boneInverses: []
  14896. };
  14897. data.uuid = this.uuid;
  14898. const bones = this.bones;
  14899. const boneInverses = this.boneInverses;
  14900. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  14901. const bone = bones[ i ];
  14902. data.bones.push( bone.uuid );
  14903. const boneInverse = boneInverses[ i ];
  14904. data.boneInverses.push( boneInverse.toArray() );
  14905. }
  14906. return data;
  14907. }
  14908. }
  14909. class InstancedBufferAttribute extends BufferAttribute {
  14910. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  14911. super( array, itemSize, normalized );
  14912. this.isInstancedBufferAttribute = true;
  14913. this.meshPerAttribute = meshPerAttribute;
  14914. }
  14915. copy( source ) {
  14916. super.copy( source );
  14917. this.meshPerAttribute = source.meshPerAttribute;
  14918. return this;
  14919. }
  14920. toJSON() {
  14921. const data = super.toJSON();
  14922. data.meshPerAttribute = this.meshPerAttribute;
  14923. data.isInstancedBufferAttribute = true;
  14924. return data;
  14925. }
  14926. }
  14927. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  14928. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  14929. const _instanceIntersects = [];
  14930. const _box3 = /*@__PURE__*/ new Box3();
  14931. const _identity = /*@__PURE__*/ new Matrix4();
  14932. const _mesh$1 = /*@__PURE__*/ new Mesh();
  14933. const _sphere$4 = /*@__PURE__*/ new Sphere();
  14934. /**
  14935. * A special version of a mesh with instanced rendering support. Use
  14936. * this class if you have to render a large number of objects with the same
  14937. * geometry and material(s) but with different world transformations. The usage
  14938. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  14939. * improve the overall rendering performance in your application.
  14940. *
  14941. * @augments Mesh
  14942. */
  14943. class InstancedMesh extends Mesh {
  14944. /**
  14945. * Constructs a new instanced mesh.
  14946. *
  14947. * @param {BufferGeometry} [geometry] - The mesh geometry.
  14948. * @param {Material|Array<Material>} [material] - The mesh material.
  14949. * @param {number} count - The number of instances.
  14950. */
  14951. constructor( geometry, material, count ) {
  14952. super( geometry, material );
  14953. /**
  14954. * This flag can be used for type testing.
  14955. *
  14956. * @type {boolean}
  14957. * @readonly
  14958. * @default true
  14959. */
  14960. this.isInstancedMesh = true;
  14961. /**
  14962. * Represents the local transformation of all instances. You have to set its
  14963. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  14964. * via {@link InstancedMesh#setMatrixAt}.
  14965. *
  14966. * @type {InstancedBufferAttribute}
  14967. */
  14968. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  14969. /**
  14970. * Represents the color of all instances. You have to set its
  14971. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  14972. * via {@link InstancedMesh#setColorAt}.
  14973. *
  14974. * @type {?InstancedBufferAttribute}
  14975. * @default null
  14976. */
  14977. this.instanceColor = null;
  14978. /**
  14979. * Represents the morph target weights of all instances. You have to set its
  14980. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  14981. * via {@link InstancedMesh#setMorphAt}.
  14982. *
  14983. * @type {?InstancedBufferAttribute}
  14984. * @default null
  14985. */
  14986. this.morphTexture = null;
  14987. /**
  14988. * The number of instances.
  14989. *
  14990. * @type {number}
  14991. */
  14992. this.count = count;
  14993. /**
  14994. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  14995. *
  14996. * @type {?Box3}
  14997. * @default null
  14998. */
  14999. this.boundingBox = null;
  15000. /**
  15001. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  15002. *
  15003. * @type {?Sphere}
  15004. * @default null
  15005. */
  15006. this.boundingSphere = null;
  15007. for ( let i = 0; i < count; i ++ ) {
  15008. this.setMatrixAt( i, _identity );
  15009. }
  15010. }
  15011. /**
  15012. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  15013. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  15014. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  15015. */
  15016. computeBoundingBox() {
  15017. const geometry = this.geometry;
  15018. const count = this.count;
  15019. if ( this.boundingBox === null ) {
  15020. this.boundingBox = new Box3();
  15021. }
  15022. if ( geometry.boundingBox === null ) {
  15023. geometry.computeBoundingBox();
  15024. }
  15025. this.boundingBox.makeEmpty();
  15026. for ( let i = 0; i < count; i ++ ) {
  15027. this.getMatrixAt( i, _instanceLocalMatrix );
  15028. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  15029. this.boundingBox.union( _box3 );
  15030. }
  15031. }
  15032. /**
  15033. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  15034. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  15035. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  15036. */
  15037. computeBoundingSphere() {
  15038. const geometry = this.geometry;
  15039. const count = this.count;
  15040. if ( this.boundingSphere === null ) {
  15041. this.boundingSphere = new Sphere();
  15042. }
  15043. if ( geometry.boundingSphere === null ) {
  15044. geometry.computeBoundingSphere();
  15045. }
  15046. this.boundingSphere.makeEmpty();
  15047. for ( let i = 0; i < count; i ++ ) {
  15048. this.getMatrixAt( i, _instanceLocalMatrix );
  15049. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  15050. this.boundingSphere.union( _sphere$4 );
  15051. }
  15052. }
  15053. copy( source, recursive ) {
  15054. super.copy( source, recursive );
  15055. this.instanceMatrix.copy( source.instanceMatrix );
  15056. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  15057. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  15058. this.count = source.count;
  15059. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  15060. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  15061. return this;
  15062. }
  15063. /**
  15064. * Gets the color of the defined instance.
  15065. *
  15066. * @param {number} index - The instance index.
  15067. * @param {Color} color - The target object that is used to store the method's result.
  15068. */
  15069. getColorAt( index, color ) {
  15070. color.fromArray( this.instanceColor.array, index * 3 );
  15071. }
  15072. /**
  15073. * Gets the local transformation matrix of the defined instance.
  15074. *
  15075. * @param {number} index - The instance index.
  15076. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  15077. */
  15078. getMatrixAt( index, matrix ) {
  15079. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  15080. }
  15081. /**
  15082. * Gets the morph target weights of the defined instance.
  15083. *
  15084. * @param {number} index - The instance index.
  15085. * @param {Mesh} object - The target object that is used to store the method's result.
  15086. */
  15087. getMorphAt( index, object ) {
  15088. const objectInfluences = object.morphTargetInfluences;
  15089. const array = this.morphTexture.source.data.data;
  15090. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  15091. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  15092. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  15093. objectInfluences[ i ] = array[ dataIndex + i ];
  15094. }
  15095. }
  15096. raycast( raycaster, intersects ) {
  15097. const matrixWorld = this.matrixWorld;
  15098. const raycastTimes = this.count;
  15099. _mesh$1.geometry = this.geometry;
  15100. _mesh$1.material = this.material;
  15101. if ( _mesh$1.material === undefined ) return;
  15102. // test with bounding sphere first
  15103. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  15104. _sphere$4.copy( this.boundingSphere );
  15105. _sphere$4.applyMatrix4( matrixWorld );
  15106. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  15107. // now test each instance
  15108. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  15109. // calculate the world matrix for each instance
  15110. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  15111. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  15112. // the mesh represents this single instance
  15113. _mesh$1.matrixWorld = _instanceWorldMatrix;
  15114. _mesh$1.raycast( raycaster, _instanceIntersects );
  15115. // process the result of raycast
  15116. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  15117. const intersect = _instanceIntersects[ i ];
  15118. intersect.instanceId = instanceId;
  15119. intersect.object = this;
  15120. intersects.push( intersect );
  15121. }
  15122. _instanceIntersects.length = 0;
  15123. }
  15124. }
  15125. /**
  15126. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  15127. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  15128. *
  15129. * @param {number} index - The instance index.
  15130. * @param {Color} color - The instance color.
  15131. */
  15132. setColorAt( index, color ) {
  15133. if ( this.instanceColor === null ) {
  15134. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  15135. }
  15136. color.toArray( this.instanceColor.array, index * 3 );
  15137. }
  15138. /**
  15139. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  15140. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  15141. *
  15142. * @param {number} index - The instance index.
  15143. * @param {Matrix4} matrix - The the local transformation.
  15144. */
  15145. setMatrixAt( index, matrix ) {
  15146. matrix.toArray( this.instanceMatrix.array, index * 16 );
  15147. }
  15148. /**
  15149. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  15150. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  15151. *
  15152. * @param {number} index - The instance index.
  15153. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  15154. * of a single instance.
  15155. */
  15156. setMorphAt( index, object ) {
  15157. const objectInfluences = object.morphTargetInfluences;
  15158. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  15159. if ( this.morphTexture === null ) {
  15160. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  15161. }
  15162. const array = this.morphTexture.source.data.data;
  15163. let morphInfluencesSum = 0;
  15164. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  15165. morphInfluencesSum += objectInfluences[ i ];
  15166. }
  15167. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  15168. const dataIndex = len * index;
  15169. array[ dataIndex ] = morphBaseInfluence;
  15170. array.set( objectInfluences, dataIndex + 1 );
  15171. }
  15172. updateMorphTargets() {
  15173. }
  15174. /**
  15175. * Frees the GPU-related resources allocated by this instance. Call this
  15176. * method whenever this instance is no longer used in your app.
  15177. */
  15178. dispose() {
  15179. this.dispatchEvent( { type: 'dispose' } );
  15180. if ( this.morphTexture !== null ) {
  15181. this.morphTexture.dispose();
  15182. this.morphTexture = null;
  15183. }
  15184. }
  15185. }
  15186. const _vector1 = /*@__PURE__*/ new Vector3();
  15187. const _vector2 = /*@__PURE__*/ new Vector3();
  15188. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  15189. /**
  15190. * A two dimensional surface that extends infinitely in 3D space, represented
  15191. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  15192. * by a unit length normal vector and a constant.
  15193. */
  15194. class Plane {
  15195. /**
  15196. * Constructs a new plane.
  15197. *
  15198. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  15199. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  15200. */
  15201. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  15202. /**
  15203. * This flag can be used for type testing.
  15204. *
  15205. * @type {boolean}
  15206. * @readonly
  15207. * @default true
  15208. */
  15209. this.isPlane = true;
  15210. /**
  15211. * A unit length vector defining the normal of the plane.
  15212. *
  15213. * @type {Vector3}
  15214. */
  15215. this.normal = normal;
  15216. /**
  15217. * The signed distance from the origin to the plane.
  15218. *
  15219. * @type {number}
  15220. * @default 0
  15221. */
  15222. this.constant = constant;
  15223. }
  15224. /**
  15225. * Sets the plane components by copying the given values.
  15226. *
  15227. * @param {Vector3} normal - The normal.
  15228. * @param {number} constant - The constant.
  15229. * @return {Plane} A reference to this plane.
  15230. */
  15231. set( normal, constant ) {
  15232. this.normal.copy( normal );
  15233. this.constant = constant;
  15234. return this;
  15235. }
  15236. /**
  15237. * Sets the plane components by defining `x`, `y`, `z` as the
  15238. * plane normal and `w` as the constant.
  15239. *
  15240. * @param {number} x - The value for the normal's x component.
  15241. * @param {number} y - The value for the normal's y component.
  15242. * @param {number} z - The value for the normal's z component.
  15243. * @param {number} w - The constant value.
  15244. * @return {Plane} A reference to this plane.
  15245. */
  15246. setComponents( x, y, z, w ) {
  15247. this.normal.set( x, y, z );
  15248. this.constant = w;
  15249. return this;
  15250. }
  15251. /**
  15252. * Sets the plane from the given normal and coplanar point (that is a point
  15253. * that lies onto the plane).
  15254. *
  15255. * @param {Vector3} normal - The normal.
  15256. * @param {Vector3} point - A coplanar point.
  15257. * @return {Plane} A reference to this plane.
  15258. */
  15259. setFromNormalAndCoplanarPoint( normal, point ) {
  15260. this.normal.copy( normal );
  15261. this.constant = - point.dot( this.normal );
  15262. return this;
  15263. }
  15264. /**
  15265. * Sets the plane from three coplanar points. The winding order is
  15266. * assumed to be counter-clockwise, and determines the direction of
  15267. * the plane normal.
  15268. *
  15269. * @param {Vector3} a - The first coplanar point.
  15270. * @param {Vector3} b - The second coplanar point.
  15271. * @param {Vector3} c - The third coplanar point.
  15272. * @return {Plane} A reference to this plane.
  15273. */
  15274. setFromCoplanarPoints( a, b, c ) {
  15275. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  15276. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  15277. this.setFromNormalAndCoplanarPoint( normal, a );
  15278. return this;
  15279. }
  15280. /**
  15281. * Copies the values of the given plane to this instance.
  15282. *
  15283. * @param {Plane} plane - The plane to copy.
  15284. * @return {Plane} A reference to this plane.
  15285. */
  15286. copy( plane ) {
  15287. this.normal.copy( plane.normal );
  15288. this.constant = plane.constant;
  15289. return this;
  15290. }
  15291. /**
  15292. * Normalizes the plane normal and adjusts the constant accordingly.
  15293. *
  15294. * @return {Plane} A reference to this plane.
  15295. */
  15296. normalize() {
  15297. // Note: will lead to a divide by zero if the plane is invalid.
  15298. const inverseNormalLength = 1.0 / this.normal.length();
  15299. this.normal.multiplyScalar( inverseNormalLength );
  15300. this.constant *= inverseNormalLength;
  15301. return this;
  15302. }
  15303. /**
  15304. * Negates both the plane normal and the constant.
  15305. *
  15306. * @return {Plane} A reference to this plane.
  15307. */
  15308. negate() {
  15309. this.constant *= -1;
  15310. this.normal.negate();
  15311. return this;
  15312. }
  15313. /**
  15314. * Returns the signed distance from the given point to this plane.
  15315. *
  15316. * @param {Vector3} point - The point to compute the distance for.
  15317. * @return {number} The signed distance.
  15318. */
  15319. distanceToPoint( point ) {
  15320. return this.normal.dot( point ) + this.constant;
  15321. }
  15322. /**
  15323. * Returns the signed distance from the given sphere to this plane.
  15324. *
  15325. * @param {Sphere} sphere - The sphere to compute the distance for.
  15326. * @return {number} The signed distance.
  15327. */
  15328. distanceToSphere( sphere ) {
  15329. return this.distanceToPoint( sphere.center ) - sphere.radius;
  15330. }
  15331. /**
  15332. * Projects a the given point onto the plane.
  15333. *
  15334. * @param {Vector3} point - The point to project.
  15335. * @param {Vector3} target - The target vector that is used to store the method's result.
  15336. * @return {Vector3} The projected point on the plane.
  15337. */
  15338. projectPoint( point, target ) {
  15339. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  15340. }
  15341. /**
  15342. * Returns the intersection point of the passed line and the plane. Returns
  15343. * `null` if the line does not intersect. Returns the line's starting point if
  15344. * the line is coplanar with the plane.
  15345. *
  15346. * @param {Line3} line - The line to compute the intersection for.
  15347. * @param {Vector3} target - The target vector that is used to store the method's result.
  15348. * @return {?Vector3} The intersection point.
  15349. */
  15350. intersectLine( line, target ) {
  15351. const direction = line.delta( _vector1 );
  15352. const denominator = this.normal.dot( direction );
  15353. if ( denominator === 0 ) {
  15354. // line is coplanar, return origin
  15355. if ( this.distanceToPoint( line.start ) === 0 ) {
  15356. return target.copy( line.start );
  15357. }
  15358. // Unsure if this is the correct method to handle this case.
  15359. return null;
  15360. }
  15361. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  15362. if ( t < 0 || t > 1 ) {
  15363. return null;
  15364. }
  15365. return target.copy( line.start ).addScaledVector( direction, t );
  15366. }
  15367. /**
  15368. * Returns `true` if the given line segment intersects with (passes through) the plane.
  15369. *
  15370. * @param {Line3} line - The line to test.
  15371. * @return {boolean} Whether the given line segment intersects with the plane or not.
  15372. */
  15373. intersectsLine( line ) {
  15374. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  15375. const startSign = this.distanceToPoint( line.start );
  15376. const endSign = this.distanceToPoint( line.end );
  15377. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  15378. }
  15379. /**
  15380. * Returns `true` if the given bounding box intersects with the plane.
  15381. *
  15382. * @param {Box3} box - The bounding box to test.
  15383. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  15384. */
  15385. intersectsBox( box ) {
  15386. return box.intersectsPlane( this );
  15387. }
  15388. /**
  15389. * Returns `true` if the given bounding sphere intersects with the plane.
  15390. *
  15391. * @param {Sphere} sphere - The bounding sphere to test.
  15392. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  15393. */
  15394. intersectsSphere( sphere ) {
  15395. return sphere.intersectsPlane( this );
  15396. }
  15397. /**
  15398. * Returns a coplanar vector to the plane, by calculating the
  15399. * projection of the normal at the origin onto the plane.
  15400. *
  15401. * @param {Vector3} target - The target vector that is used to store the method's result.
  15402. * @return {Vector3} The coplanar point.
  15403. */
  15404. coplanarPoint( target ) {
  15405. return target.copy( this.normal ).multiplyScalar( - this.constant );
  15406. }
  15407. /**
  15408. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  15409. *
  15410. * The optional normal matrix can be pre-computed like so:
  15411. * ```js
  15412. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15413. * ```
  15414. *
  15415. * @param {Matrix4} matrix - The transformation matrix.
  15416. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  15417. * @return {Plane} A reference to this plane.
  15418. */
  15419. applyMatrix4( matrix, optionalNormalMatrix ) {
  15420. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  15421. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  15422. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  15423. this.constant = - referencePoint.dot( normal );
  15424. return this;
  15425. }
  15426. /**
  15427. * Translates the plane by the distance defined by the given offset vector.
  15428. * Note that this only affects the plane constant and will not affect the normal vector.
  15429. *
  15430. * @param {Vector3} offset - The offset vector.
  15431. * @return {Plane} A reference to this plane.
  15432. */
  15433. translate( offset ) {
  15434. this.constant -= offset.dot( this.normal );
  15435. return this;
  15436. }
  15437. /**
  15438. * Returns `true` if this plane is equal with the given one.
  15439. *
  15440. * @param {Plane} plane - The plane to test for equality.
  15441. * @return {boolean} Whether this plane is equal with the given one.
  15442. */
  15443. equals( plane ) {
  15444. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  15445. }
  15446. /**
  15447. * Returns a new plane with copied values from this instance.
  15448. *
  15449. * @return {Plane} A clone of this instance.
  15450. */
  15451. clone() {
  15452. return new this.constructor().copy( this );
  15453. }
  15454. }
  15455. const _sphere$3 = /*@__PURE__*/ new Sphere();
  15456. const _vector$6 = /*@__PURE__*/ new Vector3();
  15457. /**
  15458. * Frustums are used to determine what is inside the camera's field of view.
  15459. * They help speed up the rendering process - objects which lie outside a camera's
  15460. * frustum can safely be excluded from rendering.
  15461. *
  15462. * This class is mainly intended for use internally by a renderer.
  15463. */
  15464. class Frustum {
  15465. /**
  15466. * Constructs a new frustum.
  15467. *
  15468. * @param {Plane} [p0] - The first plane that encloses the frustum.
  15469. * @param {Plane} [p1] - The second plane that encloses the frustum.
  15470. * @param {Plane} [p2] - The third plane that encloses the frustum.
  15471. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  15472. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  15473. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  15474. */
  15475. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  15476. /**
  15477. * This array holds the planes that enclose the frustum.
  15478. *
  15479. * @type {Array<Plane>}
  15480. */
  15481. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  15482. }
  15483. /**
  15484. * Sets the frustum planes by copying the given planes.
  15485. *
  15486. * @param {Plane} [p0] - The first plane that encloses the frustum.
  15487. * @param {Plane} [p1] - The second plane that encloses the frustum.
  15488. * @param {Plane} [p2] - The third plane that encloses the frustum.
  15489. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  15490. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  15491. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  15492. * @return {Frustum} A reference to this frustum.
  15493. */
  15494. set( p0, p1, p2, p3, p4, p5 ) {
  15495. const planes = this.planes;
  15496. planes[ 0 ].copy( p0 );
  15497. planes[ 1 ].copy( p1 );
  15498. planes[ 2 ].copy( p2 );
  15499. planes[ 3 ].copy( p3 );
  15500. planes[ 4 ].copy( p4 );
  15501. planes[ 5 ].copy( p5 );
  15502. return this;
  15503. }
  15504. /**
  15505. * Copies the values of the given frustum to this instance.
  15506. *
  15507. * @param {Frustum} frustum - The frustum to copy.
  15508. * @return {Frustum} A reference to this frustum.
  15509. */
  15510. copy( frustum ) {
  15511. const planes = this.planes;
  15512. for ( let i = 0; i < 6; i ++ ) {
  15513. planes[ i ].copy( frustum.planes[ i ] );
  15514. }
  15515. return this;
  15516. }
  15517. /**
  15518. * Sets the frustum planes from the given projection matrix.
  15519. *
  15520. * @param {Matrix4} m - The projection matrix.
  15521. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  15522. * @return {Frustum} A reference to this frustum.
  15523. */
  15524. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  15525. const planes = this.planes;
  15526. const me = m.elements;
  15527. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  15528. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  15529. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  15530. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  15531. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  15532. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  15533. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  15534. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  15535. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  15536. if ( coordinateSystem === WebGLCoordinateSystem ) {
  15537. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  15538. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  15539. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  15540. } else {
  15541. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  15542. }
  15543. return this;
  15544. }
  15545. /**
  15546. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  15547. *
  15548. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  15549. *
  15550. * @param {Object3D} object - The 3D object to test.
  15551. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  15552. */
  15553. intersectsObject( object ) {
  15554. if ( object.boundingSphere !== undefined ) {
  15555. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  15556. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  15557. } else {
  15558. const geometry = object.geometry;
  15559. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15560. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  15561. }
  15562. return this.intersectsSphere( _sphere$3 );
  15563. }
  15564. /**
  15565. * Returns `true` if the given sprite is intersecting this frustum.
  15566. *
  15567. * @param {Sprite} sprite - The sprite to test.
  15568. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  15569. */
  15570. intersectsSprite( sprite ) {
  15571. _sphere$3.center.set( 0, 0, 0 );
  15572. _sphere$3.radius = 0.7071067811865476;
  15573. _sphere$3.applyMatrix4( sprite.matrixWorld );
  15574. return this.intersectsSphere( _sphere$3 );
  15575. }
  15576. /**
  15577. * Returns `true` if the given bounding sphere is intersecting this frustum.
  15578. *
  15579. * @param {Sphere} sphere - The bounding sphere to test.
  15580. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  15581. */
  15582. intersectsSphere( sphere ) {
  15583. const planes = this.planes;
  15584. const center = sphere.center;
  15585. const negRadius = - sphere.radius;
  15586. for ( let i = 0; i < 6; i ++ ) {
  15587. const distance = planes[ i ].distanceToPoint( center );
  15588. if ( distance < negRadius ) {
  15589. return false;
  15590. }
  15591. }
  15592. return true;
  15593. }
  15594. /**
  15595. * Returns `true` if the given bounding box is intersecting this frustum.
  15596. *
  15597. * @param {Box3} box - The bounding box to test.
  15598. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  15599. */
  15600. intersectsBox( box ) {
  15601. const planes = this.planes;
  15602. for ( let i = 0; i < 6; i ++ ) {
  15603. const plane = planes[ i ];
  15604. // corner at max distance
  15605. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  15606. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  15607. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  15608. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  15609. return false;
  15610. }
  15611. }
  15612. return true;
  15613. }
  15614. /**
  15615. * Returns `true` if the given point lies within the frustum.
  15616. *
  15617. * @param {Vector3} point - The point to test.
  15618. * @return {boolean} Whether the point lies within this frustum or not.
  15619. */
  15620. containsPoint( point ) {
  15621. const planes = this.planes;
  15622. for ( let i = 0; i < 6; i ++ ) {
  15623. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  15624. return false;
  15625. }
  15626. }
  15627. return true;
  15628. }
  15629. /**
  15630. * Returns a new frustum with copied values from this instance.
  15631. *
  15632. * @return {Frustum} A clone of this instance.
  15633. */
  15634. clone() {
  15635. return new this.constructor().copy( this );
  15636. }
  15637. }
  15638. function ascIdSort( a, b ) {
  15639. return a - b;
  15640. }
  15641. function sortOpaque( a, b ) {
  15642. return a.z - b.z;
  15643. }
  15644. function sortTransparent( a, b ) {
  15645. return b.z - a.z;
  15646. }
  15647. class MultiDrawRenderList {
  15648. constructor() {
  15649. this.index = 0;
  15650. this.pool = [];
  15651. this.list = [];
  15652. }
  15653. push( start, count, z, index ) {
  15654. const pool = this.pool;
  15655. const list = this.list;
  15656. if ( this.index >= pool.length ) {
  15657. pool.push( {
  15658. start: -1,
  15659. count: -1,
  15660. z: -1,
  15661. index: -1,
  15662. } );
  15663. }
  15664. const item = pool[ this.index ];
  15665. list.push( item );
  15666. this.index ++;
  15667. item.start = start;
  15668. item.count = count;
  15669. item.z = z;
  15670. item.index = index;
  15671. }
  15672. reset() {
  15673. this.list.length = 0;
  15674. this.index = 0;
  15675. }
  15676. }
  15677. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  15678. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  15679. const _frustum = /*@__PURE__*/ new Frustum();
  15680. const _box$1 = /*@__PURE__*/ new Box3();
  15681. const _sphere$2 = /*@__PURE__*/ new Sphere();
  15682. const _vector$5 = /*@__PURE__*/ new Vector3();
  15683. const _forward = /*@__PURE__*/ new Vector3();
  15684. const _temp = /*@__PURE__*/ new Vector3();
  15685. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  15686. const _mesh = /*@__PURE__*/ new Mesh();
  15687. const _batchIntersects = [];
  15688. // copies data from attribute "src" into "target" starting at "targetOffset"
  15689. function copyAttributeData( src, target, targetOffset = 0 ) {
  15690. const itemSize = target.itemSize;
  15691. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  15692. // use the component getters and setters if the array data cannot
  15693. // be copied directly
  15694. const vertexCount = src.count;
  15695. for ( let i = 0; i < vertexCount; i ++ ) {
  15696. for ( let c = 0; c < itemSize; c ++ ) {
  15697. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  15698. }
  15699. }
  15700. } else {
  15701. // faster copy approach using typed array set function
  15702. target.array.set( src.array, targetOffset * itemSize );
  15703. }
  15704. target.needsUpdate = true;
  15705. }
  15706. // safely copies array contents to a potentially smaller array
  15707. function copyArrayContents( src, target ) {
  15708. if ( src.constructor !== target.constructor ) {
  15709. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  15710. const len = Math.min( src.length, target.length );
  15711. for ( let i = 0; i < len; i ++ ) {
  15712. target[ i ] = src[ i ];
  15713. }
  15714. } else {
  15715. // if the arrays use the same data layout we can use a fast block copy
  15716. const len = Math.min( src.length, target.length );
  15717. target.set( new src.constructor( src.buffer, 0, len ) );
  15718. }
  15719. }
  15720. /**
  15721. * A special version of a mesh with multi draw batch rendering support. Use
  15722. * this class if you have to render a large number of objects with the same
  15723. * material but with different geometries or world transformations. The usage of
  15724. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  15725. * rendering performance in your application.
  15726. *
  15727. * ```js
  15728. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  15729. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  15730. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15731. *
  15732. * // initialize and add geometries into the batched mesh
  15733. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  15734. * const boxGeometryId = batchedMesh.addGeometry( box );
  15735. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  15736. *
  15737. * // create instances of those geometries
  15738. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  15739. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  15740. *
  15741. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  15742. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  15743. *
  15744. * // position the geometries
  15745. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  15746. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  15747. *
  15748. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  15749. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  15750. *
  15751. * scene.add( batchedMesh );
  15752. * ```
  15753. *
  15754. * @augments Mesh
  15755. */
  15756. class BatchedMesh extends Mesh {
  15757. /**
  15758. * Constructs a new batched mesh.
  15759. *
  15760. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  15761. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  15762. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  15763. * @param {Material|Array<Material>} [material] - The mesh material.
  15764. */
  15765. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  15766. super( new BufferGeometry(), material );
  15767. /**
  15768. * This flag can be used for type testing.
  15769. *
  15770. * @type {boolean}
  15771. * @readonly
  15772. * @default true
  15773. */
  15774. this.isBatchedMesh = true;
  15775. /**
  15776. * When set ot `true`, the individual objects of a batch are frustum culled.
  15777. *
  15778. * @type {boolean}
  15779. * @default true
  15780. */
  15781. this.perObjectFrustumCulled = true;
  15782. /**
  15783. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  15784. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  15785. * rendered front to back.
  15786. *
  15787. * @type {boolean}
  15788. * @default true
  15789. */
  15790. this.sortObjects = true;
  15791. /**
  15792. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  15793. *
  15794. * @type {?Box3}
  15795. * @default null
  15796. */
  15797. this.boundingBox = null;
  15798. /**
  15799. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  15800. *
  15801. * @type {?Sphere}
  15802. * @default null
  15803. */
  15804. this.boundingSphere = null;
  15805. /**
  15806. * Takes a sort a function that is run before render. The function takes a list of instances to
  15807. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  15808. * sort with.
  15809. *
  15810. * @type {?Function}
  15811. * @default null
  15812. */
  15813. this.customSort = null;
  15814. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  15815. this._instanceInfo = [];
  15816. this._geometryInfo = [];
  15817. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  15818. this._availableInstanceIds = [];
  15819. this._availableGeometryIds = [];
  15820. // used to track where the next point is that geometry should be inserted
  15821. this._nextIndexStart = 0;
  15822. this._nextVertexStart = 0;
  15823. this._geometryCount = 0;
  15824. // flags
  15825. this._visibilityChanged = true;
  15826. this._geometryInitialized = false;
  15827. // cached user options
  15828. this._maxInstanceCount = maxInstanceCount;
  15829. this._maxVertexCount = maxVertexCount;
  15830. this._maxIndexCount = maxIndexCount;
  15831. // buffers for multi draw
  15832. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  15833. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  15834. this._multiDrawCount = 0;
  15835. this._multiDrawInstances = null;
  15836. // Local matrix per geometry by using data texture
  15837. this._matricesTexture = null;
  15838. this._indirectTexture = null;
  15839. this._colorsTexture = null;
  15840. this._initMatricesTexture();
  15841. this._initIndirectTexture();
  15842. }
  15843. /**
  15844. * The maximum number of individual instances that can be stored in the batch.
  15845. *
  15846. * @type {number}
  15847. * @readonly
  15848. */
  15849. get maxInstanceCount() {
  15850. return this._maxInstanceCount;
  15851. }
  15852. /**
  15853. * The instance count.
  15854. *
  15855. * @type {number}
  15856. * @readonly
  15857. */
  15858. get instanceCount() {
  15859. return this._instanceInfo.length - this._availableInstanceIds.length;
  15860. }
  15861. /**
  15862. * The number of unused vertices.
  15863. *
  15864. * @type {number}
  15865. * @readonly
  15866. */
  15867. get unusedVertexCount() {
  15868. return this._maxVertexCount - this._nextVertexStart;
  15869. }
  15870. /**
  15871. * The number of unused indices.
  15872. *
  15873. * @type {number}
  15874. * @readonly
  15875. */
  15876. get unusedIndexCount() {
  15877. return this._maxIndexCount - this._nextIndexStart;
  15878. }
  15879. _initMatricesTexture() {
  15880. // layout (1 matrix = 4 pixels)
  15881. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15882. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  15883. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  15884. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  15885. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  15886. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  15887. size = Math.ceil( size / 4 ) * 4;
  15888. size = Math.max( size, 4 );
  15889. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  15890. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  15891. this._matricesTexture = matricesTexture;
  15892. }
  15893. _initIndirectTexture() {
  15894. let size = Math.sqrt( this._maxInstanceCount );
  15895. size = Math.ceil( size );
  15896. const indirectArray = new Uint32Array( size * size );
  15897. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  15898. this._indirectTexture = indirectTexture;
  15899. }
  15900. _initColorsTexture() {
  15901. let size = Math.sqrt( this._maxInstanceCount );
  15902. size = Math.ceil( size );
  15903. // 4 floats per RGBA pixel initialized to white
  15904. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  15905. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  15906. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  15907. this._colorsTexture = colorsTexture;
  15908. }
  15909. _initializeGeometry( reference ) {
  15910. const geometry = this.geometry;
  15911. const maxVertexCount = this._maxVertexCount;
  15912. const maxIndexCount = this._maxIndexCount;
  15913. if ( this._geometryInitialized === false ) {
  15914. for ( const attributeName in reference.attributes ) {
  15915. const srcAttribute = reference.getAttribute( attributeName );
  15916. const { array, itemSize, normalized } = srcAttribute;
  15917. const dstArray = new array.constructor( maxVertexCount * itemSize );
  15918. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  15919. geometry.setAttribute( attributeName, dstAttribute );
  15920. }
  15921. if ( reference.getIndex() !== null ) {
  15922. // Reserve last u16 index for primitive restart.
  15923. const indexArray = maxVertexCount > 65535
  15924. ? new Uint32Array( maxIndexCount )
  15925. : new Uint16Array( maxIndexCount );
  15926. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  15927. }
  15928. this._geometryInitialized = true;
  15929. }
  15930. }
  15931. // Make sure the geometry is compatible with the existing combined geometry attributes
  15932. _validateGeometry( geometry ) {
  15933. // check to ensure the geometries are using consistent attributes and indices
  15934. const batchGeometry = this.geometry;
  15935. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  15936. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  15937. }
  15938. for ( const attributeName in batchGeometry.attributes ) {
  15939. if ( ! geometry.hasAttribute( attributeName ) ) {
  15940. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  15941. }
  15942. const srcAttribute = geometry.getAttribute( attributeName );
  15943. const dstAttribute = batchGeometry.getAttribute( attributeName );
  15944. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  15945. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  15946. }
  15947. }
  15948. }
  15949. /**
  15950. * Validates the instance defined by the given ID.
  15951. *
  15952. * @param {number} instanceId - The the instance to validate.
  15953. */
  15954. validateInstanceId( instanceId ) {
  15955. const instanceInfo = this._instanceInfo;
  15956. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  15957. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  15958. }
  15959. }
  15960. /**
  15961. * Validates the geometry defined by the given ID.
  15962. *
  15963. * @param {number} geometryId - The the geometry to validate.
  15964. */
  15965. validateGeometryId( geometryId ) {
  15966. const geometryInfoList = this._geometryInfo;
  15967. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  15968. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  15969. }
  15970. }
  15971. /**
  15972. * Takes a sort a function that is run before render. The function takes a list of instances to
  15973. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  15974. *
  15975. * @param {Function} func - The custom sort function.
  15976. * @return {BatchedMesh} A reference to this batched mesh.
  15977. */
  15978. setCustomSort( func ) {
  15979. this.customSort = func;
  15980. return this;
  15981. }
  15982. /**
  15983. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  15984. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  15985. * otherwise they are `null`.
  15986. */
  15987. computeBoundingBox() {
  15988. if ( this.boundingBox === null ) {
  15989. this.boundingBox = new Box3();
  15990. }
  15991. const boundingBox = this.boundingBox;
  15992. const instanceInfo = this._instanceInfo;
  15993. boundingBox.makeEmpty();
  15994. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15995. if ( instanceInfo[ i ].active === false ) continue;
  15996. const geometryId = instanceInfo[ i ].geometryIndex;
  15997. this.getMatrixAt( i, _matrix$1 );
  15998. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  15999. boundingBox.union( _box$1 );
  16000. }
  16001. }
  16002. /**
  16003. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  16004. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  16005. * otherwise they are `null`.
  16006. */
  16007. computeBoundingSphere() {
  16008. if ( this.boundingSphere === null ) {
  16009. this.boundingSphere = new Sphere();
  16010. }
  16011. const boundingSphere = this.boundingSphere;
  16012. const instanceInfo = this._instanceInfo;
  16013. boundingSphere.makeEmpty();
  16014. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  16015. if ( instanceInfo[ i ].active === false ) continue;
  16016. const geometryId = instanceInfo[ i ].geometryIndex;
  16017. this.getMatrixAt( i, _matrix$1 );
  16018. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  16019. boundingSphere.union( _sphere$2 );
  16020. }
  16021. }
  16022. /**
  16023. * Adds a new instance to the batch using the geometry of the given ID and returns
  16024. * a new id referring to the new instance to be used by other functions.
  16025. *
  16026. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  16027. * @return {number} The instance ID.
  16028. */
  16029. addInstance( geometryId ) {
  16030. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  16031. // ensure we're not over geometry
  16032. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  16033. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  16034. }
  16035. const instanceInfo = {
  16036. visible: true,
  16037. active: true,
  16038. geometryIndex: geometryId,
  16039. };
  16040. let drawId = null;
  16041. // Prioritize using previously freed instance ids
  16042. if ( this._availableInstanceIds.length > 0 ) {
  16043. this._availableInstanceIds.sort( ascIdSort );
  16044. drawId = this._availableInstanceIds.shift();
  16045. this._instanceInfo[ drawId ] = instanceInfo;
  16046. } else {
  16047. drawId = this._instanceInfo.length;
  16048. this._instanceInfo.push( instanceInfo );
  16049. }
  16050. const matricesTexture = this._matricesTexture;
  16051. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  16052. matricesTexture.needsUpdate = true;
  16053. const colorsTexture = this._colorsTexture;
  16054. if ( colorsTexture ) {
  16055. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  16056. colorsTexture.needsUpdate = true;
  16057. }
  16058. this._visibilityChanged = true;
  16059. return drawId;
  16060. }
  16061. /**
  16062. * Adds the given geometry to the batch and returns the associated
  16063. * geometry id referring to it to be used in other functions.
  16064. *
  16065. * @param {BufferGeometry} geometry - The geometry to add.
  16066. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  16067. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  16068. * to set a new geometry at this index at a later time that is larger than the original geometry.
  16069. * Defaults to the length of the given geometry vertex buffer.
  16070. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  16071. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  16072. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  16073. * the length of the given geometry index buffer.
  16074. * @return {number} The geometry ID.
  16075. */
  16076. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  16077. this._initializeGeometry( geometry );
  16078. this._validateGeometry( geometry );
  16079. const geometryInfo = {
  16080. // geometry information
  16081. vertexStart: -1,
  16082. vertexCount: -1,
  16083. reservedVertexCount: -1,
  16084. indexStart: -1,
  16085. indexCount: -1,
  16086. reservedIndexCount: -1,
  16087. // draw range information
  16088. start: -1,
  16089. count: -1,
  16090. // state
  16091. boundingBox: null,
  16092. boundingSphere: null,
  16093. active: true,
  16094. };
  16095. const geometryInfoList = this._geometryInfo;
  16096. geometryInfo.vertexStart = this._nextVertexStart;
  16097. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  16098. const index = geometry.getIndex();
  16099. const hasIndex = index !== null;
  16100. if ( hasIndex ) {
  16101. geometryInfo.indexStart = this._nextIndexStart;
  16102. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  16103. }
  16104. if (
  16105. geometryInfo.indexStart !== -1 &&
  16106. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  16107. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  16108. ) {
  16109. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  16110. }
  16111. // update id
  16112. let geometryId;
  16113. if ( this._availableGeometryIds.length > 0 ) {
  16114. this._availableGeometryIds.sort( ascIdSort );
  16115. geometryId = this._availableGeometryIds.shift();
  16116. geometryInfoList[ geometryId ] = geometryInfo;
  16117. } else {
  16118. geometryId = this._geometryCount;
  16119. this._geometryCount ++;
  16120. geometryInfoList.push( geometryInfo );
  16121. }
  16122. // update the geometry
  16123. this.setGeometryAt( geometryId, geometry );
  16124. // increment the next geometry position
  16125. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  16126. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  16127. return geometryId;
  16128. }
  16129. /**
  16130. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  16131. * is not enough space reserved for geometry. Calling this will change all instances that are
  16132. * rendering that geometry.
  16133. *
  16134. * @param {number} geometryId - The ID of the geomtry that should be replaced with the given geometry.
  16135. * @param {BufferGeometry} geometry - The new geometry.
  16136. * @return {number} The geometry ID.
  16137. */
  16138. setGeometryAt( geometryId, geometry ) {
  16139. if ( geometryId >= this._geometryCount ) {
  16140. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  16141. }
  16142. this._validateGeometry( geometry );
  16143. const batchGeometry = this.geometry;
  16144. const hasIndex = batchGeometry.getIndex() !== null;
  16145. const dstIndex = batchGeometry.getIndex();
  16146. const srcIndex = geometry.getIndex();
  16147. const geometryInfo = this._geometryInfo[ geometryId ];
  16148. if (
  16149. hasIndex &&
  16150. srcIndex.count > geometryInfo.reservedIndexCount ||
  16151. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  16152. ) {
  16153. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  16154. }
  16155. // copy geometry buffer data over
  16156. const vertexStart = geometryInfo.vertexStart;
  16157. const reservedVertexCount = geometryInfo.reservedVertexCount;
  16158. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  16159. for ( const attributeName in batchGeometry.attributes ) {
  16160. // copy attribute data
  16161. const srcAttribute = geometry.getAttribute( attributeName );
  16162. const dstAttribute = batchGeometry.getAttribute( attributeName );
  16163. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  16164. // fill the rest in with zeroes
  16165. const itemSize = srcAttribute.itemSize;
  16166. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  16167. const index = vertexStart + i;
  16168. for ( let c = 0; c < itemSize; c ++ ) {
  16169. dstAttribute.setComponent( index, c, 0 );
  16170. }
  16171. }
  16172. dstAttribute.needsUpdate = true;
  16173. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  16174. }
  16175. // copy index
  16176. if ( hasIndex ) {
  16177. const indexStart = geometryInfo.indexStart;
  16178. const reservedIndexCount = geometryInfo.reservedIndexCount;
  16179. geometryInfo.indexCount = geometry.getIndex().count;
  16180. // copy index data over
  16181. for ( let i = 0; i < srcIndex.count; i ++ ) {
  16182. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  16183. }
  16184. // fill the rest in with zeroes
  16185. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  16186. dstIndex.setX( indexStart + i, vertexStart );
  16187. }
  16188. dstIndex.needsUpdate = true;
  16189. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  16190. }
  16191. // update the draw range
  16192. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  16193. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  16194. // store the bounding boxes
  16195. geometryInfo.boundingBox = null;
  16196. if ( geometry.boundingBox !== null ) {
  16197. geometryInfo.boundingBox = geometry.boundingBox.clone();
  16198. }
  16199. geometryInfo.boundingSphere = null;
  16200. if ( geometry.boundingSphere !== null ) {
  16201. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  16202. }
  16203. this._visibilityChanged = true;
  16204. return geometryId;
  16205. }
  16206. /**
  16207. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  16208. * this geometry will also be removed as a side effect.
  16209. *
  16210. * @param {number} geometryId - The ID of the geomtry to remove from the batch.
  16211. * @return {BatchedMesh} A reference to this batched mesh.
  16212. */
  16213. deleteGeometry( geometryId ) {
  16214. const geometryInfoList = this._geometryInfo;
  16215. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  16216. return this;
  16217. }
  16218. // delete any instances associated with this geometry
  16219. const instanceInfo = this._instanceInfo;
  16220. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  16221. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  16222. this.deleteInstance( i );
  16223. }
  16224. }
  16225. geometryInfoList[ geometryId ].active = false;
  16226. this._availableGeometryIds.push( geometryId );
  16227. this._visibilityChanged = true;
  16228. return this;
  16229. }
  16230. /**
  16231. * Deletes an existing instance from the batch using the given ID.
  16232. *
  16233. * @param {number} instanceId - The ID of the instance to remove from the batch.
  16234. * @return {BatchedMesh} A reference to this batched mesh.
  16235. */
  16236. deleteInstance( instanceId ) {
  16237. this.validateInstanceId( instanceId );
  16238. this._instanceInfo[ instanceId ].active = false;
  16239. this._availableInstanceIds.push( instanceId );
  16240. this._visibilityChanged = true;
  16241. return this;
  16242. }
  16243. /**
  16244. * Repacks the sub geometries in [name] to remove any unused space remaining from
  16245. * previously deleted geometry, freeing up space to add new geometry.
  16246. *
  16247. * @param {number} instanceId - The ID of the instance to remove from the batch.
  16248. * @return {BatchedMesh} A reference to this batched mesh.
  16249. */
  16250. optimize() {
  16251. // track the next indices to copy data to
  16252. let nextVertexStart = 0;
  16253. let nextIndexStart = 0;
  16254. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  16255. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  16256. const geometryInfoList = this._geometryInfo;
  16257. const indices = geometryInfoList
  16258. .map( ( e, i ) => i )
  16259. .sort( ( a, b ) => {
  16260. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  16261. } );
  16262. const geometry = this.geometry;
  16263. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  16264. // if a geometry range is inactive then don't copy anything
  16265. const index = indices[ i ];
  16266. const geometryInfo = geometryInfoList[ index ];
  16267. if ( geometryInfo.active === false ) {
  16268. continue;
  16269. }
  16270. // if a geometry contains an index buffer then shift it, as well
  16271. if ( geometry.index !== null ) {
  16272. if ( geometryInfo.indexStart !== nextIndexStart ) {
  16273. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  16274. const index = geometry.index;
  16275. const array = index.array;
  16276. // shift the index pointers based on how the vertex data will shift
  16277. // adjusting the index must happen first so the original vertex start value is available
  16278. const elementDelta = nextVertexStart - vertexStart;
  16279. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  16280. array[ j ] = array[ j ] + elementDelta;
  16281. }
  16282. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  16283. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  16284. geometryInfo.indexStart = nextIndexStart;
  16285. }
  16286. nextIndexStart += geometryInfo.reservedIndexCount;
  16287. }
  16288. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  16289. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  16290. const { vertexStart, reservedVertexCount } = geometryInfo;
  16291. const attributes = geometry.attributes;
  16292. for ( const key in attributes ) {
  16293. const attribute = attributes[ key ];
  16294. const { array, itemSize } = attribute;
  16295. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  16296. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  16297. }
  16298. geometryInfo.vertexStart = nextVertexStart;
  16299. }
  16300. nextVertexStart += geometryInfo.reservedVertexCount;
  16301. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  16302. // step the next geometry points to the shifted position
  16303. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  16304. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  16305. }
  16306. return this;
  16307. }
  16308. /**
  16309. * Returns the bounding box for the given geometry.
  16310. *
  16311. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  16312. * @param {Box3} target - The target object that is used to store the method's result.
  16313. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  16314. */
  16315. getBoundingBoxAt( geometryId, target ) {
  16316. if ( geometryId >= this._geometryCount ) {
  16317. return null;
  16318. }
  16319. // compute bounding box
  16320. const geometry = this.geometry;
  16321. const geometryInfo = this._geometryInfo[ geometryId ];
  16322. if ( geometryInfo.boundingBox === null ) {
  16323. const box = new Box3();
  16324. const index = geometry.index;
  16325. const position = geometry.attributes.position;
  16326. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  16327. let iv = i;
  16328. if ( index ) {
  16329. iv = index.getX( iv );
  16330. }
  16331. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  16332. }
  16333. geometryInfo.boundingBox = box;
  16334. }
  16335. target.copy( geometryInfo.boundingBox );
  16336. return target;
  16337. }
  16338. /**
  16339. * Returns the bounding sphere for the given geometry.
  16340. *
  16341. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  16342. * @param {Sphere} target - The target object that is used to store the method's result.
  16343. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  16344. */
  16345. getBoundingSphereAt( geometryId, target ) {
  16346. if ( geometryId >= this._geometryCount ) {
  16347. return null;
  16348. }
  16349. // compute bounding sphere
  16350. const geometry = this.geometry;
  16351. const geometryInfo = this._geometryInfo[ geometryId ];
  16352. if ( geometryInfo.boundingSphere === null ) {
  16353. const sphere = new Sphere();
  16354. this.getBoundingBoxAt( geometryId, _box$1 );
  16355. _box$1.getCenter( sphere.center );
  16356. const index = geometry.index;
  16357. const position = geometry.attributes.position;
  16358. let maxRadiusSq = 0;
  16359. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  16360. let iv = i;
  16361. if ( index ) {
  16362. iv = index.getX( iv );
  16363. }
  16364. _vector$5.fromBufferAttribute( position, iv );
  16365. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  16366. }
  16367. sphere.radius = Math.sqrt( maxRadiusSq );
  16368. geometryInfo.boundingSphere = sphere;
  16369. }
  16370. target.copy( geometryInfo.boundingSphere );
  16371. return target;
  16372. }
  16373. /**
  16374. * Sets the given local transformation matrix to the defined instance.
  16375. * Negatively scaled matrices are not supported.
  16376. *
  16377. * @param {number} instanceId - The ID of an instance to set the matrix of.
  16378. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  16379. * @return {BatchedMesh} A reference to this batched mesh.
  16380. */
  16381. setMatrixAt( instanceId, matrix ) {
  16382. this.validateInstanceId( instanceId );
  16383. const matricesTexture = this._matricesTexture;
  16384. const matricesArray = this._matricesTexture.image.data;
  16385. matrix.toArray( matricesArray, instanceId * 16 );
  16386. matricesTexture.needsUpdate = true;
  16387. return this;
  16388. }
  16389. /**
  16390. * Returns the local transformation matrix of the defined instance.
  16391. *
  16392. * @param {number} instanceId - The ID of an instance to get the matrix of.
  16393. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  16394. * @return {Matrix4} The instance's local transformation matrix.
  16395. */
  16396. getMatrixAt( instanceId, matrix ) {
  16397. this.validateInstanceId( instanceId );
  16398. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  16399. }
  16400. /**
  16401. * Sets the given color to the defined instance.
  16402. *
  16403. * @param {number} instanceId - The ID of an instance to set the color of.
  16404. * @param {Color} color - The color to set the instance to.
  16405. * @return {BatchedMesh} A reference to this batched mesh.
  16406. */
  16407. setColorAt( instanceId, color ) {
  16408. this.validateInstanceId( instanceId );
  16409. if ( this._colorsTexture === null ) {
  16410. this._initColorsTexture();
  16411. }
  16412. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  16413. this._colorsTexture.needsUpdate = true;
  16414. return this;
  16415. }
  16416. /**
  16417. * Returns the color of the defined instance.
  16418. *
  16419. * @param {number} instanceId - The ID of an instance to get the color of.
  16420. * @param {Color} color - The target object that is used to store the method's result.
  16421. * @return {Color} The instance's color.
  16422. */
  16423. getColorAt( instanceId, color ) {
  16424. this.validateInstanceId( instanceId );
  16425. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  16426. }
  16427. /**
  16428. * Sets the visibility of the instance.
  16429. *
  16430. * @param {number} instanceId - The id of the instance to set the visibility of.
  16431. * @param {boolean} visible - Whether the instance is visible or not.
  16432. * @return {BatchedMesh} A reference to this batched mesh.
  16433. */
  16434. setVisibleAt( instanceId, visible ) {
  16435. this.validateInstanceId( instanceId );
  16436. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  16437. return this;
  16438. }
  16439. this._instanceInfo[ instanceId ].visible = visible;
  16440. this._visibilityChanged = true;
  16441. return this;
  16442. }
  16443. /**
  16444. * Returns the visibility state of the defined instance.
  16445. *
  16446. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  16447. * @return {boolean} Whether the instance is visible or not.
  16448. */
  16449. getVisibleAt( instanceId ) {
  16450. this.validateInstanceId( instanceId );
  16451. return this._instanceInfo[ instanceId ].visible;
  16452. }
  16453. /**
  16454. * Sets the geometry ID of the instance at the given index.
  16455. *
  16456. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  16457. * @param {number} geometryId - The geometry ID to be use by the instance.
  16458. * @return {BatchedMesh} A reference to this batched mesh.
  16459. */
  16460. setGeometryIdAt( instanceId, geometryId ) {
  16461. this.validateInstanceId( instanceId );
  16462. this.validateGeometryId( geometryId );
  16463. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  16464. return this;
  16465. }
  16466. /**
  16467. * Returns the geometry ID of the defined instance.
  16468. *
  16469. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  16470. * @return {number} The instance's geometry ID.
  16471. */
  16472. getGeometryIdAt( instanceId ) {
  16473. this.validateInstanceId( instanceId );
  16474. return this._instanceInfo[ instanceId ].geometryIndex;
  16475. }
  16476. /**
  16477. * Get the range representing the subset of triangles related to the attached geometry,
  16478. * indicating the starting offset and count, or `null` if invalid.
  16479. *
  16480. * @param {number} geometryId - The id of the geometry to get the range of.
  16481. * @param {Object} [target] - The target object that is used to store the method's result.
  16482. * @return {{
  16483. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  16484. * indexStart:number,indexCount:number,reservedIndexCount:number,
  16485. * start:number,count:number
  16486. * }} The result object with range data.
  16487. */
  16488. getGeometryRangeAt( geometryId, target = {} ) {
  16489. this.validateGeometryId( geometryId );
  16490. const geometryInfo = this._geometryInfo[ geometryId ];
  16491. target.vertexStart = geometryInfo.vertexStart;
  16492. target.vertexCount = geometryInfo.vertexCount;
  16493. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  16494. target.indexStart = geometryInfo.indexStart;
  16495. target.indexCount = geometryInfo.indexCount;
  16496. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  16497. target.start = geometryInfo.start;
  16498. target.count = geometryInfo.count;
  16499. return target;
  16500. }
  16501. /**
  16502. * Resizes the necessary buffers to support the provided number of instances.
  16503. * If the provided arguments shrink the number of instances but there are not enough
  16504. * unused Ids at the end of the list then an error is thrown.
  16505. *
  16506. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  16507. */
  16508. setInstanceCount( maxInstanceCount ) {
  16509. // shrink the available instances as much as possible
  16510. const availableInstanceIds = this._availableInstanceIds;
  16511. const instanceInfo = this._instanceInfo;
  16512. availableInstanceIds.sort( ascIdSort );
  16513. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  16514. instanceInfo.pop();
  16515. availableInstanceIds.pop();
  16516. }
  16517. // throw an error if it can't be shrunk to the desired size
  16518. if ( maxInstanceCount < instanceInfo.length ) {
  16519. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  16520. }
  16521. // copy the multi draw counts
  16522. const multiDrawCounts = new Int32Array( maxInstanceCount );
  16523. const multiDrawStarts = new Int32Array( maxInstanceCount );
  16524. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  16525. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  16526. this._multiDrawCounts = multiDrawCounts;
  16527. this._multiDrawStarts = multiDrawStarts;
  16528. this._maxInstanceCount = maxInstanceCount;
  16529. // update texture data for instance sampling
  16530. const indirectTexture = this._indirectTexture;
  16531. const matricesTexture = this._matricesTexture;
  16532. const colorsTexture = this._colorsTexture;
  16533. indirectTexture.dispose();
  16534. this._initIndirectTexture();
  16535. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  16536. matricesTexture.dispose();
  16537. this._initMatricesTexture();
  16538. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  16539. if ( colorsTexture ) {
  16540. colorsTexture.dispose();
  16541. this._initColorsTexture();
  16542. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  16543. }
  16544. }
  16545. /**
  16546. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  16547. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  16548. * end of the geometry attributes then an error is thrown.
  16549. *
  16550. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  16551. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  16552. */
  16553. setGeometrySize( maxVertexCount, maxIndexCount ) {
  16554. // Check if we can shrink to the requested vertex attribute size
  16555. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  16556. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  16557. if ( requiredVertexLength > maxVertexCount ) {
  16558. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  16559. }
  16560. // Check if we can shrink to the requested index attribute size
  16561. if ( this.geometry.index ) {
  16562. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  16563. if ( requiredIndexLength > maxIndexCount ) {
  16564. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  16565. }
  16566. }
  16567. //
  16568. // dispose of the previous geometry
  16569. const oldGeometry = this.geometry;
  16570. oldGeometry.dispose();
  16571. // recreate the geometry needed based on the previous variant
  16572. this._maxVertexCount = maxVertexCount;
  16573. this._maxIndexCount = maxIndexCount;
  16574. if ( this._geometryInitialized ) {
  16575. this._geometryInitialized = false;
  16576. this.geometry = new BufferGeometry();
  16577. this._initializeGeometry( oldGeometry );
  16578. }
  16579. // copy data from the previous geometry
  16580. const geometry = this.geometry;
  16581. if ( oldGeometry.index ) {
  16582. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  16583. }
  16584. for ( const key in oldGeometry.attributes ) {
  16585. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  16586. }
  16587. }
  16588. raycast( raycaster, intersects ) {
  16589. const instanceInfo = this._instanceInfo;
  16590. const geometryInfoList = this._geometryInfo;
  16591. const matrixWorld = this.matrixWorld;
  16592. const batchGeometry = this.geometry;
  16593. // iterate over each geometry
  16594. _mesh.material = this.material;
  16595. _mesh.geometry.index = batchGeometry.index;
  16596. _mesh.geometry.attributes = batchGeometry.attributes;
  16597. if ( _mesh.geometry.boundingBox === null ) {
  16598. _mesh.geometry.boundingBox = new Box3();
  16599. }
  16600. if ( _mesh.geometry.boundingSphere === null ) {
  16601. _mesh.geometry.boundingSphere = new Sphere();
  16602. }
  16603. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  16604. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  16605. continue;
  16606. }
  16607. const geometryId = instanceInfo[ i ].geometryIndex;
  16608. const geometryInfo = geometryInfoList[ geometryId ];
  16609. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  16610. // get the intersects
  16611. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  16612. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  16613. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  16614. _mesh.raycast( raycaster, _batchIntersects );
  16615. // add batch id to the intersects
  16616. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  16617. const intersect = _batchIntersects[ j ];
  16618. intersect.object = this;
  16619. intersect.batchId = i;
  16620. intersects.push( intersect );
  16621. }
  16622. _batchIntersects.length = 0;
  16623. }
  16624. _mesh.material = null;
  16625. _mesh.geometry.index = null;
  16626. _mesh.geometry.attributes = {};
  16627. _mesh.geometry.setDrawRange( 0, Infinity );
  16628. }
  16629. copy( source ) {
  16630. super.copy( source );
  16631. this.geometry = source.geometry.clone();
  16632. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  16633. this.sortObjects = source.sortObjects;
  16634. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  16635. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  16636. this._geometryInfo = source._geometryInfo.map( info => ( {
  16637. ...info,
  16638. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  16639. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  16640. } ) );
  16641. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  16642. this._maxInstanceCount = source._maxInstanceCount;
  16643. this._maxVertexCount = source._maxVertexCount;
  16644. this._maxIndexCount = source._maxIndexCount;
  16645. this._geometryInitialized = source._geometryInitialized;
  16646. this._geometryCount = source._geometryCount;
  16647. this._multiDrawCounts = source._multiDrawCounts.slice();
  16648. this._multiDrawStarts = source._multiDrawStarts.slice();
  16649. this._matricesTexture = source._matricesTexture.clone();
  16650. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  16651. if ( this._colorsTexture !== null ) {
  16652. this._colorsTexture = source._colorsTexture.clone();
  16653. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  16654. }
  16655. return this;
  16656. }
  16657. /**
  16658. * Frees the GPU-related resources allocated by this instance. Call this
  16659. * method whenever this instance is no longer used in your app.
  16660. */
  16661. dispose() {
  16662. // Assuming the geometry is not shared with other meshes
  16663. this.geometry.dispose();
  16664. this._matricesTexture.dispose();
  16665. this._matricesTexture = null;
  16666. this._indirectTexture.dispose();
  16667. this._indirectTexture = null;
  16668. if ( this._colorsTexture !== null ) {
  16669. this._colorsTexture.dispose();
  16670. this._colorsTexture = null;
  16671. }
  16672. }
  16673. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  16674. // if visibility has not changed and frustum culling and object sorting is not required
  16675. // then skip iterating over all items
  16676. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  16677. return;
  16678. }
  16679. // the indexed version of the multi draw function requires specifying the start
  16680. // offset in bytes.
  16681. const index = geometry.getIndex();
  16682. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  16683. const instanceInfo = this._instanceInfo;
  16684. const multiDrawStarts = this._multiDrawStarts;
  16685. const multiDrawCounts = this._multiDrawCounts;
  16686. const geometryInfoList = this._geometryInfo;
  16687. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  16688. const indirectTexture = this._indirectTexture;
  16689. const indirectArray = indirectTexture.image.data;
  16690. // prepare the frustum in the local frame
  16691. if ( perObjectFrustumCulled ) {
  16692. _matrix$1
  16693. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  16694. .multiply( this.matrixWorld );
  16695. _frustum.setFromProjectionMatrix(
  16696. _matrix$1,
  16697. renderer.coordinateSystem
  16698. );
  16699. }
  16700. let multiDrawCount = 0;
  16701. if ( this.sortObjects ) {
  16702. // get the camera position in the local frame
  16703. _matrix$1.copy( this.matrixWorld ).invert();
  16704. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  16705. _forward.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  16706. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  16707. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  16708. const geometryId = instanceInfo[ i ].geometryIndex;
  16709. // get the bounds in world space
  16710. this.getMatrixAt( i, _matrix$1 );
  16711. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  16712. // determine whether the batched geometry is within the frustum
  16713. let culled = false;
  16714. if ( perObjectFrustumCulled ) {
  16715. culled = ! _frustum.intersectsSphere( _sphere$2 );
  16716. }
  16717. if ( ! culled ) {
  16718. // get the distance from camera used for sorting
  16719. const geometryInfo = geometryInfoList[ geometryId ];
  16720. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  16721. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  16722. }
  16723. }
  16724. }
  16725. // Sort the draw ranges and prep for rendering
  16726. const list = _renderList.list;
  16727. const customSort = this.customSort;
  16728. if ( customSort === null ) {
  16729. list.sort( material.transparent ? sortTransparent : sortOpaque );
  16730. } else {
  16731. customSort.call( this, list, camera );
  16732. }
  16733. for ( let i = 0, l = list.length; i < l; i ++ ) {
  16734. const item = list[ i ];
  16735. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  16736. multiDrawCounts[ multiDrawCount ] = item.count;
  16737. indirectArray[ multiDrawCount ] = item.index;
  16738. multiDrawCount ++;
  16739. }
  16740. _renderList.reset();
  16741. } else {
  16742. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  16743. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  16744. const geometryId = instanceInfo[ i ].geometryIndex;
  16745. // determine whether the batched geometry is within the frustum
  16746. let culled = false;
  16747. if ( perObjectFrustumCulled ) {
  16748. // get the bounds in world space
  16749. this.getMatrixAt( i, _matrix$1 );
  16750. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  16751. culled = ! _frustum.intersectsSphere( _sphere$2 );
  16752. }
  16753. if ( ! culled ) {
  16754. const geometryInfo = geometryInfoList[ geometryId ];
  16755. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  16756. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  16757. indirectArray[ multiDrawCount ] = i;
  16758. multiDrawCount ++;
  16759. }
  16760. }
  16761. }
  16762. }
  16763. indirectTexture.needsUpdate = true;
  16764. this._multiDrawCount = multiDrawCount;
  16765. this._visibilityChanged = false;
  16766. }
  16767. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  16768. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  16769. }
  16770. }
  16771. class LineBasicMaterial extends Material {
  16772. constructor( parameters ) {
  16773. super();
  16774. this.isLineBasicMaterial = true;
  16775. this.type = 'LineBasicMaterial';
  16776. this.color = new Color( 0xffffff );
  16777. this.map = null;
  16778. this.linewidth = 1;
  16779. this.linecap = 'round';
  16780. this.linejoin = 'round';
  16781. this.fog = true;
  16782. this.setValues( parameters );
  16783. }
  16784. copy( source ) {
  16785. super.copy( source );
  16786. this.color.copy( source.color );
  16787. this.map = source.map;
  16788. this.linewidth = source.linewidth;
  16789. this.linecap = source.linecap;
  16790. this.linejoin = source.linejoin;
  16791. this.fog = source.fog;
  16792. return this;
  16793. }
  16794. }
  16795. const _vStart = /*@__PURE__*/ new Vector3();
  16796. const _vEnd = /*@__PURE__*/ new Vector3();
  16797. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  16798. const _ray$1 = /*@__PURE__*/ new Ray();
  16799. const _sphere$1 = /*@__PURE__*/ new Sphere();
  16800. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  16801. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  16802. /**
  16803. * A continuous line. The line are rendered by connecting consecutive
  16804. * vertices with straight lines.
  16805. *
  16806. * ```js
  16807. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  16808. *
  16809. * const points = [];
  16810. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  16811. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  16812. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  16813. *
  16814. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  16815. *
  16816. * const line = new THREE.Line( geometry, material );
  16817. * scene.add( line );
  16818. * ```
  16819. *
  16820. * @augments Object3D
  16821. */
  16822. class Line extends Object3D {
  16823. /**
  16824. * Constructs a new line.
  16825. *
  16826. * @param {BufferGeometry} [geometry] - The line geometry.
  16827. * @param {Material|Array<Material>} [material] - The line material.
  16828. */
  16829. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  16830. super();
  16831. /**
  16832. * This flag can be used for type testing.
  16833. *
  16834. * @type {boolean}
  16835. * @readonly
  16836. * @default true
  16837. */
  16838. this.isLine = true;
  16839. this.type = 'Line';
  16840. /**
  16841. * The line geometry.
  16842. *
  16843. * @type {BufferGeometry}
  16844. */
  16845. this.geometry = geometry;
  16846. /**
  16847. * The line material.
  16848. *
  16849. * @type {Material|Array<Material>}
  16850. * @default LineBasicMaterial
  16851. */
  16852. this.material = material;
  16853. /**
  16854. * A dictionary representing the morph targets in the geometry. The key is the
  16855. * morph targets name, the value its attribute index. This member is `undefined`
  16856. * by default and only set when morph targets are detected in the geometry.
  16857. *
  16858. * @type {Object<String,number>|undefined}
  16859. * @default undefined
  16860. */
  16861. this.morphTargetDictionary = undefined;
  16862. /**
  16863. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  16864. * is applied. This member is `undefined` by default and only set when morph targets are
  16865. * detected in the geometry.
  16866. *
  16867. * @type {Array<number>|undefined}
  16868. * @default undefined
  16869. */
  16870. this.morphTargetInfluences = undefined;
  16871. this.updateMorphTargets();
  16872. }
  16873. copy( source, recursive ) {
  16874. super.copy( source, recursive );
  16875. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  16876. this.geometry = source.geometry;
  16877. return this;
  16878. }
  16879. /**
  16880. * Computes an array of distance values which are necessary for rendering dashed lines.
  16881. * For each vertex in the geometry, the method calculates the cumulative length from the
  16882. * current point to the very beginning of the line.
  16883. *
  16884. * @return {Line} A reference to this line.
  16885. */
  16886. computeLineDistances() {
  16887. const geometry = this.geometry;
  16888. // we assume non-indexed geometry
  16889. if ( geometry.index === null ) {
  16890. const positionAttribute = geometry.attributes.position;
  16891. const lineDistances = [ 0 ];
  16892. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  16893. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  16894. _vEnd.fromBufferAttribute( positionAttribute, i );
  16895. lineDistances[ i ] = lineDistances[ i - 1 ];
  16896. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  16897. }
  16898. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16899. } else {
  16900. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16901. }
  16902. return this;
  16903. }
  16904. /**
  16905. * Computes intersection points between a casted ray and this line.
  16906. *
  16907. * @param {Raycaster} raycaster - The raycaster.
  16908. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16909. */
  16910. raycast( raycaster, intersects ) {
  16911. const geometry = this.geometry;
  16912. const matrixWorld = this.matrixWorld;
  16913. const threshold = raycaster.params.Line.threshold;
  16914. const drawRange = geometry.drawRange;
  16915. // Checking boundingSphere distance to ray
  16916. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16917. _sphere$1.copy( geometry.boundingSphere );
  16918. _sphere$1.applyMatrix4( matrixWorld );
  16919. _sphere$1.radius += threshold;
  16920. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  16921. //
  16922. _inverseMatrix$1.copy( matrixWorld ).invert();
  16923. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  16924. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16925. const localThresholdSq = localThreshold * localThreshold;
  16926. const step = this.isLineSegments ? 2 : 1;
  16927. const index = geometry.index;
  16928. const attributes = geometry.attributes;
  16929. const positionAttribute = attributes.position;
  16930. if ( index !== null ) {
  16931. const start = Math.max( 0, drawRange.start );
  16932. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  16933. for ( let i = start, l = end - 1; i < l; i += step ) {
  16934. const a = index.getX( i );
  16935. const b = index.getX( i + 1 );
  16936. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  16937. if ( intersect ) {
  16938. intersects.push( intersect );
  16939. }
  16940. }
  16941. if ( this.isLineLoop ) {
  16942. const a = index.getX( end - 1 );
  16943. const b = index.getX( start );
  16944. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  16945. if ( intersect ) {
  16946. intersects.push( intersect );
  16947. }
  16948. }
  16949. } else {
  16950. const start = Math.max( 0, drawRange.start );
  16951. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  16952. for ( let i = start, l = end - 1; i < l; i += step ) {
  16953. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  16954. if ( intersect ) {
  16955. intersects.push( intersect );
  16956. }
  16957. }
  16958. if ( this.isLineLoop ) {
  16959. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  16960. if ( intersect ) {
  16961. intersects.push( intersect );
  16962. }
  16963. }
  16964. }
  16965. }
  16966. /**
  16967. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  16968. * to make sure existing morph targets can influence this 3D object.
  16969. */
  16970. updateMorphTargets() {
  16971. const geometry = this.geometry;
  16972. const morphAttributes = geometry.morphAttributes;
  16973. const keys = Object.keys( morphAttributes );
  16974. if ( keys.length > 0 ) {
  16975. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16976. if ( morphAttribute !== undefined ) {
  16977. this.morphTargetInfluences = [];
  16978. this.morphTargetDictionary = {};
  16979. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16980. const name = morphAttribute[ m ].name || String( m );
  16981. this.morphTargetInfluences.push( 0 );
  16982. this.morphTargetDictionary[ name ] = m;
  16983. }
  16984. }
  16985. }
  16986. }
  16987. }
  16988. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  16989. const positionAttribute = object.geometry.attributes.position;
  16990. _vStart.fromBufferAttribute( positionAttribute, a );
  16991. _vEnd.fromBufferAttribute( positionAttribute, b );
  16992. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  16993. if ( distSq > thresholdSq ) return;
  16994. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  16995. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  16996. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16997. return {
  16998. distance: distance,
  16999. // What do we want? intersection point on the ray or on the segment??
  17000. // point: raycaster.ray.at( distance ),
  17001. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  17002. index: i,
  17003. face: null,
  17004. faceIndex: null,
  17005. barycoord: null,
  17006. object: object
  17007. };
  17008. }
  17009. const _start = /*@__PURE__*/ new Vector3();
  17010. const _end = /*@__PURE__*/ new Vector3();
  17011. /**
  17012. * A series of lines drawn between pairs of vertices.
  17013. *
  17014. * @augments Line
  17015. */
  17016. class LineSegments extends Line {
  17017. /**
  17018. * Constructs a new line segments.
  17019. *
  17020. * @param {BufferGeometry} [geometry] - The line geometry.
  17021. * @param {Material|Array<Material>} [material] - The line material.
  17022. */
  17023. constructor( geometry, material ) {
  17024. super( geometry, material );
  17025. /**
  17026. * This flag can be used for type testing.
  17027. *
  17028. * @type {boolean}
  17029. * @readonly
  17030. * @default true
  17031. */
  17032. this.isLineSegments = true;
  17033. this.type = 'LineSegments';
  17034. }
  17035. computeLineDistances() {
  17036. const geometry = this.geometry;
  17037. // we assume non-indexed geometry
  17038. if ( geometry.index === null ) {
  17039. const positionAttribute = geometry.attributes.position;
  17040. const lineDistances = [];
  17041. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  17042. _start.fromBufferAttribute( positionAttribute, i );
  17043. _end.fromBufferAttribute( positionAttribute, i + 1 );
  17044. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  17045. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  17046. }
  17047. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  17048. } else {
  17049. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  17050. }
  17051. return this;
  17052. }
  17053. }
  17054. /**
  17055. * A continuous line. This is nearly the same as {@link Line} the only difference
  17056. * is that the last vertex is connected with the first vertex in order to close
  17057. * the line to form a loop.
  17058. *
  17059. * @augments Line
  17060. */
  17061. class LineLoop extends Line {
  17062. /**
  17063. * Constructs a new line loop.
  17064. *
  17065. * @param {BufferGeometry} [geometry] - The line geometry.
  17066. * @param {Material|Array<Material>} [material] - The line material.
  17067. */
  17068. constructor( geometry, material ) {
  17069. super( geometry, material );
  17070. /**
  17071. * This flag can be used for type testing.
  17072. *
  17073. * @type {boolean}
  17074. * @readonly
  17075. * @default true
  17076. */
  17077. this.isLineLoop = true;
  17078. this.type = 'LineLoop';
  17079. }
  17080. }
  17081. class PointsMaterial extends Material {
  17082. constructor( parameters ) {
  17083. super();
  17084. this.isPointsMaterial = true;
  17085. this.type = 'PointsMaterial';
  17086. this.color = new Color( 0xffffff );
  17087. this.map = null;
  17088. this.alphaMap = null;
  17089. this.size = 1;
  17090. this.sizeAttenuation = true;
  17091. this.fog = true;
  17092. this.setValues( parameters );
  17093. }
  17094. copy( source ) {
  17095. super.copy( source );
  17096. this.color.copy( source.color );
  17097. this.map = source.map;
  17098. this.alphaMap = source.alphaMap;
  17099. this.size = source.size;
  17100. this.sizeAttenuation = source.sizeAttenuation;
  17101. this.fog = source.fog;
  17102. return this;
  17103. }
  17104. }
  17105. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  17106. const _ray = /*@__PURE__*/ new Ray();
  17107. const _sphere = /*@__PURE__*/ new Sphere();
  17108. const _position$2 = /*@__PURE__*/ new Vector3();
  17109. /**
  17110. * A class for displaying points or point clouds.
  17111. *
  17112. * @augments Object3D
  17113. */
  17114. class Points extends Object3D {
  17115. /**
  17116. * Constructs a new point cloud.
  17117. *
  17118. * @param {BufferGeometry} [geometry] - The points geometry.
  17119. * @param {Material|Array<Material>} [material] - The points material.
  17120. */
  17121. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  17122. super();
  17123. /**
  17124. * This flag can be used for type testing.
  17125. *
  17126. * @type {boolean}
  17127. * @readonly
  17128. * @default true
  17129. */
  17130. this.isPoints = true;
  17131. this.type = 'Points';
  17132. /**
  17133. * The points geometry.
  17134. *
  17135. * @type {BufferGeometry}
  17136. */
  17137. this.geometry = geometry;
  17138. /**
  17139. * The line material.
  17140. *
  17141. * @type {Material|Array<Material>}
  17142. * @default PointsMaterial
  17143. */
  17144. this.material = material;
  17145. /**
  17146. * A dictionary representing the morph targets in the geometry. The key is the
  17147. * morph targets name, the value its attribute index. This member is `undefined`
  17148. * by default and only set when morph targets are detected in the geometry.
  17149. *
  17150. * @type {Object<String,number>|undefined}
  17151. * @default undefined
  17152. */
  17153. this.morphTargetDictionary = undefined;
  17154. /**
  17155. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  17156. * is applied. This member is `undefined` by default and only set when morph targets are
  17157. * detected in the geometry.
  17158. *
  17159. * @type {Array<number>|undefined}
  17160. * @default undefined
  17161. */
  17162. this.morphTargetInfluences = undefined;
  17163. this.updateMorphTargets();
  17164. }
  17165. copy( source, recursive ) {
  17166. super.copy( source, recursive );
  17167. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  17168. this.geometry = source.geometry;
  17169. return this;
  17170. }
  17171. /**
  17172. * Computes intersection points between a casted ray and this point cloud.
  17173. *
  17174. * @param {Raycaster} raycaster - The raycaster.
  17175. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17176. */
  17177. raycast( raycaster, intersects ) {
  17178. const geometry = this.geometry;
  17179. const matrixWorld = this.matrixWorld;
  17180. const threshold = raycaster.params.Points.threshold;
  17181. const drawRange = geometry.drawRange;
  17182. // Checking boundingSphere distance to ray
  17183. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17184. _sphere.copy( geometry.boundingSphere );
  17185. _sphere.applyMatrix4( matrixWorld );
  17186. _sphere.radius += threshold;
  17187. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  17188. //
  17189. _inverseMatrix.copy( matrixWorld ).invert();
  17190. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  17191. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  17192. const localThresholdSq = localThreshold * localThreshold;
  17193. const index = geometry.index;
  17194. const attributes = geometry.attributes;
  17195. const positionAttribute = attributes.position;
  17196. if ( index !== null ) {
  17197. const start = Math.max( 0, drawRange.start );
  17198. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17199. for ( let i = start, il = end; i < il; i ++ ) {
  17200. const a = index.getX( i );
  17201. _position$2.fromBufferAttribute( positionAttribute, a );
  17202. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17203. }
  17204. } else {
  17205. const start = Math.max( 0, drawRange.start );
  17206. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  17207. for ( let i = start, l = end; i < l; i ++ ) {
  17208. _position$2.fromBufferAttribute( positionAttribute, i );
  17209. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17210. }
  17211. }
  17212. }
  17213. /**
  17214. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  17215. * to make sure existing morph targets can influence this 3D object.
  17216. */
  17217. updateMorphTargets() {
  17218. const geometry = this.geometry;
  17219. const morphAttributes = geometry.morphAttributes;
  17220. const keys = Object.keys( morphAttributes );
  17221. if ( keys.length > 0 ) {
  17222. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17223. if ( morphAttribute !== undefined ) {
  17224. this.morphTargetInfluences = [];
  17225. this.morphTargetDictionary = {};
  17226. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17227. const name = morphAttribute[ m ].name || String( m );
  17228. this.morphTargetInfluences.push( 0 );
  17229. this.morphTargetDictionary[ name ] = m;
  17230. }
  17231. }
  17232. }
  17233. }
  17234. }
  17235. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  17236. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  17237. if ( rayPointDistanceSq < localThresholdSq ) {
  17238. const intersectPoint = new Vector3();
  17239. _ray.closestPointToPoint( point, intersectPoint );
  17240. intersectPoint.applyMatrix4( matrixWorld );
  17241. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  17242. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17243. intersects.push( {
  17244. distance: distance,
  17245. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  17246. point: intersectPoint,
  17247. index: index,
  17248. face: null,
  17249. faceIndex: null,
  17250. barycoord: null,
  17251. object: object
  17252. } );
  17253. }
  17254. }
  17255. class VideoTexture extends Texture {
  17256. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17257. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17258. this.isVideoTexture = true;
  17259. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17260. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17261. this.generateMipmaps = false;
  17262. const scope = this;
  17263. function updateVideo() {
  17264. scope.needsUpdate = true;
  17265. video.requestVideoFrameCallback( updateVideo );
  17266. }
  17267. if ( 'requestVideoFrameCallback' in video ) {
  17268. video.requestVideoFrameCallback( updateVideo );
  17269. }
  17270. }
  17271. clone() {
  17272. return new this.constructor( this.image ).copy( this );
  17273. }
  17274. update() {
  17275. const video = this.image;
  17276. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  17277. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  17278. this.needsUpdate = true;
  17279. }
  17280. }
  17281. }
  17282. class VideoFrameTexture extends VideoTexture {
  17283. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17284. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17285. this.isVideoFrameTexture = true;
  17286. }
  17287. update() {
  17288. // overwrites `VideoTexture.update()` with an empty method since
  17289. // this type of texture is updated via `setFrame()`.
  17290. }
  17291. clone() {
  17292. return new this.constructor().copy( this ); // restoring Texture.clone()
  17293. }
  17294. setFrame( frame ) {
  17295. this.image = frame;
  17296. this.needsUpdate = true;
  17297. }
  17298. }
  17299. class FramebufferTexture extends Texture {
  17300. constructor( width, height ) {
  17301. super( { width, height } );
  17302. this.isFramebufferTexture = true;
  17303. this.magFilter = NearestFilter;
  17304. this.minFilter = NearestFilter;
  17305. this.generateMipmaps = false;
  17306. this.needsUpdate = true;
  17307. }
  17308. }
  17309. class CompressedTexture extends Texture {
  17310. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  17311. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  17312. this.isCompressedTexture = true;
  17313. this.image = { width: width, height: height };
  17314. this.mipmaps = mipmaps;
  17315. // no flipping for cube textures
  17316. // (also flipping doesn't work for compressed textures )
  17317. this.flipY = false;
  17318. // can't generate mipmaps for compressed textures
  17319. // mips must be embedded in DDS files
  17320. this.generateMipmaps = false;
  17321. }
  17322. }
  17323. class CompressedArrayTexture extends CompressedTexture {
  17324. constructor( mipmaps, width, height, depth, format, type ) {
  17325. super( mipmaps, width, height, format, type );
  17326. this.isCompressedArrayTexture = true;
  17327. this.image.depth = depth;
  17328. this.wrapR = ClampToEdgeWrapping;
  17329. this.layerUpdates = new Set();
  17330. }
  17331. addLayerUpdate( layerIndex ) {
  17332. this.layerUpdates.add( layerIndex );
  17333. }
  17334. clearLayerUpdates() {
  17335. this.layerUpdates.clear();
  17336. }
  17337. }
  17338. class CompressedCubeTexture extends CompressedTexture {
  17339. constructor( images, format, type ) {
  17340. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  17341. this.isCompressedCubeTexture = true;
  17342. this.isCubeTexture = true;
  17343. this.image = images;
  17344. }
  17345. }
  17346. class CanvasTexture extends Texture {
  17347. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17348. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17349. this.isCanvasTexture = true;
  17350. this.needsUpdate = true;
  17351. }
  17352. }
  17353. class DepthTexture extends Texture {
  17354. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  17355. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  17356. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  17357. }
  17358. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  17359. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  17360. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17361. this.isDepthTexture = true;
  17362. this.image = { width: width, height: height };
  17363. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17364. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17365. this.flipY = false;
  17366. this.generateMipmaps = false;
  17367. this.compareFunction = null;
  17368. }
  17369. copy( source ) {
  17370. super.copy( source );
  17371. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  17372. this.compareFunction = source.compareFunction;
  17373. return this;
  17374. }
  17375. toJSON( meta ) {
  17376. const data = super.toJSON( meta );
  17377. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  17378. return data;
  17379. }
  17380. }
  17381. /**
  17382. * An abstract base class for creating an analytic curve object that contains methods
  17383. * for interpolation.
  17384. *
  17385. * @abstract
  17386. */
  17387. class Curve {
  17388. /**
  17389. * Constructs a new curve.
  17390. */
  17391. constructor() {
  17392. /**
  17393. * The type property is used for detecting the object type
  17394. * in context of serialization/deserialization.
  17395. *
  17396. * @type {string}
  17397. * @readonly
  17398. */
  17399. this.type = 'Curve';
  17400. /**
  17401. * This value determines the amount of divisions when calculating the
  17402. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  17403. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  17404. * recommended to increase the value of this property if the curve is very large.
  17405. *
  17406. * @type {number}
  17407. * @default 200
  17408. */
  17409. this.arcLengthDivisions = 200;
  17410. /**
  17411. * Must be set to `true` if the curve parameters have changed.
  17412. *
  17413. * @type {boolean}
  17414. * @default false
  17415. */
  17416. this.needsUpdate = false;
  17417. /**
  17418. * An internal cache that holds precomputed curve length values.
  17419. *
  17420. * @private
  17421. * @type {?Array<number>}
  17422. * @default null
  17423. */
  17424. this.cacheArcLengths = null;
  17425. }
  17426. /**
  17427. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  17428. * for the given interpolation factor.
  17429. *
  17430. * @abstract
  17431. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17432. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  17433. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  17434. */
  17435. getPoint( /* t, optionalTarget */ ) {
  17436. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  17437. }
  17438. /**
  17439. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  17440. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  17441. * of the curve which equidistant samples.
  17442. *
  17443. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17444. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  17445. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  17446. */
  17447. getPointAt( u, optionalTarget ) {
  17448. const t = this.getUtoTmapping( u );
  17449. return this.getPoint( t, optionalTarget );
  17450. }
  17451. /**
  17452. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  17453. * the curve shape.
  17454. *
  17455. * @param {number} [divisions=5] - The number of divisions.
  17456. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  17457. */
  17458. getPoints( divisions = 5 ) {
  17459. const points = [];
  17460. for ( let d = 0; d <= divisions; d ++ ) {
  17461. points.push( this.getPoint( d / divisions ) );
  17462. }
  17463. return points;
  17464. }
  17465. // Get sequence of points using getPointAt( u )
  17466. /**
  17467. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  17468. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  17469. * curve.
  17470. *
  17471. * @param {number} [divisions=5] - The number of divisions.
  17472. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  17473. */
  17474. getSpacedPoints( divisions = 5 ) {
  17475. const points = [];
  17476. for ( let d = 0; d <= divisions; d ++ ) {
  17477. points.push( this.getPointAt( d / divisions ) );
  17478. }
  17479. return points;
  17480. }
  17481. /**
  17482. * Returns the total arc length of the curve.
  17483. *
  17484. * @return {number} The length of the curve.
  17485. */
  17486. getLength() {
  17487. const lengths = this.getLengths();
  17488. return lengths[ lengths.length - 1 ];
  17489. }
  17490. /**
  17491. * Returns an array of cumulative segment lengths of the curve.
  17492. *
  17493. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  17494. * @return {Array<number>} An array holding the cumulative segment lengths.
  17495. */
  17496. getLengths( divisions = this.arcLengthDivisions ) {
  17497. if ( this.cacheArcLengths &&
  17498. ( this.cacheArcLengths.length === divisions + 1 ) &&
  17499. ! this.needsUpdate ) {
  17500. return this.cacheArcLengths;
  17501. }
  17502. this.needsUpdate = false;
  17503. const cache = [];
  17504. let current, last = this.getPoint( 0 );
  17505. let sum = 0;
  17506. cache.push( 0 );
  17507. for ( let p = 1; p <= divisions; p ++ ) {
  17508. current = this.getPoint( p / divisions );
  17509. sum += current.distanceTo( last );
  17510. cache.push( sum );
  17511. last = current;
  17512. }
  17513. this.cacheArcLengths = cache;
  17514. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  17515. }
  17516. /**
  17517. * Update the cumulative segment distance cache. The method must be called
  17518. * every time curve parameters are changed. If an updated curve is part of a
  17519. * composed curve like {@link CurvePath}, this method must be called on the
  17520. * composed curve, too.
  17521. */
  17522. updateArcLengths() {
  17523. this.needsUpdate = true;
  17524. this.getLengths();
  17525. }
  17526. /**
  17527. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  17528. * interpolation factor in the same range that can be ued to sample equidistant points
  17529. * from a curve.
  17530. *
  17531. * @param {number} u - The interpolation factor.
  17532. * @param {?number} distance - An optional distance on the curve.
  17533. * @return {number} The updated interpolation factor.
  17534. */
  17535. getUtoTmapping( u, distance = null ) {
  17536. const arcLengths = this.getLengths();
  17537. let i = 0;
  17538. const il = arcLengths.length;
  17539. let targetArcLength; // The targeted u distance value to get
  17540. if ( distance ) {
  17541. targetArcLength = distance;
  17542. } else {
  17543. targetArcLength = u * arcLengths[ il - 1 ];
  17544. }
  17545. // binary search for the index with largest value smaller than target u distance
  17546. let low = 0, high = il - 1, comparison;
  17547. while ( low <= high ) {
  17548. 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
  17549. comparison = arcLengths[ i ] - targetArcLength;
  17550. if ( comparison < 0 ) {
  17551. low = i + 1;
  17552. } else if ( comparison > 0 ) {
  17553. high = i - 1;
  17554. } else {
  17555. high = i;
  17556. break;
  17557. // DONE
  17558. }
  17559. }
  17560. i = high;
  17561. if ( arcLengths[ i ] === targetArcLength ) {
  17562. return i / ( il - 1 );
  17563. }
  17564. // we could get finer grain at lengths, or use simple interpolation between two points
  17565. const lengthBefore = arcLengths[ i ];
  17566. const lengthAfter = arcLengths[ i + 1 ];
  17567. const segmentLength = lengthAfter - lengthBefore;
  17568. // determine where we are between the 'before' and 'after' points
  17569. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17570. // add that fractional amount to t
  17571. const t = ( i + segmentFraction ) / ( il - 1 );
  17572. return t;
  17573. }
  17574. /**
  17575. * Returns a unit vector tangent for the given interpolation factor.
  17576. * If the derived curve does not implement its tangent derivation,
  17577. * two points a small delta apart will be used to find its gradient
  17578. * which seems to give a reasonable approximation.
  17579. *
  17580. * @param {number} t - The interpolation factor.
  17581. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  17582. * @return {(Vector2|Vector3)} The tangent vector.
  17583. */
  17584. getTangent( t, optionalTarget ) {
  17585. const delta = 0.0001;
  17586. let t1 = t - delta;
  17587. let t2 = t + delta;
  17588. // Capping in case of danger
  17589. if ( t1 < 0 ) t1 = 0;
  17590. if ( t2 > 1 ) t2 = 1;
  17591. const pt1 = this.getPoint( t1 );
  17592. const pt2 = this.getPoint( t2 );
  17593. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  17594. tangent.copy( pt2 ).sub( pt1 ).normalize();
  17595. return tangent;
  17596. }
  17597. /**
  17598. * Same as {@link Curve#getTangent} but with equidistant samples.
  17599. *
  17600. * @param {number} u - The interpolation factor.
  17601. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  17602. * @return {(Vector2|Vector3)} The tangent vector.
  17603. * @see {@link Curve#getPointAt}
  17604. */
  17605. getTangentAt( u, optionalTarget ) {
  17606. const t = this.getUtoTmapping( u );
  17607. return this.getTangent( t, optionalTarget );
  17608. }
  17609. /**
  17610. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  17611. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  17612. *
  17613. * @param {number} segments - The number of segments.
  17614. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  17615. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  17616. */
  17617. computeFrenetFrames( segments, closed = false ) {
  17618. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  17619. const normal = new Vector3();
  17620. const tangents = [];
  17621. const normals = [];
  17622. const binormals = [];
  17623. const vec = new Vector3();
  17624. const mat = new Matrix4();
  17625. // compute the tangent vectors for each segment on the curve
  17626. for ( let i = 0; i <= segments; i ++ ) {
  17627. const u = i / segments;
  17628. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  17629. }
  17630. // select an initial normal vector perpendicular to the first tangent vector,
  17631. // and in the direction of the minimum tangent xyz component
  17632. normals[ 0 ] = new Vector3();
  17633. binormals[ 0 ] = new Vector3();
  17634. let min = Number.MAX_VALUE;
  17635. const tx = Math.abs( tangents[ 0 ].x );
  17636. const ty = Math.abs( tangents[ 0 ].y );
  17637. const tz = Math.abs( tangents[ 0 ].z );
  17638. if ( tx <= min ) {
  17639. min = tx;
  17640. normal.set( 1, 0, 0 );
  17641. }
  17642. if ( ty <= min ) {
  17643. min = ty;
  17644. normal.set( 0, 1, 0 );
  17645. }
  17646. if ( tz <= min ) {
  17647. normal.set( 0, 0, 1 );
  17648. }
  17649. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  17650. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  17651. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  17652. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  17653. for ( let i = 1; i <= segments; i ++ ) {
  17654. normals[ i ] = normals[ i - 1 ].clone();
  17655. binormals[ i ] = binormals[ i - 1 ].clone();
  17656. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  17657. if ( vec.length() > Number.EPSILON ) {
  17658. vec.normalize();
  17659. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  17660. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  17661. }
  17662. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  17663. }
  17664. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  17665. if ( closed === true ) {
  17666. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  17667. theta /= segments;
  17668. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  17669. theta = - theta;
  17670. }
  17671. for ( let i = 1; i <= segments; i ++ ) {
  17672. // twist a little...
  17673. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  17674. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  17675. }
  17676. }
  17677. return {
  17678. tangents: tangents,
  17679. normals: normals,
  17680. binormals: binormals
  17681. };
  17682. }
  17683. /**
  17684. * Returns a new curve with copied values from this instance.
  17685. *
  17686. * @return {Curve} A clone of this instance.
  17687. */
  17688. clone() {
  17689. return new this.constructor().copy( this );
  17690. }
  17691. /**
  17692. * Copies the values of the given curve to this instance.
  17693. *
  17694. * @param {Curve} source - The curve to copy.
  17695. * @return {Curve} A reference to this curve.
  17696. */
  17697. copy( source ) {
  17698. this.arcLengthDivisions = source.arcLengthDivisions;
  17699. return this;
  17700. }
  17701. /**
  17702. * Serializes the curve into JSON.
  17703. *
  17704. * @return {Object} A JSON object representing the serialized curve.
  17705. * @see {@link ObjectLoader#parse}
  17706. */
  17707. toJSON() {
  17708. const data = {
  17709. metadata: {
  17710. version: 4.6,
  17711. type: 'Curve',
  17712. generator: 'Curve.toJSON'
  17713. }
  17714. };
  17715. data.arcLengthDivisions = this.arcLengthDivisions;
  17716. data.type = this.type;
  17717. return data;
  17718. }
  17719. /**
  17720. * Deserializes the curve from the given JSON.
  17721. *
  17722. * @param {Object} json - The JSON holding the serialized curve.
  17723. * @return {Curve} A reference to this curve.
  17724. */
  17725. fromJSON( json ) {
  17726. this.arcLengthDivisions = json.arcLengthDivisions;
  17727. return this;
  17728. }
  17729. }
  17730. /**
  17731. * A curve representing an ellipse.
  17732. *
  17733. * ```js
  17734. * const curve = new THREE.EllipseCurve(
  17735. * 0, 0,
  17736. * 10, 10,
  17737. * 0, 2 * Math.PI,
  17738. * false,
  17739. * 0
  17740. * );
  17741. *
  17742. * const points = curve.getPoints( 50 );
  17743. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  17744. *
  17745. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  17746. *
  17747. * // Create the final object to add to the scene
  17748. * const ellipse = new THREE.Line( geometry, material );
  17749. * ```
  17750. *
  17751. * @augments Curve
  17752. */
  17753. class EllipseCurve extends Curve {
  17754. /**
  17755. * Constructs a new ellipse curve.
  17756. *
  17757. * @param {number} [aX=0] - The X center of the ellipse.
  17758. * @param {number} [aY=0] - The Y center of the ellipse.
  17759. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  17760. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  17761. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  17762. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  17763. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  17764. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  17765. */
  17766. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  17767. super();
  17768. /**
  17769. * This flag can be used for type testing.
  17770. *
  17771. * @type {boolean}
  17772. * @readonly
  17773. * @default true
  17774. */
  17775. this.isEllipseCurve = true;
  17776. this.type = 'EllipseCurve';
  17777. /**
  17778. * The X center of the ellipse.
  17779. *
  17780. * @type {number}
  17781. * @default 0
  17782. */
  17783. this.aX = aX;
  17784. /**
  17785. * The Y center of the ellipse.
  17786. *
  17787. * @type {number}
  17788. * @default 0
  17789. */
  17790. this.aY = aY;
  17791. /**
  17792. * The radius of the ellipse in the x direction.
  17793. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  17794. *
  17795. * @type {number}
  17796. * @default 1
  17797. */
  17798. this.xRadius = xRadius;
  17799. /**
  17800. * The radius of the ellipse in the y direction.
  17801. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  17802. *
  17803. * @type {number}
  17804. * @default 1
  17805. */
  17806. this.yRadius = yRadius;
  17807. /**
  17808. * The start angle of the curve in radians starting from the positive X axis.
  17809. *
  17810. * @type {number}
  17811. * @default 0
  17812. */
  17813. this.aStartAngle = aStartAngle;
  17814. /**
  17815. * The end angle of the curve in radians starting from the positive X axis.
  17816. *
  17817. * @type {number}
  17818. * @default Math.PI*2
  17819. */
  17820. this.aEndAngle = aEndAngle;
  17821. /**
  17822. * Whether the ellipse is drawn clockwise or not.
  17823. *
  17824. * @type {boolean}
  17825. * @default false
  17826. */
  17827. this.aClockwise = aClockwise;
  17828. /**
  17829. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  17830. *
  17831. * @type {number}
  17832. * @default 0
  17833. */
  17834. this.aRotation = aRotation;
  17835. }
  17836. /**
  17837. * Returns a point on the curve.
  17838. *
  17839. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17840. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  17841. * @return {Vector2} The position on the curve.
  17842. */
  17843. getPoint( t, optionalTarget = new Vector2() ) {
  17844. const point = optionalTarget;
  17845. const twoPi = Math.PI * 2;
  17846. let deltaAngle = this.aEndAngle - this.aStartAngle;
  17847. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  17848. // ensures that deltaAngle is 0 .. 2 PI
  17849. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  17850. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  17851. if ( deltaAngle < Number.EPSILON ) {
  17852. if ( samePoints ) {
  17853. deltaAngle = 0;
  17854. } else {
  17855. deltaAngle = twoPi;
  17856. }
  17857. }
  17858. if ( this.aClockwise === true && ! samePoints ) {
  17859. if ( deltaAngle === twoPi ) {
  17860. deltaAngle = - twoPi;
  17861. } else {
  17862. deltaAngle = deltaAngle - twoPi;
  17863. }
  17864. }
  17865. const angle = this.aStartAngle + t * deltaAngle;
  17866. let x = this.aX + this.xRadius * Math.cos( angle );
  17867. let y = this.aY + this.yRadius * Math.sin( angle );
  17868. if ( this.aRotation !== 0 ) {
  17869. const cos = Math.cos( this.aRotation );
  17870. const sin = Math.sin( this.aRotation );
  17871. const tx = x - this.aX;
  17872. const ty = y - this.aY;
  17873. // Rotate the point about the center of the ellipse.
  17874. x = tx * cos - ty * sin + this.aX;
  17875. y = tx * sin + ty * cos + this.aY;
  17876. }
  17877. return point.set( x, y );
  17878. }
  17879. copy( source ) {
  17880. super.copy( source );
  17881. this.aX = source.aX;
  17882. this.aY = source.aY;
  17883. this.xRadius = source.xRadius;
  17884. this.yRadius = source.yRadius;
  17885. this.aStartAngle = source.aStartAngle;
  17886. this.aEndAngle = source.aEndAngle;
  17887. this.aClockwise = source.aClockwise;
  17888. this.aRotation = source.aRotation;
  17889. return this;
  17890. }
  17891. toJSON() {
  17892. const data = super.toJSON();
  17893. data.aX = this.aX;
  17894. data.aY = this.aY;
  17895. data.xRadius = this.xRadius;
  17896. data.yRadius = this.yRadius;
  17897. data.aStartAngle = this.aStartAngle;
  17898. data.aEndAngle = this.aEndAngle;
  17899. data.aClockwise = this.aClockwise;
  17900. data.aRotation = this.aRotation;
  17901. return data;
  17902. }
  17903. fromJSON( json ) {
  17904. super.fromJSON( json );
  17905. this.aX = json.aX;
  17906. this.aY = json.aY;
  17907. this.xRadius = json.xRadius;
  17908. this.yRadius = json.yRadius;
  17909. this.aStartAngle = json.aStartAngle;
  17910. this.aEndAngle = json.aEndAngle;
  17911. this.aClockwise = json.aClockwise;
  17912. this.aRotation = json.aRotation;
  17913. return this;
  17914. }
  17915. }
  17916. /**
  17917. * A curve representing an arc.
  17918. *
  17919. * @augments EllipseCurve
  17920. */
  17921. class ArcCurve extends EllipseCurve {
  17922. /**
  17923. * Constructs a new arc curve.
  17924. *
  17925. * @param {number} [aX=0] - The X center of the ellipse.
  17926. * @param {number} [aY=0] - The Y center of the ellipse.
  17927. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  17928. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  17929. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  17930. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  17931. */
  17932. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17933. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17934. /**
  17935. * This flag can be used for type testing.
  17936. *
  17937. * @type {boolean}
  17938. * @readonly
  17939. * @default true
  17940. */
  17941. this.isArcCurve = true;
  17942. this.type = 'ArcCurve';
  17943. }
  17944. }
  17945. function CubicPoly() {
  17946. /**
  17947. * Centripetal CatmullRom Curve - which is useful for avoiding
  17948. * cusps and self-intersections in non-uniform catmull rom curves.
  17949. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  17950. *
  17951. * curve.type accepts centripetal(default), chordal and catmullrom
  17952. * curve.tension is used for catmullrom which defaults to 0.5
  17953. */
  17954. /*
  17955. Based on an optimized c++ solution in
  17956. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  17957. - http://ideone.com/NoEbVM
  17958. This CubicPoly class could be used for reusing some variables and calculations,
  17959. but for three.js curve use, it could be possible inlined and flatten into a single function call
  17960. which can be placed in CurveUtils.
  17961. */
  17962. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  17963. /*
  17964. * Compute coefficients for a cubic polynomial
  17965. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  17966. * such that
  17967. * p(0) = x0, p(1) = x1
  17968. * and
  17969. * p'(0) = t0, p'(1) = t1.
  17970. */
  17971. function init( x0, x1, t0, t1 ) {
  17972. c0 = x0;
  17973. c1 = t0;
  17974. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  17975. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  17976. }
  17977. return {
  17978. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  17979. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  17980. },
  17981. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  17982. // compute tangents when parameterized in [t1,t2]
  17983. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  17984. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  17985. // rescale tangents for parametrization in [0,1]
  17986. t1 *= dt1;
  17987. t2 *= dt1;
  17988. init( x1, x2, t1, t2 );
  17989. },
  17990. calc: function ( t ) {
  17991. const t2 = t * t;
  17992. const t3 = t2 * t;
  17993. return c0 + c1 * t + c2 * t2 + c3 * t3;
  17994. }
  17995. };
  17996. }
  17997. //
  17998. const tmp = /*@__PURE__*/ new Vector3();
  17999. const px = /*@__PURE__*/ new CubicPoly();
  18000. const py = /*@__PURE__*/ new CubicPoly();
  18001. const pz = /*@__PURE__*/ new CubicPoly();
  18002. /**
  18003. * A curve representing a Catmull-Rom spline.
  18004. *
  18005. * ```js
  18006. * //Create a closed wavey loop
  18007. * const curve = new THREE.CatmullRomCurve3( [
  18008. * new THREE.Vector3( -10, 0, 10 ),
  18009. * new THREE.Vector3( -5, 5, 5 ),
  18010. * new THREE.Vector3( 0, 0, 0 ),
  18011. * new THREE.Vector3( 5, -5, 5 ),
  18012. * new THREE.Vector3( 10, 0, 10 )
  18013. * ] );
  18014. *
  18015. * const points = curve.getPoints( 50 );
  18016. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  18017. *
  18018. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  18019. *
  18020. * // Create the final object to add to the scene
  18021. * const curveObject = new THREE.Line( geometry, material );
  18022. * ```
  18023. *
  18024. * @augments Curve
  18025. */
  18026. class CatmullRomCurve3 extends Curve {
  18027. /**
  18028. * Constructs a new Catmull-Rom curve.
  18029. *
  18030. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  18031. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  18032. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  18033. * @param {number} [tension=0.5] - Tension of the curve.
  18034. */
  18035. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  18036. super();
  18037. /**
  18038. * This flag can be used for type testing.
  18039. *
  18040. * @type {boolean}
  18041. * @readonly
  18042. * @default true
  18043. */
  18044. this.isCatmullRomCurve3 = true;
  18045. this.type = 'CatmullRomCurve3';
  18046. /**
  18047. * An array of 3D points defining the curve.
  18048. *
  18049. * @type {Array<Vector3>}
  18050. */
  18051. this.points = points;
  18052. /**
  18053. * Whether the curve is closed or not.
  18054. *
  18055. * @type {boolean}
  18056. * @default false
  18057. */
  18058. this.closed = closed;
  18059. /**
  18060. * The curve type.
  18061. *
  18062. * @type {('centripetal'|'chordal'|'catmullrom')}
  18063. * @default 'centripetal'
  18064. */
  18065. this.curveType = curveType;
  18066. /**
  18067. * Tension of the curve.
  18068. *
  18069. * @type {number}
  18070. * @default 0.5
  18071. */
  18072. this.tension = tension;
  18073. }
  18074. /**
  18075. * Returns a point on the curve.
  18076. *
  18077. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18078. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  18079. * @return {Vector3} The position on the curve.
  18080. */
  18081. getPoint( t, optionalTarget = new Vector3() ) {
  18082. const point = optionalTarget;
  18083. const points = this.points;
  18084. const l = points.length;
  18085. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  18086. let intPoint = Math.floor( p );
  18087. let weight = p - intPoint;
  18088. if ( this.closed ) {
  18089. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  18090. } else if ( weight === 0 && intPoint === l - 1 ) {
  18091. intPoint = l - 2;
  18092. weight = 1;
  18093. }
  18094. let p0, p3; // 4 points (p1 & p2 defined below)
  18095. if ( this.closed || intPoint > 0 ) {
  18096. p0 = points[ ( intPoint - 1 ) % l ];
  18097. } else {
  18098. // extrapolate first point
  18099. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  18100. p0 = tmp;
  18101. }
  18102. const p1 = points[ intPoint % l ];
  18103. const p2 = points[ ( intPoint + 1 ) % l ];
  18104. if ( this.closed || intPoint + 2 < l ) {
  18105. p3 = points[ ( intPoint + 2 ) % l ];
  18106. } else {
  18107. // extrapolate last point
  18108. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  18109. p3 = tmp;
  18110. }
  18111. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  18112. // init Centripetal / Chordal Catmull-Rom
  18113. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18114. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  18115. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  18116. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  18117. // safety check for repeated points
  18118. if ( dt1 < 1e-4 ) dt1 = 1.0;
  18119. if ( dt0 < 1e-4 ) dt0 = dt1;
  18120. if ( dt2 < 1e-4 ) dt2 = dt1;
  18121. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  18122. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  18123. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  18124. } else if ( this.curveType === 'catmullrom' ) {
  18125. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  18126. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  18127. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  18128. }
  18129. point.set(
  18130. px.calc( weight ),
  18131. py.calc( weight ),
  18132. pz.calc( weight )
  18133. );
  18134. return point;
  18135. }
  18136. copy( source ) {
  18137. super.copy( source );
  18138. this.points = [];
  18139. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18140. const point = source.points[ i ];
  18141. this.points.push( point.clone() );
  18142. }
  18143. this.closed = source.closed;
  18144. this.curveType = source.curveType;
  18145. this.tension = source.tension;
  18146. return this;
  18147. }
  18148. toJSON() {
  18149. const data = super.toJSON();
  18150. data.points = [];
  18151. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18152. const point = this.points[ i ];
  18153. data.points.push( point.toArray() );
  18154. }
  18155. data.closed = this.closed;
  18156. data.curveType = this.curveType;
  18157. data.tension = this.tension;
  18158. return data;
  18159. }
  18160. fromJSON( json ) {
  18161. super.fromJSON( json );
  18162. this.points = [];
  18163. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18164. const point = json.points[ i ];
  18165. this.points.push( new Vector3().fromArray( point ) );
  18166. }
  18167. this.closed = json.closed;
  18168. this.curveType = json.curveType;
  18169. this.tension = json.tension;
  18170. return this;
  18171. }
  18172. }
  18173. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18174. /**
  18175. * Computes a point on a Catmull-Rom spline.
  18176. *
  18177. * @param {number} t - The interpolation factor.
  18178. * @param {number} p0 - The first control point.
  18179. * @param {number} p1 - The second control point.
  18180. * @param {number} p2 - The third control point.
  18181. * @param {number} p3 - The fourth control point.
  18182. * @return {number} The calculated point on a Catmull-Rom spline.
  18183. */
  18184. function CatmullRom( t, p0, p1, p2, p3 ) {
  18185. const v0 = ( p2 - p0 ) * 0.5;
  18186. const v1 = ( p3 - p1 ) * 0.5;
  18187. const t2 = t * t;
  18188. const t3 = t * t2;
  18189. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18190. }
  18191. //
  18192. function QuadraticBezierP0( t, p ) {
  18193. const k = 1 - t;
  18194. return k * k * p;
  18195. }
  18196. function QuadraticBezierP1( t, p ) {
  18197. return 2 * ( 1 - t ) * t * p;
  18198. }
  18199. function QuadraticBezierP2( t, p ) {
  18200. return t * t * p;
  18201. }
  18202. /**
  18203. * Computes a point on a Quadratic Bezier curve.
  18204. *
  18205. * @param {number} t - The interpolation factor.
  18206. * @param {number} p0 - The first control point.
  18207. * @param {number} p1 - The second control point.
  18208. * @param {number} p2 - The third control point.
  18209. * @return {number} The calculated point on a Quadratic Bezier curve.
  18210. */
  18211. function QuadraticBezier( t, p0, p1, p2 ) {
  18212. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  18213. QuadraticBezierP2( t, p2 );
  18214. }
  18215. //
  18216. function CubicBezierP0( t, p ) {
  18217. const k = 1 - t;
  18218. return k * k * k * p;
  18219. }
  18220. function CubicBezierP1( t, p ) {
  18221. const k = 1 - t;
  18222. return 3 * k * k * t * p;
  18223. }
  18224. function CubicBezierP2( t, p ) {
  18225. return 3 * ( 1 - t ) * t * t * p;
  18226. }
  18227. function CubicBezierP3( t, p ) {
  18228. return t * t * t * p;
  18229. }
  18230. /**
  18231. * Computes a point on a Cubic Bezier curve.
  18232. *
  18233. * @param {number} t - The interpolation factor.
  18234. * @param {number} p0 - The first control point.
  18235. * @param {number} p1 - The second control point.
  18236. * @param {number} p2 - The third control point.
  18237. * @param {number} p3 - The fourth control point.
  18238. * @return {number} The calculated point on a Cubic Bezier curve.
  18239. */
  18240. function CubicBezier( t, p0, p1, p2, p3 ) {
  18241. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  18242. CubicBezierP3( t, p3 );
  18243. }
  18244. /**
  18245. * A curve representing a 2D Cubic Bezier curve.
  18246. *
  18247. * ```js
  18248. * const curve = new THREE.CubicBezierCurve(
  18249. * new THREE.Vector2( - 0, 0 ),
  18250. * new THREE.Vector2( - 5, 15 ),
  18251. * new THREE.Vector2( 20, 15 ),
  18252. * new THREE.Vector2( 10, 0 )
  18253. * );
  18254. *
  18255. * const points = curve.getPoints( 50 );
  18256. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  18257. *
  18258. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  18259. *
  18260. * // Create the final object to add to the scene
  18261. * const curveObject = new THREE.Line( geometry, material );
  18262. * ```
  18263. *
  18264. * @augments Curve
  18265. */
  18266. class CubicBezierCurve extends Curve {
  18267. /**
  18268. * Constructs a new Cubic Bezier curve.
  18269. *
  18270. * @param {Vector2} [v0] - The start point.
  18271. * @param {Vector2} [v1] - The first control point.
  18272. * @param {Vector2} [v2] - The second control point.
  18273. * @param {Vector2} [v3] - The end point.
  18274. */
  18275. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  18276. super();
  18277. /**
  18278. * This flag can be used for type testing.
  18279. *
  18280. * @type {boolean}
  18281. * @readonly
  18282. * @default true
  18283. */
  18284. this.isCubicBezierCurve = true;
  18285. this.type = 'CubicBezierCurve';
  18286. /**
  18287. * The start point.
  18288. *
  18289. * @type {Vector2}
  18290. */
  18291. this.v0 = v0;
  18292. /**
  18293. * The first control point.
  18294. *
  18295. * @type {Vector2}
  18296. */
  18297. this.v1 = v1;
  18298. /**
  18299. * The second control point.
  18300. *
  18301. * @type {Vector2}
  18302. */
  18303. this.v2 = v2;
  18304. /**
  18305. * The end point.
  18306. *
  18307. * @type {Vector2}
  18308. */
  18309. this.v3 = v3;
  18310. }
  18311. /**
  18312. * Returns a point on the curve.
  18313. *
  18314. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18315. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  18316. * @return {Vector2} The position on the curve.
  18317. */
  18318. getPoint( t, optionalTarget = new Vector2() ) {
  18319. const point = optionalTarget;
  18320. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18321. point.set(
  18322. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18323. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  18324. );
  18325. return point;
  18326. }
  18327. copy( source ) {
  18328. super.copy( source );
  18329. this.v0.copy( source.v0 );
  18330. this.v1.copy( source.v1 );
  18331. this.v2.copy( source.v2 );
  18332. this.v3.copy( source.v3 );
  18333. return this;
  18334. }
  18335. toJSON() {
  18336. const data = super.toJSON();
  18337. data.v0 = this.v0.toArray();
  18338. data.v1 = this.v1.toArray();
  18339. data.v2 = this.v2.toArray();
  18340. data.v3 = this.v3.toArray();
  18341. return data;
  18342. }
  18343. fromJSON( json ) {
  18344. super.fromJSON( json );
  18345. this.v0.fromArray( json.v0 );
  18346. this.v1.fromArray( json.v1 );
  18347. this.v2.fromArray( json.v2 );
  18348. this.v3.fromArray( json.v3 );
  18349. return this;
  18350. }
  18351. }
  18352. /**
  18353. * A curve representing a 3D Cubic Bezier curve.
  18354. *
  18355. * @augments Curve
  18356. */
  18357. class CubicBezierCurve3 extends Curve {
  18358. /**
  18359. * Constructs a new Cubic Bezier curve.
  18360. *
  18361. * @param {Vector3} [v0] - The start point.
  18362. * @param {Vector3} [v1] - The first control point.
  18363. * @param {Vector3} [v2] - The second control point.
  18364. * @param {Vector3} [v3] - The end point.
  18365. */
  18366. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  18367. super();
  18368. /**
  18369. * This flag can be used for type testing.
  18370. *
  18371. * @type {boolean}
  18372. * @readonly
  18373. * @default true
  18374. */
  18375. this.isCubicBezierCurve3 = true;
  18376. this.type = 'CubicBezierCurve3';
  18377. /**
  18378. * The start point.
  18379. *
  18380. * @type {Vector3}
  18381. */
  18382. this.v0 = v0;
  18383. /**
  18384. * The first control point.
  18385. *
  18386. * @type {Vector3}
  18387. */
  18388. this.v1 = v1;
  18389. /**
  18390. * The second control point.
  18391. *
  18392. * @type {Vector3}
  18393. */
  18394. this.v2 = v2;
  18395. /**
  18396. * The end point.
  18397. *
  18398. * @type {Vector3}
  18399. */
  18400. this.v3 = v3;
  18401. }
  18402. /**
  18403. * Returns a point on the curve.
  18404. *
  18405. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18406. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  18407. * @return {Vector3} The position on the curve.
  18408. */
  18409. getPoint( t, optionalTarget = new Vector3() ) {
  18410. const point = optionalTarget;
  18411. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18412. point.set(
  18413. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18414. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  18415. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  18416. );
  18417. return point;
  18418. }
  18419. copy( source ) {
  18420. super.copy( source );
  18421. this.v0.copy( source.v0 );
  18422. this.v1.copy( source.v1 );
  18423. this.v2.copy( source.v2 );
  18424. this.v3.copy( source.v3 );
  18425. return this;
  18426. }
  18427. toJSON() {
  18428. const data = super.toJSON();
  18429. data.v0 = this.v0.toArray();
  18430. data.v1 = this.v1.toArray();
  18431. data.v2 = this.v2.toArray();
  18432. data.v3 = this.v3.toArray();
  18433. return data;
  18434. }
  18435. fromJSON( json ) {
  18436. super.fromJSON( json );
  18437. this.v0.fromArray( json.v0 );
  18438. this.v1.fromArray( json.v1 );
  18439. this.v2.fromArray( json.v2 );
  18440. this.v3.fromArray( json.v3 );
  18441. return this;
  18442. }
  18443. }
  18444. /**
  18445. * A curve representing a 2D line segment.
  18446. *
  18447. * @augments Curve
  18448. */
  18449. class LineCurve extends Curve {
  18450. /**
  18451. * Constructs a new line curve.
  18452. *
  18453. * @param {Vector2} [v1] - The start point.
  18454. * @param {Vector2} [v2] - The end point.
  18455. */
  18456. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  18457. super();
  18458. /**
  18459. * This flag can be used for type testing.
  18460. *
  18461. * @type {boolean}
  18462. * @readonly
  18463. * @default true
  18464. */
  18465. this.isLineCurve = true;
  18466. this.type = 'LineCurve';
  18467. /**
  18468. * The start point.
  18469. *
  18470. * @type {Vector2}
  18471. */
  18472. this.v1 = v1;
  18473. /**
  18474. * The end point.
  18475. *
  18476. * @type {Vector2}
  18477. */
  18478. this.v2 = v2;
  18479. }
  18480. /**
  18481. * Returns a point on the line.
  18482. *
  18483. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  18484. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  18485. * @return {Vector2} The position on the line.
  18486. */
  18487. getPoint( t, optionalTarget = new Vector2() ) {
  18488. const point = optionalTarget;
  18489. if ( t === 1 ) {
  18490. point.copy( this.v2 );
  18491. } else {
  18492. point.copy( this.v2 ).sub( this.v1 );
  18493. point.multiplyScalar( t ).add( this.v1 );
  18494. }
  18495. return point;
  18496. }
  18497. // Line curve is linear, so we can overwrite default getPointAt
  18498. getPointAt( u, optionalTarget ) {
  18499. return this.getPoint( u, optionalTarget );
  18500. }
  18501. getTangent( t, optionalTarget = new Vector2() ) {
  18502. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  18503. }
  18504. getTangentAt( u, optionalTarget ) {
  18505. return this.getTangent( u, optionalTarget );
  18506. }
  18507. copy( source ) {
  18508. super.copy( source );
  18509. this.v1.copy( source.v1 );
  18510. this.v2.copy( source.v2 );
  18511. return this;
  18512. }
  18513. toJSON() {
  18514. const data = super.toJSON();
  18515. data.v1 = this.v1.toArray();
  18516. data.v2 = this.v2.toArray();
  18517. return data;
  18518. }
  18519. fromJSON( json ) {
  18520. super.fromJSON( json );
  18521. this.v1.fromArray( json.v1 );
  18522. this.v2.fromArray( json.v2 );
  18523. return this;
  18524. }
  18525. }
  18526. /**
  18527. * A curve representing a 3D line segment.
  18528. *
  18529. * @augments Curve
  18530. */
  18531. class LineCurve3 extends Curve {
  18532. /**
  18533. * Constructs a new line curve.
  18534. *
  18535. * @param {Vector3} [v1] - The start point.
  18536. * @param {Vector3} [v2] - The end point.
  18537. */
  18538. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  18539. super();
  18540. /**
  18541. * This flag can be used for type testing.
  18542. *
  18543. * @type {boolean}
  18544. * @readonly
  18545. * @default true
  18546. */
  18547. this.isLineCurve3 = true;
  18548. this.type = 'LineCurve3';
  18549. /**
  18550. * The start point.
  18551. *
  18552. * @type {Vector3}
  18553. */
  18554. this.v1 = v1;
  18555. /**
  18556. * The end point.
  18557. *
  18558. * @type {Vector2}
  18559. */
  18560. this.v2 = v2;
  18561. }
  18562. /**
  18563. * Returns a point on the line.
  18564. *
  18565. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  18566. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  18567. * @return {Vector3} The position on the line.
  18568. */
  18569. getPoint( t, optionalTarget = new Vector3() ) {
  18570. const point = optionalTarget;
  18571. if ( t === 1 ) {
  18572. point.copy( this.v2 );
  18573. } else {
  18574. point.copy( this.v2 ).sub( this.v1 );
  18575. point.multiplyScalar( t ).add( this.v1 );
  18576. }
  18577. return point;
  18578. }
  18579. // Line curve is linear, so we can overwrite default getPointAt
  18580. getPointAt( u, optionalTarget ) {
  18581. return this.getPoint( u, optionalTarget );
  18582. }
  18583. getTangent( t, optionalTarget = new Vector3() ) {
  18584. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  18585. }
  18586. getTangentAt( u, optionalTarget ) {
  18587. return this.getTangent( u, optionalTarget );
  18588. }
  18589. copy( source ) {
  18590. super.copy( source );
  18591. this.v1.copy( source.v1 );
  18592. this.v2.copy( source.v2 );
  18593. return this;
  18594. }
  18595. toJSON() {
  18596. const data = super.toJSON();
  18597. data.v1 = this.v1.toArray();
  18598. data.v2 = this.v2.toArray();
  18599. return data;
  18600. }
  18601. fromJSON( json ) {
  18602. super.fromJSON( json );
  18603. this.v1.fromArray( json.v1 );
  18604. this.v2.fromArray( json.v2 );
  18605. return this;
  18606. }
  18607. }
  18608. /**
  18609. * A curve representing a 2D Quadratic Bezier curve.
  18610. *
  18611. * ```js
  18612. * const curve = new THREE.QuadraticBezierCurve(
  18613. * new THREE.Vector2( - 10, 0 ),
  18614. * new THREE.Vector2( 20, 15 ),
  18615. * new THREE.Vector2( 10, 0 )
  18616. * )
  18617. *
  18618. * const points = curve.getPoints( 50 );
  18619. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  18620. *
  18621. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  18622. *
  18623. * // Create the final object to add to the scene
  18624. * const curveObject = new THREE.Line( geometry, material );
  18625. * ```
  18626. *
  18627. * @augments Curve
  18628. */
  18629. class QuadraticBezierCurve extends Curve {
  18630. /**
  18631. * Constructs a new Quadratic Bezier curve.
  18632. *
  18633. * @param {Vector2} [v0] - The start point.
  18634. * @param {Vector2} [v1] - The control point.
  18635. * @param {Vector2} [v2] - The end point.
  18636. */
  18637. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  18638. super();
  18639. /**
  18640. * This flag can be used for type testing.
  18641. *
  18642. * @type {boolean}
  18643. * @readonly
  18644. * @default true
  18645. */
  18646. this.isQuadraticBezierCurve = true;
  18647. this.type = 'QuadraticBezierCurve';
  18648. /**
  18649. * The start point.
  18650. *
  18651. * @type {Vector2}
  18652. */
  18653. this.v0 = v0;
  18654. /**
  18655. * The control point.
  18656. *
  18657. * @type {Vector2}
  18658. */
  18659. this.v1 = v1;
  18660. /**
  18661. * The end point.
  18662. *
  18663. * @type {Vector2}
  18664. */
  18665. this.v2 = v2;
  18666. }
  18667. /**
  18668. * Returns a point on the curve.
  18669. *
  18670. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18671. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  18672. * @return {Vector2} The position on the curve.
  18673. */
  18674. getPoint( t, optionalTarget = new Vector2() ) {
  18675. const point = optionalTarget;
  18676. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  18677. point.set(
  18678. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  18679. QuadraticBezier( t, v0.y, v1.y, v2.y )
  18680. );
  18681. return point;
  18682. }
  18683. copy( source ) {
  18684. super.copy( source );
  18685. this.v0.copy( source.v0 );
  18686. this.v1.copy( source.v1 );
  18687. this.v2.copy( source.v2 );
  18688. return this;
  18689. }
  18690. toJSON() {
  18691. const data = super.toJSON();
  18692. data.v0 = this.v0.toArray();
  18693. data.v1 = this.v1.toArray();
  18694. data.v2 = this.v2.toArray();
  18695. return data;
  18696. }
  18697. fromJSON( json ) {
  18698. super.fromJSON( json );
  18699. this.v0.fromArray( json.v0 );
  18700. this.v1.fromArray( json.v1 );
  18701. this.v2.fromArray( json.v2 );
  18702. return this;
  18703. }
  18704. }
  18705. /**
  18706. * A curve representing a 3D Quadratic Bezier curve.
  18707. *
  18708. * @augments Curve
  18709. */
  18710. class QuadraticBezierCurve3 extends Curve {
  18711. /**
  18712. * Constructs a new Quadratic Bezier curve.
  18713. *
  18714. * @param {Vector3} [v0] - The start point.
  18715. * @param {Vector3} [v1] - The control point.
  18716. * @param {Vector3} [v2] - The end point.
  18717. */
  18718. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  18719. super();
  18720. /**
  18721. * This flag can be used for type testing.
  18722. *
  18723. * @type {boolean}
  18724. * @readonly
  18725. * @default true
  18726. */
  18727. this.isQuadraticBezierCurve3 = true;
  18728. this.type = 'QuadraticBezierCurve3';
  18729. /**
  18730. * The start point.
  18731. *
  18732. * @type {Vector3}
  18733. */
  18734. this.v0 = v0;
  18735. /**
  18736. * The control point.
  18737. *
  18738. * @type {Vector3}
  18739. */
  18740. this.v1 = v1;
  18741. /**
  18742. * The end point.
  18743. *
  18744. * @type {Vector3}
  18745. */
  18746. this.v2 = v2;
  18747. }
  18748. /**
  18749. * Returns a point on the curve.
  18750. *
  18751. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18752. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  18753. * @return {Vector3} The position on the curve.
  18754. */
  18755. getPoint( t, optionalTarget = new Vector3() ) {
  18756. const point = optionalTarget;
  18757. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  18758. point.set(
  18759. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  18760. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  18761. QuadraticBezier( t, v0.z, v1.z, v2.z )
  18762. );
  18763. return point;
  18764. }
  18765. copy( source ) {
  18766. super.copy( source );
  18767. this.v0.copy( source.v0 );
  18768. this.v1.copy( source.v1 );
  18769. this.v2.copy( source.v2 );
  18770. return this;
  18771. }
  18772. toJSON() {
  18773. const data = super.toJSON();
  18774. data.v0 = this.v0.toArray();
  18775. data.v1 = this.v1.toArray();
  18776. data.v2 = this.v2.toArray();
  18777. return data;
  18778. }
  18779. fromJSON( json ) {
  18780. super.fromJSON( json );
  18781. this.v0.fromArray( json.v0 );
  18782. this.v1.fromArray( json.v1 );
  18783. this.v2.fromArray( json.v2 );
  18784. return this;
  18785. }
  18786. }
  18787. /**
  18788. * A curve representing a 2D spline curve.
  18789. *
  18790. * ```js
  18791. * // Create a sine-like wave
  18792. * const curve = new THREE.SplineCurve( [
  18793. * new THREE.Vector2( -10, 0 ),
  18794. * new THREE.Vector2( -5, 5 ),
  18795. * new THREE.Vector2( 0, 0 ),
  18796. * new THREE.Vector2( 5, -5 ),
  18797. * new THREE.Vector2( 10, 0 )
  18798. * ] );
  18799. *
  18800. * const points = curve.getPoints( 50 );
  18801. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  18802. *
  18803. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  18804. *
  18805. * // Create the final object to add to the scene
  18806. * const splineObject = new THREE.Line( geometry, material );
  18807. * ```
  18808. *
  18809. * @augments Curve
  18810. */
  18811. class SplineCurve extends Curve {
  18812. /**
  18813. * Constructs a new 2D spline curve.
  18814. *
  18815. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  18816. */
  18817. constructor( points = [] ) {
  18818. super();
  18819. /**
  18820. * This flag can be used for type testing.
  18821. *
  18822. * @type {boolean}
  18823. * @readonly
  18824. * @default true
  18825. */
  18826. this.isSplineCurve = true;
  18827. this.type = 'SplineCurve';
  18828. /**
  18829. * An array of 2D points defining the curve.
  18830. *
  18831. * @type {Array<Vector2>}
  18832. */
  18833. this.points = points;
  18834. }
  18835. /**
  18836. * Returns a point on the curve.
  18837. *
  18838. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18839. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  18840. * @return {Vector2} The position on the curve.
  18841. */
  18842. getPoint( t, optionalTarget = new Vector2() ) {
  18843. const point = optionalTarget;
  18844. const points = this.points;
  18845. const p = ( points.length - 1 ) * t;
  18846. const intPoint = Math.floor( p );
  18847. const weight = p - intPoint;
  18848. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  18849. const p1 = points[ intPoint ];
  18850. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  18851. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  18852. point.set(
  18853. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  18854. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  18855. );
  18856. return point;
  18857. }
  18858. copy( source ) {
  18859. super.copy( source );
  18860. this.points = [];
  18861. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18862. const point = source.points[ i ];
  18863. this.points.push( point.clone() );
  18864. }
  18865. return this;
  18866. }
  18867. toJSON() {
  18868. const data = super.toJSON();
  18869. data.points = [];
  18870. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18871. const point = this.points[ i ];
  18872. data.points.push( point.toArray() );
  18873. }
  18874. return data;
  18875. }
  18876. fromJSON( json ) {
  18877. super.fromJSON( json );
  18878. this.points = [];
  18879. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18880. const point = json.points[ i ];
  18881. this.points.push( new Vector2().fromArray( point ) );
  18882. }
  18883. return this;
  18884. }
  18885. }
  18886. var Curves = /*#__PURE__*/Object.freeze({
  18887. __proto__: null,
  18888. ArcCurve: ArcCurve,
  18889. CatmullRomCurve3: CatmullRomCurve3,
  18890. CubicBezierCurve: CubicBezierCurve,
  18891. CubicBezierCurve3: CubicBezierCurve3,
  18892. EllipseCurve: EllipseCurve,
  18893. LineCurve: LineCurve,
  18894. LineCurve3: LineCurve3,
  18895. QuadraticBezierCurve: QuadraticBezierCurve,
  18896. QuadraticBezierCurve3: QuadraticBezierCurve3,
  18897. SplineCurve: SplineCurve
  18898. });
  18899. /**
  18900. * A base class extending {@link Curve}. `CurvePath` is simply an
  18901. * array of connected curves, but retains the API of a curve.
  18902. *
  18903. * @augments Curve
  18904. */
  18905. class CurvePath extends Curve {
  18906. /**
  18907. * Constructs a new curve path.
  18908. */
  18909. constructor() {
  18910. super();
  18911. this.type = 'CurvePath';
  18912. /**
  18913. * An array of curves defining the
  18914. * path.
  18915. *
  18916. * @type {Array<Curve>}
  18917. */
  18918. this.curves = [];
  18919. /**
  18920. * Whether the path should automatically be closed
  18921. * by a line curve.
  18922. *
  18923. * @type {boolean}
  18924. * @default false
  18925. */
  18926. this.autoClose = false;
  18927. }
  18928. /**
  18929. * Adds a curve to this curve path.
  18930. *
  18931. * @param {Curve} curve - The curve to add.
  18932. */
  18933. add( curve ) {
  18934. this.curves.push( curve );
  18935. }
  18936. /**
  18937. * Adds a line curve to close the path.
  18938. *
  18939. * @return {CurvePath} A reference to this curve path.
  18940. */
  18941. closePath() {
  18942. // Add a line curve if start and end of lines are not connected
  18943. const startPoint = this.curves[ 0 ].getPoint( 0 );
  18944. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  18945. if ( ! startPoint.equals( endPoint ) ) {
  18946. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  18947. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  18948. }
  18949. return this;
  18950. }
  18951. /**
  18952. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  18953. * for the given interpolation factor.
  18954. *
  18955. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18956. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  18957. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  18958. */
  18959. getPoint( t, optionalTarget ) {
  18960. // To get accurate point with reference to
  18961. // entire path distance at time t,
  18962. // following has to be done:
  18963. // 1. Length of each sub path have to be known
  18964. // 2. Locate and identify type of curve
  18965. // 3. Get t for the curve
  18966. // 4. Return curve.getPointAt(t')
  18967. const d = t * this.getLength();
  18968. const curveLengths = this.getCurveLengths();
  18969. let i = 0;
  18970. // To think about boundaries points.
  18971. while ( i < curveLengths.length ) {
  18972. if ( curveLengths[ i ] >= d ) {
  18973. const diff = curveLengths[ i ] - d;
  18974. const curve = this.curves[ i ];
  18975. const segmentLength = curve.getLength();
  18976. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  18977. return curve.getPointAt( u, optionalTarget );
  18978. }
  18979. i ++;
  18980. }
  18981. return null;
  18982. // loop where sum != 0, sum > d , sum+1 <d
  18983. }
  18984. getLength() {
  18985. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  18986. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  18987. // getPoint() depends on getLength
  18988. const lens = this.getCurveLengths();
  18989. return lens[ lens.length - 1 ];
  18990. }
  18991. updateArcLengths() {
  18992. // cacheLengths must be recalculated.
  18993. this.needsUpdate = true;
  18994. this.cacheLengths = null;
  18995. this.getCurveLengths();
  18996. }
  18997. /**
  18998. * Returns list of cumulative curve lengths of the defined curves.
  18999. *
  19000. * @return {Array<number>} The curve lengths.
  19001. */
  19002. getCurveLengths() {
  19003. // Compute lengths and cache them
  19004. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19005. // We use cache values if curves and cache array are same length
  19006. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19007. return this.cacheLengths;
  19008. }
  19009. // Get length of sub-curve
  19010. // Push sums into cached array
  19011. const lengths = [];
  19012. let sums = 0;
  19013. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19014. sums += this.curves[ i ].getLength();
  19015. lengths.push( sums );
  19016. }
  19017. this.cacheLengths = lengths;
  19018. return lengths;
  19019. }
  19020. getSpacedPoints( divisions = 40 ) {
  19021. const points = [];
  19022. for ( let i = 0; i <= divisions; i ++ ) {
  19023. points.push( this.getPoint( i / divisions ) );
  19024. }
  19025. if ( this.autoClose ) {
  19026. points.push( points[ 0 ] );
  19027. }
  19028. return points;
  19029. }
  19030. getPoints( divisions = 12 ) {
  19031. const points = [];
  19032. let last;
  19033. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19034. const curve = curves[ i ];
  19035. const resolution = curve.isEllipseCurve ? divisions * 2
  19036. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19037. : curve.isSplineCurve ? divisions * curve.points.length
  19038. : divisions;
  19039. const pts = curve.getPoints( resolution );
  19040. for ( let j = 0; j < pts.length; j ++ ) {
  19041. const point = pts[ j ];
  19042. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19043. points.push( point );
  19044. last = point;
  19045. }
  19046. }
  19047. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19048. points.push( points[ 0 ] );
  19049. }
  19050. return points;
  19051. }
  19052. copy( source ) {
  19053. super.copy( source );
  19054. this.curves = [];
  19055. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19056. const curve = source.curves[ i ];
  19057. this.curves.push( curve.clone() );
  19058. }
  19059. this.autoClose = source.autoClose;
  19060. return this;
  19061. }
  19062. toJSON() {
  19063. const data = super.toJSON();
  19064. data.autoClose = this.autoClose;
  19065. data.curves = [];
  19066. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19067. const curve = this.curves[ i ];
  19068. data.curves.push( curve.toJSON() );
  19069. }
  19070. return data;
  19071. }
  19072. fromJSON( json ) {
  19073. super.fromJSON( json );
  19074. this.autoClose = json.autoClose;
  19075. this.curves = [];
  19076. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19077. const curve = json.curves[ i ];
  19078. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19079. }
  19080. return this;
  19081. }
  19082. }
  19083. /**
  19084. * A 2D path representation. The class provides methods for creating paths
  19085. * and contours of 2D shapes similar to the 2D Canvas API.
  19086. *
  19087. * ```js
  19088. * const path = new THREE.Path();
  19089. *
  19090. * path.lineTo( 0, 0.8 );
  19091. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  19092. * path.lineTo( 1, 1 );
  19093. *
  19094. * const points = path.getPoints();
  19095. *
  19096. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  19097. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  19098. *
  19099. * const line = new THREE.Line( geometry, material );
  19100. * scene.add( line );
  19101. * ```
  19102. *
  19103. * @augments CurvePath
  19104. */
  19105. class Path extends CurvePath {
  19106. /**
  19107. * Constructs a new path.
  19108. *
  19109. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  19110. */
  19111. constructor( points ) {
  19112. super();
  19113. this.type = 'Path';
  19114. /**
  19115. * The current offset of the path. Any new curve added will start here.
  19116. *
  19117. * @type {Vector2}
  19118. */
  19119. this.currentPoint = new Vector2();
  19120. if ( points ) {
  19121. this.setFromPoints( points );
  19122. }
  19123. }
  19124. /**
  19125. * Creates a path from the given list of points. The points are added
  19126. * to the path as instances of {@link LineCurve}.
  19127. *
  19128. * @param {Array<Vector2>} points - An array of 2D points.
  19129. * @return {Path} A reference to this path.
  19130. */
  19131. setFromPoints( points ) {
  19132. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19133. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19134. this.lineTo( points[ i ].x, points[ i ].y );
  19135. }
  19136. return this;
  19137. }
  19138. /**
  19139. * Moves {@link Path#currentPoint} to the given point.
  19140. *
  19141. * @param {number} x - The x coordinate.
  19142. * @param {number} y - The y coordinate.
  19143. * @return {Path} A reference to this path.
  19144. */
  19145. moveTo( x, y ) {
  19146. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19147. return this;
  19148. }
  19149. /**
  19150. * Adds an instance of {@link LineCurve} to the path by connecting
  19151. * the current point with the given one.
  19152. *
  19153. * @param {number} x - The x coordinate of the end point.
  19154. * @param {number} y - The y coordinate of the end point.
  19155. * @return {Path} A reference to this path.
  19156. */
  19157. lineTo( x, y ) {
  19158. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19159. this.curves.push( curve );
  19160. this.currentPoint.set( x, y );
  19161. return this;
  19162. }
  19163. /**
  19164. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  19165. * the current point with the given one.
  19166. *
  19167. * @param {number} aCPx - The x coordinate of the control point.
  19168. * @param {number} aCPy - The y coordinate of the control point.
  19169. * @param {number} aX - The x coordinate of the end point.
  19170. * @param {number} aY - The y coordinate of the end point.
  19171. * @return {Path} A reference to this path.
  19172. */
  19173. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19174. const curve = new QuadraticBezierCurve(
  19175. this.currentPoint.clone(),
  19176. new Vector2( aCPx, aCPy ),
  19177. new Vector2( aX, aY )
  19178. );
  19179. this.curves.push( curve );
  19180. this.currentPoint.set( aX, aY );
  19181. return this;
  19182. }
  19183. /**
  19184. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  19185. * the current point with the given one.
  19186. *
  19187. * @param {number} aCP1x - The x coordinate of the first control point.
  19188. * @param {number} aCP1y - The y coordinate of the first control point.
  19189. * @param {number} aCP2x - The x coordinate of the second control point.
  19190. * @param {number} aCP2y - The y coordinate of the second control point.
  19191. * @param {number} aX - The x coordinate of the end point.
  19192. * @param {number} aY - The y coordinate of the end point.
  19193. * @return {Path} A reference to this path.
  19194. */
  19195. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19196. const curve = new CubicBezierCurve(
  19197. this.currentPoint.clone(),
  19198. new Vector2( aCP1x, aCP1y ),
  19199. new Vector2( aCP2x, aCP2y ),
  19200. new Vector2( aX, aY )
  19201. );
  19202. this.curves.push( curve );
  19203. this.currentPoint.set( aX, aY );
  19204. return this;
  19205. }
  19206. /**
  19207. * Adds an instance of {@link SplineCurve} to the path by connecting
  19208. * the current point with the given list of points.
  19209. *
  19210. * @param {Array<Vector2>} pts - An array of points in 2D space.
  19211. * @return {Path} A reference to this path.
  19212. */
  19213. splineThru( pts ) {
  19214. const npts = [ this.currentPoint.clone() ].concat( pts );
  19215. const curve = new SplineCurve( npts );
  19216. this.curves.push( curve );
  19217. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19218. return this;
  19219. }
  19220. /**
  19221. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  19222. * to the current point.
  19223. *
  19224. * @param {number} aX - The x coordinate of the center of the arc offsetted from the previous curve.
  19225. * @param {number} aY - The y coordinate of the center of the arc offsetted from the previous curve.
  19226. * @param {number} aRadius - The radius of the arc.
  19227. * @param {number} aStartAngle - The start angle in radians.
  19228. * @param {number} aEndAngle - The end angle in radians.
  19229. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  19230. * @return {Path} A reference to this path.
  19231. */
  19232. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19233. const x0 = this.currentPoint.x;
  19234. const y0 = this.currentPoint.y;
  19235. this.absarc( aX + x0, aY + y0, aRadius,
  19236. aStartAngle, aEndAngle, aClockwise );
  19237. return this;
  19238. }
  19239. /**
  19240. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  19241. *
  19242. * @param {number} aX - The x coordinate of the center of the arc.
  19243. * @param {number} aY - The y coordinate of the center of the arc.
  19244. * @param {number} aRadius - The radius of the arc.
  19245. * @param {number} aStartAngle - The start angle in radians.
  19246. * @param {number} aEndAngle - The end angle in radians.
  19247. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  19248. * @return {Path} A reference to this path.
  19249. */
  19250. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19251. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19252. return this;
  19253. }
  19254. /**
  19255. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  19256. * to the current point
  19257. *
  19258. * @param {number} aX - The x coordinate of the center of the ellipse offsetted from the previous curve.
  19259. * @param {number} aY - The y coordinate of the center of the ellipse offsetted from the previous curve.
  19260. * @param {number} xRadius - The radius of the ellipse in the x axis.
  19261. * @param {number} yRadius - The radius of the ellipse in the y axis.
  19262. * @param {number} aStartAngle - The start angle in radians.
  19263. * @param {number} aEndAngle - The end angle in radians.
  19264. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  19265. * @param {boolean} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  19266. * @return {Path} A reference to this path.
  19267. */
  19268. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19269. const x0 = this.currentPoint.x;
  19270. const y0 = this.currentPoint.y;
  19271. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19272. return this;
  19273. }
  19274. /**
  19275. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  19276. *
  19277. * @param {number} aX - The x coordinate of the absolute center of the ellipse.
  19278. * @param {number} aY - The y coordinate of the absolute center of the ellipse.
  19279. * @param {number} xRadius - The radius of the ellipse in the x axis.
  19280. * @param {number} yRadius - The radius of the ellipse in the y axis.
  19281. * @param {number} aStartAngle - The start angle in radians.
  19282. * @param {number} aEndAngle - The end angle in radians.
  19283. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  19284. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  19285. * @return {Path} A reference to this path.
  19286. */
  19287. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19288. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19289. if ( this.curves.length > 0 ) {
  19290. // if a previous curve is present, attempt to join
  19291. const firstPoint = curve.getPoint( 0 );
  19292. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19293. this.lineTo( firstPoint.x, firstPoint.y );
  19294. }
  19295. }
  19296. this.curves.push( curve );
  19297. const lastPoint = curve.getPoint( 1 );
  19298. this.currentPoint.copy( lastPoint );
  19299. return this;
  19300. }
  19301. copy( source ) {
  19302. super.copy( source );
  19303. this.currentPoint.copy( source.currentPoint );
  19304. return this;
  19305. }
  19306. toJSON() {
  19307. const data = super.toJSON();
  19308. data.currentPoint = this.currentPoint.toArray();
  19309. return data;
  19310. }
  19311. fromJSON( json ) {
  19312. super.fromJSON( json );
  19313. this.currentPoint.fromArray( json.currentPoint );
  19314. return this;
  19315. }
  19316. }
  19317. /**
  19318. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  19319. *
  19320. * ```js
  19321. * const points = [];
  19322. * for ( let i = 0; i < 10; i ++ ) {
  19323. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  19324. * }
  19325. * const geometry = new THREE.LatheGeometry( points );
  19326. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  19327. * const lathe = new THREE.Mesh( geometry, material );
  19328. * scene.add( lathe );
  19329. * ```
  19330. *
  19331. * @augments BufferGeometry
  19332. */
  19333. class LatheGeometry extends BufferGeometry {
  19334. /**
  19335. * Constructs a new lathe geometry.
  19336. *
  19337. * @param {Array<Vector2>} [points] - An array of points in 2D space. The x-coordinate of each point
  19338. * must be greater than zero.
  19339. * @param {number} [segments=12] - The number of circumference segments to generate.
  19340. * @param {number} [phiStart=0] - The starting angle in radians.
  19341. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  19342. * closed lathe, less than 2PI is a portion.
  19343. */
  19344. 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 ) {
  19345. super();
  19346. this.type = 'LatheGeometry';
  19347. /**
  19348. * Holds the constructor parameters that have been
  19349. * used to generate the geometry. Any modification
  19350. * after instantiation does not change the geometry.
  19351. *
  19352. * @type {Object}
  19353. */
  19354. this.parameters = {
  19355. points: points,
  19356. segments: segments,
  19357. phiStart: phiStart,
  19358. phiLength: phiLength
  19359. };
  19360. segments = Math.floor( segments );
  19361. // clamp phiLength so it's in range of [ 0, 2PI ]
  19362. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  19363. // buffers
  19364. const indices = [];
  19365. const vertices = [];
  19366. const uvs = [];
  19367. const initNormals = [];
  19368. const normals = [];
  19369. // helper variables
  19370. const inverseSegments = 1.0 / segments;
  19371. const vertex = new Vector3();
  19372. const uv = new Vector2();
  19373. const normal = new Vector3();
  19374. const curNormal = new Vector3();
  19375. const prevNormal = new Vector3();
  19376. let dx = 0;
  19377. let dy = 0;
  19378. // pre-compute normals for initial "meridian"
  19379. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19380. switch ( j ) {
  19381. case 0: // special handling for 1st vertex on path
  19382. dx = points[ j + 1 ].x - points[ j ].x;
  19383. dy = points[ j + 1 ].y - points[ j ].y;
  19384. normal.x = dy * 1.0;
  19385. normal.y = - dx;
  19386. normal.z = dy * 0.0;
  19387. prevNormal.copy( normal );
  19388. normal.normalize();
  19389. initNormals.push( normal.x, normal.y, normal.z );
  19390. break;
  19391. case ( points.length - 1 ): // special handling for last Vertex on path
  19392. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  19393. break;
  19394. default: // default handling for all vertices in between
  19395. dx = points[ j + 1 ].x - points[ j ].x;
  19396. dy = points[ j + 1 ].y - points[ j ].y;
  19397. normal.x = dy * 1.0;
  19398. normal.y = - dx;
  19399. normal.z = dy * 0.0;
  19400. curNormal.copy( normal );
  19401. normal.x += prevNormal.x;
  19402. normal.y += prevNormal.y;
  19403. normal.z += prevNormal.z;
  19404. normal.normalize();
  19405. initNormals.push( normal.x, normal.y, normal.z );
  19406. prevNormal.copy( curNormal );
  19407. }
  19408. }
  19409. // generate vertices, uvs and normals
  19410. for ( let i = 0; i <= segments; i ++ ) {
  19411. const phi = phiStart + i * inverseSegments * phiLength;
  19412. const sin = Math.sin( phi );
  19413. const cos = Math.cos( phi );
  19414. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19415. // vertex
  19416. vertex.x = points[ j ].x * sin;
  19417. vertex.y = points[ j ].y;
  19418. vertex.z = points[ j ].x * cos;
  19419. vertices.push( vertex.x, vertex.y, vertex.z );
  19420. // uv
  19421. uv.x = i / segments;
  19422. uv.y = j / ( points.length - 1 );
  19423. uvs.push( uv.x, uv.y );
  19424. // normal
  19425. const x = initNormals[ 3 * j + 0 ] * sin;
  19426. const y = initNormals[ 3 * j + 1 ];
  19427. const z = initNormals[ 3 * j + 0 ] * cos;
  19428. normals.push( x, y, z );
  19429. }
  19430. }
  19431. // indices
  19432. for ( let i = 0; i < segments; i ++ ) {
  19433. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19434. const base = j + i * points.length;
  19435. const a = base;
  19436. const b = base + points.length;
  19437. const c = base + points.length + 1;
  19438. const d = base + 1;
  19439. // faces
  19440. indices.push( a, b, d );
  19441. indices.push( c, d, b );
  19442. }
  19443. }
  19444. // build geometry
  19445. this.setIndex( indices );
  19446. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19447. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19448. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19449. }
  19450. copy( source ) {
  19451. super.copy( source );
  19452. this.parameters = Object.assign( {}, source.parameters );
  19453. return this;
  19454. }
  19455. /**
  19456. * Factory method for creating an instance of this class from the given
  19457. * JSON object.
  19458. *
  19459. * @param {Object} data - A JSON object representing the serialized geometry.
  19460. * @return {LatheGeometry} A new instance.
  19461. */
  19462. static fromJSON( data ) {
  19463. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  19464. }
  19465. }
  19466. /**
  19467. * A geometry class for a capsule with given radii and height. It is constructed using a lathe.
  19468. *
  19469. * ```js
  19470. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8 );
  19471. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19472. * const capsule = new THREE.Mesh( geometry, material );
  19473. * scene.add( capsule );
  19474. * ```
  19475. *
  19476. * @augments LatheGeometry
  19477. */
  19478. class CapsuleGeometry extends LatheGeometry {
  19479. /**
  19480. * Constructs a new capsule geometry.
  19481. *
  19482. * @param {number} [radius=1] - Radius of the capsule.
  19483. * @param {number} [length=1] - Length of the middle section.
  19484. * @param {number} [capSegments=4] - Number of curve segments used to build the caps.
  19485. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule.
  19486. */
  19487. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  19488. const path = new Path();
  19489. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  19490. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  19491. super( path.getPoints( capSegments ), radialSegments );
  19492. this.type = 'CapsuleGeometry';
  19493. /**
  19494. * Holds the constructor parameters that have been
  19495. * used to generate the geometry. Any modification
  19496. * after instantiation does not change the geometry.
  19497. *
  19498. * @type {Object}
  19499. */
  19500. this.parameters = {
  19501. radius: radius,
  19502. length: length,
  19503. capSegments: capSegments,
  19504. radialSegments: radialSegments,
  19505. };
  19506. }
  19507. /**
  19508. * Factory method for creating an instance of this class from the given
  19509. * JSON object.
  19510. *
  19511. * @param {Object} data - A JSON object representing the serialized geometry.
  19512. * @return {CapsuleGeometry} A new instance.
  19513. */
  19514. static fromJSON( data ) {
  19515. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  19516. }
  19517. }
  19518. /**
  19519. * A simple shape of Euclidean geometry. It is constructed from a
  19520. * number of triangular segments that are oriented around a central point and
  19521. * extend as far out as a given radius. It is built counter-clockwise from a
  19522. * start angle and a given central angle. It can also be used to create
  19523. * regular polygons, where the number of segments determines the number of
  19524. * sides.
  19525. *
  19526. * ```js
  19527. * const geometry = new THREE.CircleGeometry( 5, 32 );
  19528. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  19529. * const circle = new THREE.Mesh( geometry, material );
  19530. * scene.add( circle )
  19531. * ```
  19532. *
  19533. * @augments BufferGeometry
  19534. */
  19535. class CircleGeometry extends BufferGeometry {
  19536. /**
  19537. * Constructs a new circle geometry.
  19538. *
  19539. * @param {number} [radius=1] - Radius of the circle.
  19540. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  19541. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  19542. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  19543. * of the circular sector in radians. The default value results in a complete circle.
  19544. */
  19545. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19546. super();
  19547. this.type = 'CircleGeometry';
  19548. /**
  19549. * Holds the constructor parameters that have been
  19550. * used to generate the geometry. Any modification
  19551. * after instantiation does not change the geometry.
  19552. *
  19553. * @type {Object}
  19554. */
  19555. this.parameters = {
  19556. radius: radius,
  19557. segments: segments,
  19558. thetaStart: thetaStart,
  19559. thetaLength: thetaLength
  19560. };
  19561. segments = Math.max( 3, segments );
  19562. // buffers
  19563. const indices = [];
  19564. const vertices = [];
  19565. const normals = [];
  19566. const uvs = [];
  19567. // helper variables
  19568. const vertex = new Vector3();
  19569. const uv = new Vector2();
  19570. // center point
  19571. vertices.push( 0, 0, 0 );
  19572. normals.push( 0, 0, 1 );
  19573. uvs.push( 0.5, 0.5 );
  19574. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  19575. const segment = thetaStart + s / segments * thetaLength;
  19576. // vertex
  19577. vertex.x = radius * Math.cos( segment );
  19578. vertex.y = radius * Math.sin( segment );
  19579. vertices.push( vertex.x, vertex.y, vertex.z );
  19580. // normal
  19581. normals.push( 0, 0, 1 );
  19582. // uvs
  19583. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  19584. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  19585. uvs.push( uv.x, uv.y );
  19586. }
  19587. // indices
  19588. for ( let i = 1; i <= segments; i ++ ) {
  19589. indices.push( i, i + 1, 0 );
  19590. }
  19591. // build geometry
  19592. this.setIndex( indices );
  19593. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19594. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19595. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19596. }
  19597. copy( source ) {
  19598. super.copy( source );
  19599. this.parameters = Object.assign( {}, source.parameters );
  19600. return this;
  19601. }
  19602. /**
  19603. * Factory method for creating an instance of this class from the given
  19604. * JSON object.
  19605. *
  19606. * @param {Object} data - A JSON object representing the serialized geometry.
  19607. * @return {CircleGeometry} A new instance.
  19608. */
  19609. static fromJSON( data ) {
  19610. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  19611. }
  19612. }
  19613. /**
  19614. * A geometry class for representing a cylinder.
  19615. *
  19616. * ```js
  19617. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  19618. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  19619. * const cylinder = new THREE.Mesh( geometry, material );
  19620. * scene.add( cylinder );
  19621. * ```
  19622. *
  19623. * @augments BufferGeometry
  19624. */
  19625. class CylinderGeometry extends BufferGeometry {
  19626. /**
  19627. * Constructs a new cylinder geometry.
  19628. *
  19629. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  19630. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  19631. * @param {number} [height=1] - Height of the cylinder.
  19632. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  19633. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  19634. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  19635. * @param {boolean} [thetaStart=0] - Start angle for first segment, in radians.
  19636. * @param {boolean} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  19637. * The default value results in a complete cylinder.
  19638. */
  19639. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19640. super();
  19641. this.type = 'CylinderGeometry';
  19642. /**
  19643. * Holds the constructor parameters that have been
  19644. * used to generate the geometry. Any modification
  19645. * after instantiation does not change the geometry.
  19646. *
  19647. * @type {Object}
  19648. */
  19649. this.parameters = {
  19650. radiusTop: radiusTop,
  19651. radiusBottom: radiusBottom,
  19652. height: height,
  19653. radialSegments: radialSegments,
  19654. heightSegments: heightSegments,
  19655. openEnded: openEnded,
  19656. thetaStart: thetaStart,
  19657. thetaLength: thetaLength
  19658. };
  19659. const scope = this;
  19660. radialSegments = Math.floor( radialSegments );
  19661. heightSegments = Math.floor( heightSegments );
  19662. // buffers
  19663. const indices = [];
  19664. const vertices = [];
  19665. const normals = [];
  19666. const uvs = [];
  19667. // helper variables
  19668. let index = 0;
  19669. const indexArray = [];
  19670. const halfHeight = height / 2;
  19671. let groupStart = 0;
  19672. // generate geometry
  19673. generateTorso();
  19674. if ( openEnded === false ) {
  19675. if ( radiusTop > 0 ) generateCap( true );
  19676. if ( radiusBottom > 0 ) generateCap( false );
  19677. }
  19678. // build geometry
  19679. this.setIndex( indices );
  19680. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19681. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19682. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19683. function generateTorso() {
  19684. const normal = new Vector3();
  19685. const vertex = new Vector3();
  19686. let groupCount = 0;
  19687. // this will be used to calculate the normal
  19688. const slope = ( radiusBottom - radiusTop ) / height;
  19689. // generate vertices, normals and uvs
  19690. for ( let y = 0; y <= heightSegments; y ++ ) {
  19691. const indexRow = [];
  19692. const v = y / heightSegments;
  19693. // calculate the radius of the current row
  19694. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19695. for ( let x = 0; x <= radialSegments; x ++ ) {
  19696. const u = x / radialSegments;
  19697. const theta = u * thetaLength + thetaStart;
  19698. const sinTheta = Math.sin( theta );
  19699. const cosTheta = Math.cos( theta );
  19700. // vertex
  19701. vertex.x = radius * sinTheta;
  19702. vertex.y = - v * height + halfHeight;
  19703. vertex.z = radius * cosTheta;
  19704. vertices.push( vertex.x, vertex.y, vertex.z );
  19705. // normal
  19706. normal.set( sinTheta, slope, cosTheta ).normalize();
  19707. normals.push( normal.x, normal.y, normal.z );
  19708. // uv
  19709. uvs.push( u, 1 - v );
  19710. // save index of vertex in respective row
  19711. indexRow.push( index ++ );
  19712. }
  19713. // now save vertices of the row in our index array
  19714. indexArray.push( indexRow );
  19715. }
  19716. // generate indices
  19717. for ( let x = 0; x < radialSegments; x ++ ) {
  19718. for ( let y = 0; y < heightSegments; y ++ ) {
  19719. // we use the index array to access the correct indices
  19720. const a = indexArray[ y ][ x ];
  19721. const b = indexArray[ y + 1 ][ x ];
  19722. const c = indexArray[ y + 1 ][ x + 1 ];
  19723. const d = indexArray[ y ][ x + 1 ];
  19724. // faces
  19725. if ( radiusTop > 0 || y !== 0 ) {
  19726. indices.push( a, b, d );
  19727. groupCount += 3;
  19728. }
  19729. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  19730. indices.push( b, c, d );
  19731. groupCount += 3;
  19732. }
  19733. }
  19734. }
  19735. // add a group to the geometry. this will ensure multi material support
  19736. scope.addGroup( groupStart, groupCount, 0 );
  19737. // calculate new start value for groups
  19738. groupStart += groupCount;
  19739. }
  19740. function generateCap( top ) {
  19741. // save the index of the first center vertex
  19742. const centerIndexStart = index;
  19743. const uv = new Vector2();
  19744. const vertex = new Vector3();
  19745. let groupCount = 0;
  19746. const radius = ( top === true ) ? radiusTop : radiusBottom;
  19747. const sign = ( top === true ) ? 1 : -1;
  19748. // first we generate the center vertex data of the cap.
  19749. // because the geometry needs one set of uvs per face,
  19750. // we must generate a center vertex per face/segment
  19751. for ( let x = 1; x <= radialSegments; x ++ ) {
  19752. // vertex
  19753. vertices.push( 0, halfHeight * sign, 0 );
  19754. // normal
  19755. normals.push( 0, sign, 0 );
  19756. // uv
  19757. uvs.push( 0.5, 0.5 );
  19758. // increase index
  19759. index ++;
  19760. }
  19761. // save the index of the last center vertex
  19762. const centerIndexEnd = index;
  19763. // now we generate the surrounding vertices, normals and uvs
  19764. for ( let x = 0; x <= radialSegments; x ++ ) {
  19765. const u = x / radialSegments;
  19766. const theta = u * thetaLength + thetaStart;
  19767. const cosTheta = Math.cos( theta );
  19768. const sinTheta = Math.sin( theta );
  19769. // vertex
  19770. vertex.x = radius * sinTheta;
  19771. vertex.y = halfHeight * sign;
  19772. vertex.z = radius * cosTheta;
  19773. vertices.push( vertex.x, vertex.y, vertex.z );
  19774. // normal
  19775. normals.push( 0, sign, 0 );
  19776. // uv
  19777. uv.x = ( cosTheta * 0.5 ) + 0.5;
  19778. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  19779. uvs.push( uv.x, uv.y );
  19780. // increase index
  19781. index ++;
  19782. }
  19783. // generate indices
  19784. for ( let x = 0; x < radialSegments; x ++ ) {
  19785. const c = centerIndexStart + x;
  19786. const i = centerIndexEnd + x;
  19787. if ( top === true ) {
  19788. // face top
  19789. indices.push( i, i + 1, c );
  19790. } else {
  19791. // face bottom
  19792. indices.push( i + 1, i, c );
  19793. }
  19794. groupCount += 3;
  19795. }
  19796. // add a group to the geometry. this will ensure multi material support
  19797. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  19798. // calculate new start value for groups
  19799. groupStart += groupCount;
  19800. }
  19801. }
  19802. copy( source ) {
  19803. super.copy( source );
  19804. this.parameters = Object.assign( {}, source.parameters );
  19805. return this;
  19806. }
  19807. /**
  19808. * Factory method for creating an instance of this class from the given
  19809. * JSON object.
  19810. *
  19811. * @param {Object} data - A JSON object representing the serialized geometry.
  19812. * @return {CylinderGeometry} A new instance.
  19813. */
  19814. static fromJSON( data ) {
  19815. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  19816. }
  19817. }
  19818. /**
  19819. * A geometry class for representing a cone.
  19820. *
  19821. * ```js
  19822. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  19823. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  19824. * const cone = new THREE.Mesh(geometry, material );
  19825. * scene.add( cone );
  19826. * ```
  19827. *
  19828. * @augments CylinderGeometry
  19829. */
  19830. class ConeGeometry extends CylinderGeometry {
  19831. /**
  19832. * Constructs a new cone geometry.
  19833. *
  19834. * @param {number} [radius=1] - Radius of the cone base.
  19835. * @param {number} [height=1] - Height of the cone.
  19836. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  19837. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  19838. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  19839. * @param {boolean} [thetaStart=0] - Start angle for first segment, in radians.
  19840. * @param {boolean} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  19841. * The default value results in a complete cone.
  19842. */
  19843. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19844. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  19845. this.type = 'ConeGeometry';
  19846. /**
  19847. * Holds the constructor parameters that have been
  19848. * used to generate the geometry. Any modification
  19849. * after instantiation does not change the geometry.
  19850. *
  19851. * @type {Object}
  19852. */
  19853. this.parameters = {
  19854. radius: radius,
  19855. height: height,
  19856. radialSegments: radialSegments,
  19857. heightSegments: heightSegments,
  19858. openEnded: openEnded,
  19859. thetaStart: thetaStart,
  19860. thetaLength: thetaLength
  19861. };
  19862. }
  19863. /**
  19864. * Factory method for creating an instance of this class from the given
  19865. * JSON object.
  19866. *
  19867. * @param {Object} data - A JSON object representing the serialized geometry.
  19868. * @return {ConeGeometry} A new instance.
  19869. */
  19870. static fromJSON( data ) {
  19871. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  19872. }
  19873. }
  19874. /**
  19875. * A polyhedron is a solid in three dimensions with flat faces. This class
  19876. * will take an array of vertices, project them onto a sphere, and then
  19877. * divide them up to the desired level of detail.
  19878. *
  19879. * @augments BufferGeometry
  19880. */
  19881. class PolyhedronGeometry extends BufferGeometry {
  19882. /**
  19883. * Constructs a new polyhedron geometry.
  19884. *
  19885. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  19886. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  19887. * @param {number} [radius=1] - The radius of the shape.
  19888. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  19889. */
  19890. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  19891. super();
  19892. this.type = 'PolyhedronGeometry';
  19893. /**
  19894. * Holds the constructor parameters that have been
  19895. * used to generate the geometry. Any modification
  19896. * after instantiation does not change the geometry.
  19897. *
  19898. * @type {Object}
  19899. */
  19900. this.parameters = {
  19901. vertices: vertices,
  19902. indices: indices,
  19903. radius: radius,
  19904. detail: detail
  19905. };
  19906. // default buffer data
  19907. const vertexBuffer = [];
  19908. const uvBuffer = [];
  19909. // the subdivision creates the vertex buffer data
  19910. subdivide( detail );
  19911. // all vertices should lie on a conceptual sphere with a given radius
  19912. applyRadius( radius );
  19913. // finally, create the uv data
  19914. generateUVs();
  19915. // build non-indexed geometry
  19916. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  19917. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  19918. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  19919. if ( detail === 0 ) {
  19920. this.computeVertexNormals(); // flat normals
  19921. } else {
  19922. this.normalizeNormals(); // smooth normals
  19923. }
  19924. // helper functions
  19925. function subdivide( detail ) {
  19926. const a = new Vector3();
  19927. const b = new Vector3();
  19928. const c = new Vector3();
  19929. // iterate over all faces and apply a subdivision with the given detail value
  19930. for ( let i = 0; i < indices.length; i += 3 ) {
  19931. // get the vertices of the face
  19932. getVertexByIndex( indices[ i + 0 ], a );
  19933. getVertexByIndex( indices[ i + 1 ], b );
  19934. getVertexByIndex( indices[ i + 2 ], c );
  19935. // perform subdivision
  19936. subdivideFace( a, b, c, detail );
  19937. }
  19938. }
  19939. function subdivideFace( a, b, c, detail ) {
  19940. const cols = detail + 1;
  19941. // we use this multidimensional array as a data structure for creating the subdivision
  19942. const v = [];
  19943. // construct all of the vertices for this subdivision
  19944. for ( let i = 0; i <= cols; i ++ ) {
  19945. v[ i ] = [];
  19946. const aj = a.clone().lerp( c, i / cols );
  19947. const bj = b.clone().lerp( c, i / cols );
  19948. const rows = cols - i;
  19949. for ( let j = 0; j <= rows; j ++ ) {
  19950. if ( j === 0 && i === cols ) {
  19951. v[ i ][ j ] = aj;
  19952. } else {
  19953. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  19954. }
  19955. }
  19956. }
  19957. // construct all of the faces
  19958. for ( let i = 0; i < cols; i ++ ) {
  19959. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  19960. const k = Math.floor( j / 2 );
  19961. if ( j % 2 === 0 ) {
  19962. pushVertex( v[ i ][ k + 1 ] );
  19963. pushVertex( v[ i + 1 ][ k ] );
  19964. pushVertex( v[ i ][ k ] );
  19965. } else {
  19966. pushVertex( v[ i ][ k + 1 ] );
  19967. pushVertex( v[ i + 1 ][ k + 1 ] );
  19968. pushVertex( v[ i + 1 ][ k ] );
  19969. }
  19970. }
  19971. }
  19972. }
  19973. function applyRadius( radius ) {
  19974. const vertex = new Vector3();
  19975. // iterate over the entire buffer and apply the radius to each vertex
  19976. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  19977. vertex.x = vertexBuffer[ i + 0 ];
  19978. vertex.y = vertexBuffer[ i + 1 ];
  19979. vertex.z = vertexBuffer[ i + 2 ];
  19980. vertex.normalize().multiplyScalar( radius );
  19981. vertexBuffer[ i + 0 ] = vertex.x;
  19982. vertexBuffer[ i + 1 ] = vertex.y;
  19983. vertexBuffer[ i + 2 ] = vertex.z;
  19984. }
  19985. }
  19986. function generateUVs() {
  19987. const vertex = new Vector3();
  19988. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  19989. vertex.x = vertexBuffer[ i + 0 ];
  19990. vertex.y = vertexBuffer[ i + 1 ];
  19991. vertex.z = vertexBuffer[ i + 2 ];
  19992. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  19993. const v = inclination( vertex ) / Math.PI + 0.5;
  19994. uvBuffer.push( u, 1 - v );
  19995. }
  19996. correctUVs();
  19997. correctSeam();
  19998. }
  19999. function correctSeam() {
  20000. // handle case when face straddles the seam, see #3269
  20001. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20002. // uv data of a single face
  20003. const x0 = uvBuffer[ i + 0 ];
  20004. const x1 = uvBuffer[ i + 2 ];
  20005. const x2 = uvBuffer[ i + 4 ];
  20006. const max = Math.max( x0, x1, x2 );
  20007. const min = Math.min( x0, x1, x2 );
  20008. // 0.9 is somewhat arbitrary
  20009. if ( max > 0.9 && min < 0.1 ) {
  20010. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20011. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20012. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20013. }
  20014. }
  20015. }
  20016. function pushVertex( vertex ) {
  20017. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20018. }
  20019. function getVertexByIndex( index, vertex ) {
  20020. const stride = index * 3;
  20021. vertex.x = vertices[ stride + 0 ];
  20022. vertex.y = vertices[ stride + 1 ];
  20023. vertex.z = vertices[ stride + 2 ];
  20024. }
  20025. function correctUVs() {
  20026. const a = new Vector3();
  20027. const b = new Vector3();
  20028. const c = new Vector3();
  20029. const centroid = new Vector3();
  20030. const uvA = new Vector2();
  20031. const uvB = new Vector2();
  20032. const uvC = new Vector2();
  20033. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20034. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20035. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20036. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20037. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20038. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20039. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20040. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20041. const azi = azimuth( centroid );
  20042. correctUV( uvA, j + 0, a, azi );
  20043. correctUV( uvB, j + 2, b, azi );
  20044. correctUV( uvC, j + 4, c, azi );
  20045. }
  20046. }
  20047. function correctUV( uv, stride, vector, azimuth ) {
  20048. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20049. uvBuffer[ stride ] = uv.x - 1;
  20050. }
  20051. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20052. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20053. }
  20054. }
  20055. // Angle around the Y axis, counter-clockwise when looking from above.
  20056. function azimuth( vector ) {
  20057. return Math.atan2( vector.z, - vector.x );
  20058. }
  20059. // Angle above the XZ plane.
  20060. function inclination( vector ) {
  20061. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20062. }
  20063. }
  20064. copy( source ) {
  20065. super.copy( source );
  20066. this.parameters = Object.assign( {}, source.parameters );
  20067. return this;
  20068. }
  20069. /**
  20070. * Factory method for creating an instance of this class from the given
  20071. * JSON object.
  20072. *
  20073. * @param {Object} data - A JSON object representing the serialized geometry.
  20074. * @return {PolyhedronGeometry} A new instance.
  20075. */
  20076. static fromJSON( data ) {
  20077. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20078. }
  20079. }
  20080. /**
  20081. * A geometry class for representing a dodecahedron.
  20082. *
  20083. * ```js
  20084. * const geometry = new THREE.DodecahedronGeometry();
  20085. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  20086. * const dodecahedron = new THREE.Mesh( geometry, material );
  20087. * scene.add( dodecahedron );
  20088. * ```
  20089. *
  20090. * @augments PolyhedronGeometry
  20091. */
  20092. class DodecahedronGeometry extends PolyhedronGeometry {
  20093. /**
  20094. * Constructs a new dodecahedron geometry.
  20095. *
  20096. * @param {number} [radius=1] - Radius of the dodecahedron.
  20097. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  20098. */
  20099. constructor( radius = 1, detail = 0 ) {
  20100. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20101. const r = 1 / t;
  20102. const vertices = [
  20103. // (±1, ±1, ±1)
  20104. -1, -1, -1, -1, -1, 1,
  20105. -1, 1, -1, -1, 1, 1,
  20106. 1, -1, -1, 1, -1, 1,
  20107. 1, 1, -1, 1, 1, 1,
  20108. // (0, ±1/φ, ±φ)
  20109. 0, - r, - t, 0, - r, t,
  20110. 0, r, - t, 0, r, t,
  20111. // (±1/φ, ±φ, 0)
  20112. - r, - t, 0, - r, t, 0,
  20113. r, - t, 0, r, t, 0,
  20114. // (±φ, 0, ±1/φ)
  20115. - t, 0, - r, t, 0, - r,
  20116. - t, 0, r, t, 0, r
  20117. ];
  20118. const indices = [
  20119. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20120. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20121. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20122. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20123. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20124. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20125. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20126. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20127. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20128. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20129. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20130. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20131. ];
  20132. super( vertices, indices, radius, detail );
  20133. this.type = 'DodecahedronGeometry';
  20134. /**
  20135. * Holds the constructor parameters that have been
  20136. * used to generate the geometry. Any modification
  20137. * after instantiation does not change the geometry.
  20138. *
  20139. * @type {Object}
  20140. */
  20141. this.parameters = {
  20142. radius: radius,
  20143. detail: detail
  20144. };
  20145. }
  20146. /**
  20147. * Factory method for creating an instance of this class from the given
  20148. * JSON object.
  20149. *
  20150. * @param {Object} data - A JSON object representing the serialized geometry.
  20151. * @return {DodecahedronGeometry} A new instance.
  20152. */
  20153. static fromJSON( data ) {
  20154. return new DodecahedronGeometry( data.radius, data.detail );
  20155. }
  20156. }
  20157. const _v0$1 = /*@__PURE__*/ new Vector3();
  20158. const _v1$1 = /*@__PURE__*/ new Vector3();
  20159. const _normal = /*@__PURE__*/ new Vector3();
  20160. const _triangle = /*@__PURE__*/ new Triangle();
  20161. /**
  20162. * Can be used as a helper object to view the edges of a geometry.
  20163. *
  20164. * ```js
  20165. * const geometry = new THREE.BoxGeometry();
  20166. * const edges = new THREE.EdgesGeometry( geometry );
  20167. * const line = new THREE.LineSegments( edges );
  20168. * scene.add( line );
  20169. * ```
  20170. *
  20171. * Note: It is not yet possible to serialize/deserialize instances of this class.
  20172. *
  20173. * @augments BufferGeometry
  20174. */
  20175. class EdgesGeometry extends BufferGeometry {
  20176. /**
  20177. * Constructs a new edges geometry.
  20178. *
  20179. * @param {?BufferGeometry} [geometry=null] - The geometry.
  20180. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  20181. * between the face normals of the adjoining faces exceeds this value.
  20182. */
  20183. constructor( geometry = null, thresholdAngle = 1 ) {
  20184. super();
  20185. this.type = 'EdgesGeometry';
  20186. /**
  20187. * Holds the constructor parameters that have been
  20188. * used to generate the geometry. Any modification
  20189. * after instantiation does not change the geometry.
  20190. *
  20191. * @type {Object}
  20192. */
  20193. this.parameters = {
  20194. geometry: geometry,
  20195. thresholdAngle: thresholdAngle
  20196. };
  20197. if ( geometry !== null ) {
  20198. const precisionPoints = 4;
  20199. const precision = Math.pow( 10, precisionPoints );
  20200. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20201. const indexAttr = geometry.getIndex();
  20202. const positionAttr = geometry.getAttribute( 'position' );
  20203. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20204. const indexArr = [ 0, 0, 0 ];
  20205. const vertKeys = [ 'a', 'b', 'c' ];
  20206. const hashes = new Array( 3 );
  20207. const edgeData = {};
  20208. const vertices = [];
  20209. for ( let i = 0; i < indexCount; i += 3 ) {
  20210. if ( indexAttr ) {
  20211. indexArr[ 0 ] = indexAttr.getX( i );
  20212. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20213. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20214. } else {
  20215. indexArr[ 0 ] = i;
  20216. indexArr[ 1 ] = i + 1;
  20217. indexArr[ 2 ] = i + 2;
  20218. }
  20219. const { a, b, c } = _triangle;
  20220. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20221. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20222. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20223. _triangle.getNormal( _normal );
  20224. // create hashes for the edge from the vertices
  20225. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20226. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20227. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20228. // skip degenerate triangles
  20229. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20230. continue;
  20231. }
  20232. // iterate over every edge
  20233. for ( let j = 0; j < 3; j ++ ) {
  20234. // get the first and next vertex making up the edge
  20235. const jNext = ( j + 1 ) % 3;
  20236. const vecHash0 = hashes[ j ];
  20237. const vecHash1 = hashes[ jNext ];
  20238. const v0 = _triangle[ vertKeys[ j ] ];
  20239. const v1 = _triangle[ vertKeys[ jNext ] ];
  20240. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20241. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20242. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20243. // if we found a sibling edge add it into the vertex array if
  20244. // it meets the angle threshold and delete the edge from the map.
  20245. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20246. vertices.push( v0.x, v0.y, v0.z );
  20247. vertices.push( v1.x, v1.y, v1.z );
  20248. }
  20249. edgeData[ reverseHash ] = null;
  20250. } else if ( ! ( hash in edgeData ) ) {
  20251. // if we've already got an edge here then skip adding a new one
  20252. edgeData[ hash ] = {
  20253. index0: indexArr[ j ],
  20254. index1: indexArr[ jNext ],
  20255. normal: _normal.clone(),
  20256. };
  20257. }
  20258. }
  20259. }
  20260. // iterate over all remaining, unmatched edges and add them to the vertex array
  20261. for ( const key in edgeData ) {
  20262. if ( edgeData[ key ] ) {
  20263. const { index0, index1 } = edgeData[ key ];
  20264. _v0$1.fromBufferAttribute( positionAttr, index0 );
  20265. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20266. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  20267. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20268. }
  20269. }
  20270. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20271. }
  20272. }
  20273. copy( source ) {
  20274. super.copy( source );
  20275. this.parameters = Object.assign( {}, source.parameters );
  20276. return this;
  20277. }
  20278. }
  20279. /**
  20280. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  20281. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  20282. * points, or to get triangulated faces.
  20283. *
  20284. * ```js
  20285. * const heartShape = new THREE.Shape();
  20286. *
  20287. * heartShape.moveTo( 25, 25 );
  20288. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  20289. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  20290. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  20291. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  20292. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  20293. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  20294. *
  20295. * const extrudeSettings = {
  20296. * depth: 8,
  20297. * bevelEnabled: true,
  20298. * bevelSegments: 2,
  20299. * steps: 2,
  20300. * bevelSize: 1,
  20301. * bevelThickness: 1
  20302. * };
  20303. *
  20304. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  20305. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  20306. * ```
  20307. *
  20308. * @augments Path
  20309. */
  20310. class Shape extends Path {
  20311. /**
  20312. * Constructs a new shape.
  20313. *
  20314. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  20315. */
  20316. constructor( points ) {
  20317. super( points );
  20318. /**
  20319. * The UUID of the shape.
  20320. *
  20321. * @type {string}
  20322. * @readonly
  20323. */
  20324. this.uuid = generateUUID();
  20325. this.type = 'Shape';
  20326. /**
  20327. * Defines the holes in the shape. Hole definitions must use the
  20328. * opposite winding order (CW/CCW) than the outer shape.
  20329. *
  20330. * @type {Array<Path>}
  20331. * @readonly
  20332. */
  20333. this.holes = [];
  20334. }
  20335. /**
  20336. * Returns an array representing each contour of the holes
  20337. * as a list of 2D points.
  20338. *
  20339. * @param {number} divisions - The fineness of the result.
  20340. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  20341. */
  20342. getPointsHoles( divisions ) {
  20343. const holesPts = [];
  20344. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20345. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20346. }
  20347. return holesPts;
  20348. }
  20349. // get points of shape and holes (keypoints based on segments parameter)
  20350. /**
  20351. * Returns an object that holds contour data for the shape and its holes as
  20352. * arrays of 2D points.
  20353. *
  20354. * @param {number} divisions - The fineness of the result.
  20355. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  20356. */
  20357. extractPoints( divisions ) {
  20358. return {
  20359. shape: this.getPoints( divisions ),
  20360. holes: this.getPointsHoles( divisions )
  20361. };
  20362. }
  20363. copy( source ) {
  20364. super.copy( source );
  20365. this.holes = [];
  20366. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20367. const hole = source.holes[ i ];
  20368. this.holes.push( hole.clone() );
  20369. }
  20370. return this;
  20371. }
  20372. toJSON() {
  20373. const data = super.toJSON();
  20374. data.uuid = this.uuid;
  20375. data.holes = [];
  20376. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20377. const hole = this.holes[ i ];
  20378. data.holes.push( hole.toJSON() );
  20379. }
  20380. return data;
  20381. }
  20382. fromJSON( json ) {
  20383. super.fromJSON( json );
  20384. this.uuid = json.uuid;
  20385. this.holes = [];
  20386. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20387. const hole = json.holes[ i ];
  20388. this.holes.push( new Path().fromJSON( hole ) );
  20389. }
  20390. return this;
  20391. }
  20392. }
  20393. /**
  20394. * An implementation of the earcut polygon triangulation algorithm. The code
  20395. * is a port of [mapbox/earcut]{@link https://github.com/mapbox/earcut mapbox/earcut} (v2.2.4).
  20396. *
  20397. * @hideconstructor
  20398. */
  20399. class Earcut {
  20400. /**
  20401. * Triangulates the given shape definition by returning an array of triangles.
  20402. *
  20403. * @param {Array<number>} data - An array with 2D points.
  20404. * @param {Array<number>} holeIndices - An array with indices defining holes.
  20405. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  20406. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  20407. * representing vertex indices.
  20408. */
  20409. static triangulate( data, holeIndices, dim = 2 ) {
  20410. const hasHoles = holeIndices && holeIndices.length;
  20411. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20412. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20413. const triangles = [];
  20414. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20415. let minX, minY, maxX, maxY, x, y, invSize;
  20416. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20417. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20418. if ( data.length > 80 * dim ) {
  20419. minX = maxX = data[ 0 ];
  20420. minY = maxY = data[ 1 ];
  20421. for ( let i = dim; i < outerLen; i += dim ) {
  20422. x = data[ i ];
  20423. y = data[ i + 1 ];
  20424. if ( x < minX ) minX = x;
  20425. if ( y < minY ) minY = y;
  20426. if ( x > maxX ) maxX = x;
  20427. if ( y > maxY ) maxY = y;
  20428. }
  20429. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20430. invSize = Math.max( maxX - minX, maxY - minY );
  20431. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20432. }
  20433. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  20434. return triangles;
  20435. }
  20436. }
  20437. // create a circular doubly linked list from polygon points in the specified winding order
  20438. function linkedList( data, start, end, dim, clockwise ) {
  20439. let i, last;
  20440. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20441. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20442. } else {
  20443. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20444. }
  20445. if ( last && equals( last, last.next ) ) {
  20446. removeNode( last );
  20447. last = last.next;
  20448. }
  20449. return last;
  20450. }
  20451. // eliminate colinear or duplicate points
  20452. function filterPoints( start, end ) {
  20453. if ( ! start ) return start;
  20454. if ( ! end ) end = start;
  20455. let p = start,
  20456. again;
  20457. do {
  20458. again = false;
  20459. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20460. removeNode( p );
  20461. p = end = p.prev;
  20462. if ( p === p.next ) break;
  20463. again = true;
  20464. } else {
  20465. p = p.next;
  20466. }
  20467. } while ( again || p !== end );
  20468. return end;
  20469. }
  20470. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20471. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20472. if ( ! ear ) return;
  20473. // interlink polygon nodes in z-order
  20474. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20475. let stop = ear,
  20476. prev, next;
  20477. // iterate through ears, slicing them one by one
  20478. while ( ear.prev !== ear.next ) {
  20479. prev = ear.prev;
  20480. next = ear.next;
  20481. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20482. // cut off the triangle
  20483. triangles.push( prev.i / dim | 0 );
  20484. triangles.push( ear.i / dim | 0 );
  20485. triangles.push( next.i / dim | 0 );
  20486. removeNode( ear );
  20487. // skipping the next vertex leads to less sliver triangles
  20488. ear = next.next;
  20489. stop = next.next;
  20490. continue;
  20491. }
  20492. ear = next;
  20493. // if we looped through the whole remaining polygon and can't find any more ears
  20494. if ( ear === stop ) {
  20495. // try filtering points and slicing again
  20496. if ( ! pass ) {
  20497. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20498. // if this didn't work, try curing all small self-intersections locally
  20499. } else if ( pass === 1 ) {
  20500. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20501. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20502. // as a last resort, try splitting the remaining polygon into two
  20503. } else if ( pass === 2 ) {
  20504. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20505. }
  20506. break;
  20507. }
  20508. }
  20509. }
  20510. // check whether a polygon node forms a valid ear with adjacent nodes
  20511. function isEar( ear ) {
  20512. const a = ear.prev,
  20513. b = ear,
  20514. c = ear.next;
  20515. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20516. // now make sure we don't have other points inside the potential ear
  20517. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20518. // triangle bbox; min & max are calculated like this for speed
  20519. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20520. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20521. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20522. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20523. let p = c.next;
  20524. while ( p !== a ) {
  20525. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  20526. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  20527. area( p.prev, p, p.next ) >= 0 ) return false;
  20528. p = p.next;
  20529. }
  20530. return true;
  20531. }
  20532. function isEarHashed( ear, minX, minY, invSize ) {
  20533. const a = ear.prev,
  20534. b = ear,
  20535. c = ear.next;
  20536. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20537. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20538. // triangle bbox; min & max are calculated like this for speed
  20539. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20540. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20541. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20542. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20543. // z-order range for the current triangle bbox;
  20544. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  20545. maxZ = zOrder( x1, y1, minX, minY, invSize );
  20546. let p = ear.prevZ,
  20547. n = ear.nextZ;
  20548. // look for points inside the triangle in both directions
  20549. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20550. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20551. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20552. p = p.prevZ;
  20553. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20554. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20555. n = n.nextZ;
  20556. }
  20557. // look for remaining points in decreasing z-order
  20558. while ( p && p.z >= minZ ) {
  20559. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20560. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20561. p = p.prevZ;
  20562. }
  20563. // look for remaining points in increasing z-order
  20564. while ( n && n.z <= maxZ ) {
  20565. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20566. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20567. n = n.nextZ;
  20568. }
  20569. return true;
  20570. }
  20571. // go through all polygon nodes and cure small local self-intersections
  20572. function cureLocalIntersections( start, triangles, dim ) {
  20573. let p = start;
  20574. do {
  20575. const a = p.prev,
  20576. b = p.next.next;
  20577. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20578. triangles.push( a.i / dim | 0 );
  20579. triangles.push( p.i / dim | 0 );
  20580. triangles.push( b.i / dim | 0 );
  20581. // remove two nodes involved
  20582. removeNode( p );
  20583. removeNode( p.next );
  20584. p = start = b;
  20585. }
  20586. p = p.next;
  20587. } while ( p !== start );
  20588. return filterPoints( p );
  20589. }
  20590. // try splitting polygon into two and triangulate them independently
  20591. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20592. // look for a valid diagonal that divides the polygon into two
  20593. let a = start;
  20594. do {
  20595. let b = a.next.next;
  20596. while ( b !== a.prev ) {
  20597. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20598. // split the polygon in two by the diagonal
  20599. let c = splitPolygon( a, b );
  20600. // filter colinear points around the cuts
  20601. a = filterPoints( a, a.next );
  20602. c = filterPoints( c, c.next );
  20603. // run earcut on each half
  20604. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  20605. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  20606. return;
  20607. }
  20608. b = b.next;
  20609. }
  20610. a = a.next;
  20611. } while ( a !== start );
  20612. }
  20613. // link every hole into the outer loop, producing a single-ring polygon without holes
  20614. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20615. const queue = [];
  20616. let i, len, start, end, list;
  20617. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20618. start = holeIndices[ i ] * dim;
  20619. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20620. list = linkedList( data, start, end, dim, false );
  20621. if ( list === list.next ) list.steiner = true;
  20622. queue.push( getLeftmost( list ) );
  20623. }
  20624. queue.sort( compareX );
  20625. // process holes from left to right
  20626. for ( i = 0; i < queue.length; i ++ ) {
  20627. outerNode = eliminateHole( queue[ i ], outerNode );
  20628. }
  20629. return outerNode;
  20630. }
  20631. function compareX( a, b ) {
  20632. return a.x - b.x;
  20633. }
  20634. // find a bridge between vertices that connects hole with an outer ring and link it
  20635. function eliminateHole( hole, outerNode ) {
  20636. const bridge = findHoleBridge( hole, outerNode );
  20637. if ( ! bridge ) {
  20638. return outerNode;
  20639. }
  20640. const bridgeReverse = splitPolygon( bridge, hole );
  20641. // filter collinear points around the cuts
  20642. filterPoints( bridgeReverse, bridgeReverse.next );
  20643. return filterPoints( bridge, bridge.next );
  20644. }
  20645. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20646. function findHoleBridge( hole, outerNode ) {
  20647. let p = outerNode,
  20648. qx = - Infinity,
  20649. m;
  20650. const hx = hole.x, hy = hole.y;
  20651. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20652. // segment's endpoint with lesser x will be potential connection point
  20653. do {
  20654. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20655. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20656. if ( x <= hx && x > qx ) {
  20657. qx = x;
  20658. m = p.x < p.next.x ? p : p.next;
  20659. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  20660. }
  20661. }
  20662. p = p.next;
  20663. } while ( p !== outerNode );
  20664. if ( ! m ) return null;
  20665. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20666. // if there are no points found, we have a valid connection;
  20667. // otherwise choose the point of the minimum angle with the ray as connection point
  20668. const stop = m,
  20669. mx = m.x,
  20670. my = m.y;
  20671. let tanMin = Infinity, tan;
  20672. p = m;
  20673. do {
  20674. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20675. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20676. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20677. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20678. m = p;
  20679. tanMin = tan;
  20680. }
  20681. }
  20682. p = p.next;
  20683. } while ( p !== stop );
  20684. return m;
  20685. }
  20686. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20687. function sectorContainsSector( m, p ) {
  20688. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20689. }
  20690. // interlink polygon nodes in z-order
  20691. function indexCurve( start, minX, minY, invSize ) {
  20692. let p = start;
  20693. do {
  20694. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20695. p.prevZ = p.prev;
  20696. p.nextZ = p.next;
  20697. p = p.next;
  20698. } while ( p !== start );
  20699. p.prevZ.nextZ = null;
  20700. p.prevZ = null;
  20701. sortLinked( p );
  20702. }
  20703. // Simon Tatham's linked list merge sort algorithm
  20704. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20705. function sortLinked( list ) {
  20706. let i, p, q, e, tail, numMerges, pSize, qSize,
  20707. inSize = 1;
  20708. do {
  20709. p = list;
  20710. list = null;
  20711. tail = null;
  20712. numMerges = 0;
  20713. while ( p ) {
  20714. numMerges ++;
  20715. q = p;
  20716. pSize = 0;
  20717. for ( i = 0; i < inSize; i ++ ) {
  20718. pSize ++;
  20719. q = q.nextZ;
  20720. if ( ! q ) break;
  20721. }
  20722. qSize = inSize;
  20723. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20724. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20725. e = p;
  20726. p = p.nextZ;
  20727. pSize --;
  20728. } else {
  20729. e = q;
  20730. q = q.nextZ;
  20731. qSize --;
  20732. }
  20733. if ( tail ) tail.nextZ = e;
  20734. else list = e;
  20735. e.prevZ = tail;
  20736. tail = e;
  20737. }
  20738. p = q;
  20739. }
  20740. tail.nextZ = null;
  20741. inSize *= 2;
  20742. } while ( numMerges > 1 );
  20743. return list;
  20744. }
  20745. // z-order of a point given coords and inverse of the longer side of data bbox
  20746. function zOrder( x, y, minX, minY, invSize ) {
  20747. // coords are transformed into non-negative 15-bit integer range
  20748. x = ( x - minX ) * invSize | 0;
  20749. y = ( y - minY ) * invSize | 0;
  20750. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20751. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20752. x = ( x | ( x << 2 ) ) & 0x33333333;
  20753. x = ( x | ( x << 1 ) ) & 0x55555555;
  20754. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20755. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20756. y = ( y | ( y << 2 ) ) & 0x33333333;
  20757. y = ( y | ( y << 1 ) ) & 0x55555555;
  20758. return x | ( y << 1 );
  20759. }
  20760. // find the leftmost node of a polygon ring
  20761. function getLeftmost( start ) {
  20762. let p = start,
  20763. leftmost = start;
  20764. do {
  20765. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20766. p = p.next;
  20767. } while ( p !== start );
  20768. return leftmost;
  20769. }
  20770. // check if a point lies within a convex triangle
  20771. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20772. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  20773. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  20774. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  20775. }
  20776. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20777. function isValidDiagonal( a, b ) {
  20778. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges
  20779. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20780. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20781. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20782. }
  20783. // signed area of a triangle
  20784. function area( p, q, r ) {
  20785. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20786. }
  20787. // check if two points are equal
  20788. function equals( p1, p2 ) {
  20789. return p1.x === p2.x && p1.y === p2.y;
  20790. }
  20791. // check if two segments intersect
  20792. function intersects( p1, q1, p2, q2 ) {
  20793. const o1 = sign( area( p1, q1, p2 ) );
  20794. const o2 = sign( area( p1, q1, q2 ) );
  20795. const o3 = sign( area( p2, q2, p1 ) );
  20796. const o4 = sign( area( p2, q2, q1 ) );
  20797. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20798. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20799. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20800. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20801. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20802. return false;
  20803. }
  20804. // for collinear points p, q, r, check if point q lies on segment pr
  20805. function onSegment( p, q, r ) {
  20806. 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 );
  20807. }
  20808. function sign( num ) {
  20809. return num > 0 ? 1 : num < 0 ? -1 : 0;
  20810. }
  20811. // check if a polygon diagonal intersects any polygon segments
  20812. function intersectsPolygon( a, b ) {
  20813. let p = a;
  20814. do {
  20815. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20816. intersects( p, p.next, a, b ) ) return true;
  20817. p = p.next;
  20818. } while ( p !== a );
  20819. return false;
  20820. }
  20821. // check if a polygon diagonal is locally inside the polygon
  20822. function locallyInside( a, b ) {
  20823. return area( a.prev, a, a.next ) < 0 ?
  20824. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20825. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20826. }
  20827. // check if the middle point of a polygon diagonal is inside the polygon
  20828. function middleInside( a, b ) {
  20829. let p = a,
  20830. inside = false;
  20831. const px = ( a.x + b.x ) / 2,
  20832. py = ( a.y + b.y ) / 2;
  20833. do {
  20834. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20835. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20836. inside = ! inside;
  20837. p = p.next;
  20838. } while ( p !== a );
  20839. return inside;
  20840. }
  20841. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20842. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20843. function splitPolygon( a, b ) {
  20844. const a2 = new Node( a.i, a.x, a.y ),
  20845. b2 = new Node( b.i, b.x, b.y ),
  20846. an = a.next,
  20847. bp = b.prev;
  20848. a.next = b;
  20849. b.prev = a;
  20850. a2.next = an;
  20851. an.prev = a2;
  20852. b2.next = a2;
  20853. a2.prev = b2;
  20854. bp.next = b2;
  20855. b2.prev = bp;
  20856. return b2;
  20857. }
  20858. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20859. function insertNode( i, x, y, last ) {
  20860. const p = new Node( i, x, y );
  20861. if ( ! last ) {
  20862. p.prev = p;
  20863. p.next = p;
  20864. } else {
  20865. p.next = last.next;
  20866. p.prev = last;
  20867. last.next.prev = p;
  20868. last.next = p;
  20869. }
  20870. return p;
  20871. }
  20872. function removeNode( p ) {
  20873. p.next.prev = p.prev;
  20874. p.prev.next = p.next;
  20875. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20876. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20877. }
  20878. function Node( i, x, y ) {
  20879. // vertex index in coordinates array
  20880. this.i = i;
  20881. // vertex coordinates
  20882. this.x = x;
  20883. this.y = y;
  20884. // previous and next vertex nodes in a polygon ring
  20885. this.prev = null;
  20886. this.next = null;
  20887. // z-order curve value
  20888. this.z = 0;
  20889. // previous and next nodes in z-order
  20890. this.prevZ = null;
  20891. this.nextZ = null;
  20892. // indicates whether this is a steiner point
  20893. this.steiner = false;
  20894. }
  20895. function signedArea( data, start, end, dim ) {
  20896. let sum = 0;
  20897. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20898. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20899. j = i;
  20900. }
  20901. return sum;
  20902. }
  20903. /**
  20904. * A class containing utility functions for shapes.
  20905. *
  20906. * @hideconstructor
  20907. */
  20908. class ShapeUtils {
  20909. /**
  20910. * Calculate area of a ( 2D ) contour polygon.
  20911. *
  20912. * @param {Array<Vector2>} contour - An array of 2D points.
  20913. * @return {number} The area.
  20914. */
  20915. static area( contour ) {
  20916. const n = contour.length;
  20917. let a = 0.0;
  20918. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  20919. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20920. }
  20921. return a * 0.5;
  20922. }
  20923. /**
  20924. * Returns `true` if the given contour uses a clockwise winding order.
  20925. *
  20926. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  20927. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  20928. */
  20929. static isClockWise( pts ) {
  20930. return ShapeUtils.area( pts ) < 0;
  20931. }
  20932. /**
  20933. * Triangulates the given shape definition.
  20934. *
  20935. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  20936. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  20937. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  20938. */
  20939. static triangulateShape( contour, holes ) {
  20940. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20941. const holeIndices = []; // array of hole indices
  20942. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20943. removeDupEndPts( contour );
  20944. addContour( vertices, contour );
  20945. //
  20946. let holeIndex = contour.length;
  20947. holes.forEach( removeDupEndPts );
  20948. for ( let i = 0; i < holes.length; i ++ ) {
  20949. holeIndices.push( holeIndex );
  20950. holeIndex += holes[ i ].length;
  20951. addContour( vertices, holes[ i ] );
  20952. }
  20953. //
  20954. const triangles = Earcut.triangulate( vertices, holeIndices );
  20955. //
  20956. for ( let i = 0; i < triangles.length; i += 3 ) {
  20957. faces.push( triangles.slice( i, i + 3 ) );
  20958. }
  20959. return faces;
  20960. }
  20961. }
  20962. function removeDupEndPts( points ) {
  20963. const l = points.length;
  20964. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20965. points.pop();
  20966. }
  20967. }
  20968. function addContour( vertices, contour ) {
  20969. for ( let i = 0; i < contour.length; i ++ ) {
  20970. vertices.push( contour[ i ].x );
  20971. vertices.push( contour[ i ].y );
  20972. }
  20973. }
  20974. /**
  20975. * Creates extruded geometry from a path shape.
  20976. *
  20977. * parameters = {
  20978. *
  20979. * curveSegments: <int>, // number of points on the curves
  20980. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20981. * depth: <float>, // Depth to extrude the shape
  20982. *
  20983. * bevelEnabled: <bool>, // turn on bevel
  20984. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20985. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20986. * bevelOffset: <float>, // how far from shape outline does bevel start
  20987. * bevelSegments: <int>, // number of bevel layers
  20988. *
  20989. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20990. *
  20991. * UVGenerator: <Object> // object that provides UV generator functions
  20992. *
  20993. * }
  20994. */
  20995. /**
  20996. * Creates extruded geometry from a path shape.
  20997. *
  20998. * ```js
  20999. * const length = 12, width = 8;
  21000. *
  21001. * const shape = new THREE.Shape();
  21002. * shape.moveTo( 0,0 );
  21003. * shape.lineTo( 0, width );
  21004. * shape.lineTo( length, width );
  21005. * shape.lineTo( length, 0 );
  21006. * shape.lineTo( 0, 0 );
  21007. *
  21008. * const geometry = new THREE.ExtrudeGeometry( shape );
  21009. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21010. * const mesh = new THREE.Mesh( geometry, material ) ;
  21011. * scene.add( mesh );
  21012. * ```
  21013. *
  21014. * @augments BufferGeometry
  21015. */
  21016. class ExtrudeGeometry extends BufferGeometry {
  21017. /**
  21018. * Constructs a new extrude geometry.
  21019. *
  21020. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  21021. * @param {Object} [options={}] - The extrude settings.
  21022. * @param {number} [options.curveSegments=12] - Number of points on the curves.
  21023. * @param {number} [options.steps=1] - Number of points used for subdividing segments along the depth of the extruded spline.
  21024. * @param {number} [options.depth=1] - Depth to extrude the shape.
  21025. * @param {boolean} [options.bevelEnabled=true] - Whether to beveling to the shape or not.
  21026. * @param {number} [options.bevelThickness=0.2] - How deep into the original shape the bevel goes.
  21027. * @param {number} [options.bevelSize=bevelThickness-0.1] - Distance from the shape outline that the bevel extends.
  21028. * @param {number} [options.bevelOffset=0] - Distance from the shape outline that the bevel starts.
  21029. * @param {number} [options.bevelSegments=3] - Number of bevel layers.
  21030. * @param {Curve} [options.extrudePath=3] - A 3D spline path along which the shape should be extruded. Bevels not supported for path extrusion.
  21031. * @param {Object} [options.UVGenerator] - An object that provides UV generator functions for custom UV generation.
  21032. */
  21033. 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 = {} ) {
  21034. super();
  21035. this.type = 'ExtrudeGeometry';
  21036. /**
  21037. * Holds the constructor parameters that have been
  21038. * used to generate the geometry. Any modification
  21039. * after instantiation does not change the geometry.
  21040. *
  21041. * @type {Object}
  21042. */
  21043. this.parameters = {
  21044. shapes: shapes,
  21045. options: options
  21046. };
  21047. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21048. const scope = this;
  21049. const verticesArray = [];
  21050. const uvArray = [];
  21051. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21052. const shape = shapes[ i ];
  21053. addShape( shape );
  21054. }
  21055. // build geometry
  21056. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21057. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21058. this.computeVertexNormals();
  21059. // functions
  21060. function addShape( shape ) {
  21061. const placeholder = [];
  21062. // options
  21063. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21064. const steps = options.steps !== undefined ? options.steps : 1;
  21065. const depth = options.depth !== undefined ? options.depth : 1;
  21066. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21067. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21068. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21069. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21070. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21071. const extrudePath = options.extrudePath;
  21072. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21073. //
  21074. let extrudePts, extrudeByPath = false;
  21075. let splineTube, binormal, normal, position2;
  21076. if ( extrudePath ) {
  21077. extrudePts = extrudePath.getSpacedPoints( steps );
  21078. extrudeByPath = true;
  21079. bevelEnabled = false; // bevels not supported for path extrusion
  21080. // SETUP TNB variables
  21081. // TODO1 - have a .isClosed in spline?
  21082. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21083. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21084. binormal = new Vector3();
  21085. normal = new Vector3();
  21086. position2 = new Vector3();
  21087. }
  21088. // Safeguards if bevels are not enabled
  21089. if ( ! bevelEnabled ) {
  21090. bevelSegments = 0;
  21091. bevelThickness = 0;
  21092. bevelSize = 0;
  21093. bevelOffset = 0;
  21094. }
  21095. // Variables initialization
  21096. const shapePoints = shape.extractPoints( curveSegments );
  21097. let vertices = shapePoints.shape;
  21098. const holes = shapePoints.holes;
  21099. const reverse = ! ShapeUtils.isClockWise( vertices );
  21100. if ( reverse ) {
  21101. vertices = vertices.reverse();
  21102. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21103. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21104. const ahole = holes[ h ];
  21105. if ( ShapeUtils.isClockWise( ahole ) ) {
  21106. holes[ h ] = ahole.reverse();
  21107. }
  21108. }
  21109. }
  21110. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21111. /* Vertices */
  21112. const contour = vertices; // vertices has all points but contour has only points of circumference
  21113. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21114. const ahole = holes[ h ];
  21115. vertices = vertices.concat( ahole );
  21116. }
  21117. function scalePt2( pt, vec, size ) {
  21118. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21119. return pt.clone().addScaledVector( vec, size );
  21120. }
  21121. const vlen = vertices.length, flen = faces.length;
  21122. // Find directions for point movement
  21123. function getBevelVec( inPt, inPrev, inNext ) {
  21124. // computes for inPt the corresponding point inPt' on a new contour
  21125. // shifted by 1 unit (length of normalized vector) to the left
  21126. // if we walk along contour clockwise, this new contour is outside the old one
  21127. //
  21128. // inPt' is the intersection of the two lines parallel to the two
  21129. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21130. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21131. // good reading for geometry algorithms (here: line-line intersection)
  21132. // http://geomalgorithms.com/a05-_intersect-1.html
  21133. const v_prev_x = inPt.x - inPrev.x,
  21134. v_prev_y = inPt.y - inPrev.y;
  21135. const v_next_x = inNext.x - inPt.x,
  21136. v_next_y = inNext.y - inPt.y;
  21137. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21138. // check for collinear edges
  21139. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21140. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21141. // not collinear
  21142. // length of vectors for normalizing
  21143. const v_prev_len = Math.sqrt( v_prev_lensq );
  21144. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21145. // shift adjacent points by unit vectors to the left
  21146. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21147. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21148. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21149. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21150. // scaling factor for v_prev to intersection point
  21151. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21152. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21153. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21154. // vector from inPt to intersection point
  21155. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21156. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21157. // Don't normalize!, otherwise sharp corners become ugly
  21158. // but prevent crazy spikes
  21159. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21160. if ( v_trans_lensq <= 2 ) {
  21161. return new Vector2( v_trans_x, v_trans_y );
  21162. } else {
  21163. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21164. }
  21165. } else {
  21166. // handle special case of collinear edges
  21167. let direction_eq = false; // assumes: opposite
  21168. if ( v_prev_x > Number.EPSILON ) {
  21169. if ( v_next_x > Number.EPSILON ) {
  21170. direction_eq = true;
  21171. }
  21172. } else {
  21173. if ( v_prev_x < - Number.EPSILON ) {
  21174. if ( v_next_x < - Number.EPSILON ) {
  21175. direction_eq = true;
  21176. }
  21177. } else {
  21178. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21179. direction_eq = true;
  21180. }
  21181. }
  21182. }
  21183. if ( direction_eq ) {
  21184. // console.log("Warning: lines are a straight sequence");
  21185. v_trans_x = - v_prev_y;
  21186. v_trans_y = v_prev_x;
  21187. shrink_by = Math.sqrt( v_prev_lensq );
  21188. } else {
  21189. // console.log("Warning: lines are a straight spike");
  21190. v_trans_x = v_prev_x;
  21191. v_trans_y = v_prev_y;
  21192. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21193. }
  21194. }
  21195. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21196. }
  21197. const contourMovements = [];
  21198. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21199. if ( j === il ) j = 0;
  21200. if ( k === il ) k = 0;
  21201. // (j)---(i)---(k)
  21202. // console.log('i,j,k', i, j , k)
  21203. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21204. }
  21205. const holesMovements = [];
  21206. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21207. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21208. const ahole = holes[ h ];
  21209. oneHoleMovements = [];
  21210. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21211. if ( j === il ) j = 0;
  21212. if ( k === il ) k = 0;
  21213. // (j)---(i)---(k)
  21214. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21215. }
  21216. holesMovements.push( oneHoleMovements );
  21217. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21218. }
  21219. // Loop bevelSegments, 1 for the front, 1 for the back
  21220. for ( let b = 0; b < bevelSegments; b ++ ) {
  21221. //for ( b = bevelSegments; b > 0; b -- ) {
  21222. const t = b / bevelSegments;
  21223. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21224. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21225. // contract shape
  21226. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21227. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21228. v( vert.x, vert.y, - z );
  21229. }
  21230. // expand holes
  21231. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21232. const ahole = holes[ h ];
  21233. oneHoleMovements = holesMovements[ h ];
  21234. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21235. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21236. v( vert.x, vert.y, - z );
  21237. }
  21238. }
  21239. }
  21240. const bs = bevelSize + bevelOffset;
  21241. // Back facing vertices
  21242. for ( let i = 0; i < vlen; i ++ ) {
  21243. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21244. if ( ! extrudeByPath ) {
  21245. v( vert.x, vert.y, 0 );
  21246. } else {
  21247. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21248. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21249. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21250. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21251. v( position2.x, position2.y, position2.z );
  21252. }
  21253. }
  21254. // Add stepped vertices...
  21255. // Including front facing vertices
  21256. for ( let s = 1; s <= steps; s ++ ) {
  21257. for ( let i = 0; i < vlen; i ++ ) {
  21258. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21259. if ( ! extrudeByPath ) {
  21260. v( vert.x, vert.y, depth / steps * s );
  21261. } else {
  21262. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21263. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21264. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21265. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21266. v( position2.x, position2.y, position2.z );
  21267. }
  21268. }
  21269. }
  21270. // Add bevel segments planes
  21271. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21272. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21273. const t = b / bevelSegments;
  21274. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21275. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21276. // contract shape
  21277. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21278. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21279. v( vert.x, vert.y, depth + z );
  21280. }
  21281. // expand holes
  21282. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21283. const ahole = holes[ h ];
  21284. oneHoleMovements = holesMovements[ h ];
  21285. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21286. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21287. if ( ! extrudeByPath ) {
  21288. v( vert.x, vert.y, depth + z );
  21289. } else {
  21290. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21291. }
  21292. }
  21293. }
  21294. }
  21295. /* Faces */
  21296. // Top and bottom faces
  21297. buildLidFaces();
  21298. // Sides faces
  21299. buildSideFaces();
  21300. ///// Internal functions
  21301. function buildLidFaces() {
  21302. const start = verticesArray.length / 3;
  21303. if ( bevelEnabled ) {
  21304. let layer = 0; // steps + 1
  21305. let offset = vlen * layer;
  21306. // Bottom faces
  21307. for ( let i = 0; i < flen; i ++ ) {
  21308. const face = faces[ i ];
  21309. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21310. }
  21311. layer = steps + bevelSegments * 2;
  21312. offset = vlen * layer;
  21313. // Top faces
  21314. for ( let i = 0; i < flen; i ++ ) {
  21315. const face = faces[ i ];
  21316. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21317. }
  21318. } else {
  21319. // Bottom faces
  21320. for ( let i = 0; i < flen; i ++ ) {
  21321. const face = faces[ i ];
  21322. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21323. }
  21324. // Top faces
  21325. for ( let i = 0; i < flen; i ++ ) {
  21326. const face = faces[ i ];
  21327. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21328. }
  21329. }
  21330. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21331. }
  21332. // Create faces for the z-sides of the shape
  21333. function buildSideFaces() {
  21334. const start = verticesArray.length / 3;
  21335. let layeroffset = 0;
  21336. sidewalls( contour, layeroffset );
  21337. layeroffset += contour.length;
  21338. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21339. const ahole = holes[ h ];
  21340. sidewalls( ahole, layeroffset );
  21341. //, true
  21342. layeroffset += ahole.length;
  21343. }
  21344. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21345. }
  21346. function sidewalls( contour, layeroffset ) {
  21347. let i = contour.length;
  21348. while ( -- i >= 0 ) {
  21349. const j = i;
  21350. let k = i - 1;
  21351. if ( k < 0 ) k = contour.length - 1;
  21352. //console.log('b', i,j, i-1, k,vertices.length);
  21353. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21354. const slen1 = vlen * s;
  21355. const slen2 = vlen * ( s + 1 );
  21356. const a = layeroffset + j + slen1,
  21357. b = layeroffset + k + slen1,
  21358. c = layeroffset + k + slen2,
  21359. d = layeroffset + j + slen2;
  21360. f4( a, b, c, d );
  21361. }
  21362. }
  21363. }
  21364. function v( x, y, z ) {
  21365. placeholder.push( x );
  21366. placeholder.push( y );
  21367. placeholder.push( z );
  21368. }
  21369. function f3( a, b, c ) {
  21370. addVertex( a );
  21371. addVertex( b );
  21372. addVertex( c );
  21373. const nextIndex = verticesArray.length / 3;
  21374. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21375. addUV( uvs[ 0 ] );
  21376. addUV( uvs[ 1 ] );
  21377. addUV( uvs[ 2 ] );
  21378. }
  21379. function f4( a, b, c, d ) {
  21380. addVertex( a );
  21381. addVertex( b );
  21382. addVertex( d );
  21383. addVertex( b );
  21384. addVertex( c );
  21385. addVertex( d );
  21386. const nextIndex = verticesArray.length / 3;
  21387. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21388. addUV( uvs[ 0 ] );
  21389. addUV( uvs[ 1 ] );
  21390. addUV( uvs[ 3 ] );
  21391. addUV( uvs[ 1 ] );
  21392. addUV( uvs[ 2 ] );
  21393. addUV( uvs[ 3 ] );
  21394. }
  21395. function addVertex( index ) {
  21396. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21397. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21398. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21399. }
  21400. function addUV( vector2 ) {
  21401. uvArray.push( vector2.x );
  21402. uvArray.push( vector2.y );
  21403. }
  21404. }
  21405. }
  21406. copy( source ) {
  21407. super.copy( source );
  21408. this.parameters = Object.assign( {}, source.parameters );
  21409. return this;
  21410. }
  21411. toJSON() {
  21412. const data = super.toJSON();
  21413. const shapes = this.parameters.shapes;
  21414. const options = this.parameters.options;
  21415. return toJSON$1( shapes, options, data );
  21416. }
  21417. /**
  21418. * Factory method for creating an instance of this class from the given
  21419. * JSON object.
  21420. *
  21421. * @param {Object} data - A JSON object representing the serialized geometry.
  21422. * @param {Array<Shape>} shapes - An array of shapes.
  21423. * @return {ExtrudeGeometry} A new instance.
  21424. */
  21425. static fromJSON( data, shapes ) {
  21426. const geometryShapes = [];
  21427. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21428. const shape = shapes[ data.shapes[ j ] ];
  21429. geometryShapes.push( shape );
  21430. }
  21431. const extrudePath = data.options.extrudePath;
  21432. if ( extrudePath !== undefined ) {
  21433. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21434. }
  21435. return new ExtrudeGeometry( geometryShapes, data.options );
  21436. }
  21437. }
  21438. const WorldUVGenerator = {
  21439. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21440. const a_x = vertices[ indexA * 3 ];
  21441. const a_y = vertices[ indexA * 3 + 1 ];
  21442. const b_x = vertices[ indexB * 3 ];
  21443. const b_y = vertices[ indexB * 3 + 1 ];
  21444. const c_x = vertices[ indexC * 3 ];
  21445. const c_y = vertices[ indexC * 3 + 1 ];
  21446. return [
  21447. new Vector2( a_x, a_y ),
  21448. new Vector2( b_x, b_y ),
  21449. new Vector2( c_x, c_y )
  21450. ];
  21451. },
  21452. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21453. const a_x = vertices[ indexA * 3 ];
  21454. const a_y = vertices[ indexA * 3 + 1 ];
  21455. const a_z = vertices[ indexA * 3 + 2 ];
  21456. const b_x = vertices[ indexB * 3 ];
  21457. const b_y = vertices[ indexB * 3 + 1 ];
  21458. const b_z = vertices[ indexB * 3 + 2 ];
  21459. const c_x = vertices[ indexC * 3 ];
  21460. const c_y = vertices[ indexC * 3 + 1 ];
  21461. const c_z = vertices[ indexC * 3 + 2 ];
  21462. const d_x = vertices[ indexD * 3 ];
  21463. const d_y = vertices[ indexD * 3 + 1 ];
  21464. const d_z = vertices[ indexD * 3 + 2 ];
  21465. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21466. return [
  21467. new Vector2( a_x, 1 - a_z ),
  21468. new Vector2( b_x, 1 - b_z ),
  21469. new Vector2( c_x, 1 - c_z ),
  21470. new Vector2( d_x, 1 - d_z )
  21471. ];
  21472. } else {
  21473. return [
  21474. new Vector2( a_y, 1 - a_z ),
  21475. new Vector2( b_y, 1 - b_z ),
  21476. new Vector2( c_y, 1 - c_z ),
  21477. new Vector2( d_y, 1 - d_z )
  21478. ];
  21479. }
  21480. }
  21481. };
  21482. function toJSON$1( shapes, options, data ) {
  21483. data.shapes = [];
  21484. if ( Array.isArray( shapes ) ) {
  21485. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21486. const shape = shapes[ i ];
  21487. data.shapes.push( shape.uuid );
  21488. }
  21489. } else {
  21490. data.shapes.push( shapes.uuid );
  21491. }
  21492. data.options = Object.assign( {}, options );
  21493. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21494. return data;
  21495. }
  21496. /**
  21497. * A geometry class for representing an icosahedron.
  21498. *
  21499. * ```js
  21500. * const geometry = new THREE.IcosahedronGeometry();
  21501. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21502. * const icosahedron = new THREE.Mesh( geometry, material );
  21503. * scene.add( icosahedron );
  21504. * ```
  21505. *
  21506. * @augments PolyhedronGeometry
  21507. */
  21508. class IcosahedronGeometry extends PolyhedronGeometry {
  21509. /**
  21510. * Constructs a new icosahedron geometry.
  21511. *
  21512. * @param {number} [radius=1] - Radius of the icosahedron.
  21513. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  21514. */
  21515. constructor( radius = 1, detail = 0 ) {
  21516. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21517. const vertices = [
  21518. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  21519. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  21520. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  21521. ];
  21522. const indices = [
  21523. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21524. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21525. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21526. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21527. ];
  21528. super( vertices, indices, radius, detail );
  21529. this.type = 'IcosahedronGeometry';
  21530. /**
  21531. * Holds the constructor parameters that have been
  21532. * used to generate the geometry. Any modification
  21533. * after instantiation does not change the geometry.
  21534. *
  21535. * @type {Object}
  21536. */
  21537. this.parameters = {
  21538. radius: radius,
  21539. detail: detail
  21540. };
  21541. }
  21542. /**
  21543. * Factory method for creating an instance of this class from the given
  21544. * JSON object.
  21545. *
  21546. * @param {Object} data - A JSON object representing the serialized geometry.
  21547. * @return {IcosahedronGeometry} A new instance.
  21548. */
  21549. static fromJSON( data ) {
  21550. return new IcosahedronGeometry( data.radius, data.detail );
  21551. }
  21552. }
  21553. /**
  21554. * A geometry class for representing an octahedron.
  21555. *
  21556. * ```js
  21557. * const geometry = new THREE.OctahedronGeometry();
  21558. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21559. * const octahedron = new THREE.Mesh( geometry, material );
  21560. * scene.add( octahedron );
  21561. * ```
  21562. *
  21563. * @augments PolyhedronGeometry
  21564. */
  21565. class OctahedronGeometry extends PolyhedronGeometry {
  21566. /**
  21567. * Constructs a new octahedron geometry.
  21568. *
  21569. * @param {number} [radius=1] - Radius of the octahedron.
  21570. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  21571. */
  21572. constructor( radius = 1, detail = 0 ) {
  21573. const vertices = [
  21574. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  21575. 0, -1, 0, 0, 0, 1, 0, 0, -1
  21576. ];
  21577. const indices = [
  21578. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21579. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21580. 1, 3, 4, 1, 4, 2
  21581. ];
  21582. super( vertices, indices, radius, detail );
  21583. this.type = 'OctahedronGeometry';
  21584. /**
  21585. * Holds the constructor parameters that have been
  21586. * used to generate the geometry. Any modification
  21587. * after instantiation does not change the geometry.
  21588. *
  21589. * @type {Object}
  21590. */
  21591. this.parameters = {
  21592. radius: radius,
  21593. detail: detail
  21594. };
  21595. }
  21596. /**
  21597. * Factory method for creating an instance of this class from the given
  21598. * JSON object.
  21599. *
  21600. * @param {Object} data - A JSON object representing the serialized geometry.
  21601. * @return {OctahedronGeometry} A new instance.
  21602. */
  21603. static fromJSON( data ) {
  21604. return new OctahedronGeometry( data.radius, data.detail );
  21605. }
  21606. }
  21607. /**
  21608. * A geometry class for representing a plane.
  21609. *
  21610. * ```js
  21611. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  21612. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  21613. * const plane = new THREE.Mesh( geometry, material );
  21614. * scene.add( plane );
  21615. * ```
  21616. *
  21617. * @augments BufferGeometry
  21618. */
  21619. class PlaneGeometry extends BufferGeometry {
  21620. /**
  21621. * Constructs a new plane geometry.
  21622. *
  21623. * @param {number} [width=1] - The width along the X axis.
  21624. * @param {number} [height=1] - The height along the Y axis
  21625. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  21626. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  21627. */
  21628. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  21629. super();
  21630. this.type = 'PlaneGeometry';
  21631. /**
  21632. * Holds the constructor parameters that have been
  21633. * used to generate the geometry. Any modification
  21634. * after instantiation does not change the geometry.
  21635. *
  21636. * @type {Object}
  21637. */
  21638. this.parameters = {
  21639. width: width,
  21640. height: height,
  21641. widthSegments: widthSegments,
  21642. heightSegments: heightSegments
  21643. };
  21644. const width_half = width / 2;
  21645. const height_half = height / 2;
  21646. const gridX = Math.floor( widthSegments );
  21647. const gridY = Math.floor( heightSegments );
  21648. const gridX1 = gridX + 1;
  21649. const gridY1 = gridY + 1;
  21650. const segment_width = width / gridX;
  21651. const segment_height = height / gridY;
  21652. //
  21653. const indices = [];
  21654. const vertices = [];
  21655. const normals = [];
  21656. const uvs = [];
  21657. for ( let iy = 0; iy < gridY1; iy ++ ) {
  21658. const y = iy * segment_height - height_half;
  21659. for ( let ix = 0; ix < gridX1; ix ++ ) {
  21660. const x = ix * segment_width - width_half;
  21661. vertices.push( x, - y, 0 );
  21662. normals.push( 0, 0, 1 );
  21663. uvs.push( ix / gridX );
  21664. uvs.push( 1 - ( iy / gridY ) );
  21665. }
  21666. }
  21667. for ( let iy = 0; iy < gridY; iy ++ ) {
  21668. for ( let ix = 0; ix < gridX; ix ++ ) {
  21669. const a = ix + gridX1 * iy;
  21670. const b = ix + gridX1 * ( iy + 1 );
  21671. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  21672. const d = ( ix + 1 ) + gridX1 * iy;
  21673. indices.push( a, b, d );
  21674. indices.push( b, c, d );
  21675. }
  21676. }
  21677. this.setIndex( indices );
  21678. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21679. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21680. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21681. }
  21682. copy( source ) {
  21683. super.copy( source );
  21684. this.parameters = Object.assign( {}, source.parameters );
  21685. return this;
  21686. }
  21687. /**
  21688. * Factory method for creating an instance of this class from the given
  21689. * JSON object.
  21690. *
  21691. * @param {Object} data - A JSON object representing the serialized geometry.
  21692. * @return {PlaneGeometry} A new instance.
  21693. */
  21694. static fromJSON( data ) {
  21695. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  21696. }
  21697. }
  21698. /**
  21699. * A class for generating a two-dimensional ring geometry.
  21700. *
  21701. * ```js
  21702. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  21703. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  21704. * const mesh = new THREE.Mesh( geometry, material );
  21705. * scene.add( mesh );
  21706. * ```
  21707. *
  21708. * @augments BufferGeometry
  21709. */
  21710. class RingGeometry extends BufferGeometry {
  21711. /**
  21712. * Constructs a new ring geometry.
  21713. *
  21714. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  21715. * @param {number} [outerRadius=1] - The outer radius of the ring.
  21716. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  21717. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  21718. * @param {number} [thetaStart=0] - Starting angle in radians.
  21719. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  21720. */
  21721. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21722. super();
  21723. this.type = 'RingGeometry';
  21724. /**
  21725. * Holds the constructor parameters that have been
  21726. * used to generate the geometry. Any modification
  21727. * after instantiation does not change the geometry.
  21728. *
  21729. * @type {Object}
  21730. */
  21731. this.parameters = {
  21732. innerRadius: innerRadius,
  21733. outerRadius: outerRadius,
  21734. thetaSegments: thetaSegments,
  21735. phiSegments: phiSegments,
  21736. thetaStart: thetaStart,
  21737. thetaLength: thetaLength
  21738. };
  21739. thetaSegments = Math.max( 3, thetaSegments );
  21740. phiSegments = Math.max( 1, phiSegments );
  21741. // buffers
  21742. const indices = [];
  21743. const vertices = [];
  21744. const normals = [];
  21745. const uvs = [];
  21746. // some helper variables
  21747. let radius = innerRadius;
  21748. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21749. const vertex = new Vector3();
  21750. const uv = new Vector2();
  21751. // generate vertices, normals and uvs
  21752. for ( let j = 0; j <= phiSegments; j ++ ) {
  21753. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21754. // values are generate from the inside of the ring to the outside
  21755. const segment = thetaStart + i / thetaSegments * thetaLength;
  21756. // vertex
  21757. vertex.x = radius * Math.cos( segment );
  21758. vertex.y = radius * Math.sin( segment );
  21759. vertices.push( vertex.x, vertex.y, vertex.z );
  21760. // normal
  21761. normals.push( 0, 0, 1 );
  21762. // uv
  21763. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21764. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21765. uvs.push( uv.x, uv.y );
  21766. }
  21767. // increase the radius for next row of vertices
  21768. radius += radiusStep;
  21769. }
  21770. // indices
  21771. for ( let j = 0; j < phiSegments; j ++ ) {
  21772. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21773. for ( let i = 0; i < thetaSegments; i ++ ) {
  21774. const segment = i + thetaSegmentLevel;
  21775. const a = segment;
  21776. const b = segment + thetaSegments + 1;
  21777. const c = segment + thetaSegments + 2;
  21778. const d = segment + 1;
  21779. // faces
  21780. indices.push( a, b, d );
  21781. indices.push( b, c, d );
  21782. }
  21783. }
  21784. // build geometry
  21785. this.setIndex( indices );
  21786. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21787. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21788. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21789. }
  21790. copy( source ) {
  21791. super.copy( source );
  21792. this.parameters = Object.assign( {}, source.parameters );
  21793. return this;
  21794. }
  21795. /**
  21796. * Factory method for creating an instance of this class from the given
  21797. * JSON object.
  21798. *
  21799. * @param {Object} data - A JSON object representing the serialized geometry.
  21800. * @return {RingGeometry} A new instance.
  21801. */
  21802. static fromJSON( data ) {
  21803. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21804. }
  21805. }
  21806. /**
  21807. * Creates an one-sided polygonal geometry from one or more path shapes.
  21808. *
  21809. * ```js
  21810. * const arcShape = new THREE.Shape()
  21811. * .moveTo( 5, 1 )
  21812. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  21813. *
  21814. * const geometry = new THREE.ShapeGeometry( arcShape );
  21815. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  21816. * const mesh = new THREE.Mesh( geometry, material ) ;
  21817. * scene.add( mesh );
  21818. * ```
  21819. *
  21820. * @augments BufferGeometry
  21821. */
  21822. class ShapeGeometry extends BufferGeometry {
  21823. /**
  21824. * Constructs a new shape geometry.
  21825. *
  21826. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  21827. * @param {number} [curveSegments=12] - Number of segments per shape.
  21828. */
  21829. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  21830. super();
  21831. this.type = 'ShapeGeometry';
  21832. /**
  21833. * Holds the constructor parameters that have been
  21834. * used to generate the geometry. Any modification
  21835. * after instantiation does not change the geometry.
  21836. *
  21837. * @type {Object}
  21838. */
  21839. this.parameters = {
  21840. shapes: shapes,
  21841. curveSegments: curveSegments
  21842. };
  21843. // buffers
  21844. const indices = [];
  21845. const vertices = [];
  21846. const normals = [];
  21847. const uvs = [];
  21848. // helper variables
  21849. let groupStart = 0;
  21850. let groupCount = 0;
  21851. // allow single and array values for "shapes" parameter
  21852. if ( Array.isArray( shapes ) === false ) {
  21853. addShape( shapes );
  21854. } else {
  21855. for ( let i = 0; i < shapes.length; i ++ ) {
  21856. addShape( shapes[ i ] );
  21857. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21858. groupStart += groupCount;
  21859. groupCount = 0;
  21860. }
  21861. }
  21862. // build geometry
  21863. this.setIndex( indices );
  21864. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21865. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21866. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21867. // helper functions
  21868. function addShape( shape ) {
  21869. const indexOffset = vertices.length / 3;
  21870. const points = shape.extractPoints( curveSegments );
  21871. let shapeVertices = points.shape;
  21872. const shapeHoles = points.holes;
  21873. // check direction of vertices
  21874. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21875. shapeVertices = shapeVertices.reverse();
  21876. }
  21877. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21878. const shapeHole = shapeHoles[ i ];
  21879. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21880. shapeHoles[ i ] = shapeHole.reverse();
  21881. }
  21882. }
  21883. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21884. // join vertices of inner and outer paths to a single array
  21885. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21886. const shapeHole = shapeHoles[ i ];
  21887. shapeVertices = shapeVertices.concat( shapeHole );
  21888. }
  21889. // vertices, normals, uvs
  21890. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21891. const vertex = shapeVertices[ i ];
  21892. vertices.push( vertex.x, vertex.y, 0 );
  21893. normals.push( 0, 0, 1 );
  21894. uvs.push( vertex.x, vertex.y ); // world uvs
  21895. }
  21896. // indices
  21897. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21898. const face = faces[ i ];
  21899. const a = face[ 0 ] + indexOffset;
  21900. const b = face[ 1 ] + indexOffset;
  21901. const c = face[ 2 ] + indexOffset;
  21902. indices.push( a, b, c );
  21903. groupCount += 3;
  21904. }
  21905. }
  21906. }
  21907. copy( source ) {
  21908. super.copy( source );
  21909. this.parameters = Object.assign( {}, source.parameters );
  21910. return this;
  21911. }
  21912. toJSON() {
  21913. const data = super.toJSON();
  21914. const shapes = this.parameters.shapes;
  21915. return toJSON( shapes, data );
  21916. }
  21917. /**
  21918. * Factory method for creating an instance of this class from the given
  21919. * JSON object.
  21920. *
  21921. * @param {Object} data - A JSON object representing the serialized geometry.
  21922. * @param {Array<Shape>} shapes - An array of shapes.
  21923. * @return {ShapeGeometry} A new instance.
  21924. */
  21925. static fromJSON( data, shapes ) {
  21926. const geometryShapes = [];
  21927. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21928. const shape = shapes[ data.shapes[ j ] ];
  21929. geometryShapes.push( shape );
  21930. }
  21931. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21932. }
  21933. }
  21934. function toJSON( shapes, data ) {
  21935. data.shapes = [];
  21936. if ( Array.isArray( shapes ) ) {
  21937. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21938. const shape = shapes[ i ];
  21939. data.shapes.push( shape.uuid );
  21940. }
  21941. } else {
  21942. data.shapes.push( shapes.uuid );
  21943. }
  21944. return data;
  21945. }
  21946. /**
  21947. * A class for generating a sphere geometry.
  21948. *
  21949. * ```js
  21950. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  21951. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21952. * const sphere = new THREE.Mesh( geometry, material );
  21953. * scene.add( sphere );
  21954. * ```
  21955. *
  21956. * @augments BufferGeometry
  21957. */
  21958. class SphereGeometry extends BufferGeometry {
  21959. /**
  21960. * Constructs a new sphere geometry.
  21961. *
  21962. * @param {number} [radius=1] - The sphere radius.
  21963. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  21964. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  21965. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  21966. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  21967. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  21968. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  21969. */
  21970. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21971. super();
  21972. this.type = 'SphereGeometry';
  21973. /**
  21974. * Holds the constructor parameters that have been
  21975. * used to generate the geometry. Any modification
  21976. * after instantiation does not change the geometry.
  21977. *
  21978. * @type {Object}
  21979. */
  21980. this.parameters = {
  21981. radius: radius,
  21982. widthSegments: widthSegments,
  21983. heightSegments: heightSegments,
  21984. phiStart: phiStart,
  21985. phiLength: phiLength,
  21986. thetaStart: thetaStart,
  21987. thetaLength: thetaLength
  21988. };
  21989. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21990. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21991. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21992. let index = 0;
  21993. const grid = [];
  21994. const vertex = new Vector3();
  21995. const normal = new Vector3();
  21996. // buffers
  21997. const indices = [];
  21998. const vertices = [];
  21999. const normals = [];
  22000. const uvs = [];
  22001. // generate vertices, normals and uvs
  22002. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  22003. const verticesRow = [];
  22004. const v = iy / heightSegments;
  22005. // special case for the poles
  22006. let uOffset = 0;
  22007. if ( iy === 0 && thetaStart === 0 ) {
  22008. uOffset = 0.5 / widthSegments;
  22009. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  22010. uOffset = -0.5 / widthSegments;
  22011. }
  22012. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  22013. const u = ix / widthSegments;
  22014. // vertex
  22015. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22016. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22017. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22018. vertices.push( vertex.x, vertex.y, vertex.z );
  22019. // normal
  22020. normal.copy( vertex ).normalize();
  22021. normals.push( normal.x, normal.y, normal.z );
  22022. // uv
  22023. uvs.push( u + uOffset, 1 - v );
  22024. verticesRow.push( index ++ );
  22025. }
  22026. grid.push( verticesRow );
  22027. }
  22028. // indices
  22029. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  22030. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  22031. const a = grid[ iy ][ ix + 1 ];
  22032. const b = grid[ iy ][ ix ];
  22033. const c = grid[ iy + 1 ][ ix ];
  22034. const d = grid[ iy + 1 ][ ix + 1 ];
  22035. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22036. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  22037. }
  22038. }
  22039. // build geometry
  22040. this.setIndex( indices );
  22041. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22042. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22043. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22044. }
  22045. copy( source ) {
  22046. super.copy( source );
  22047. this.parameters = Object.assign( {}, source.parameters );
  22048. return this;
  22049. }
  22050. /**
  22051. * Factory method for creating an instance of this class from the given
  22052. * JSON object.
  22053. *
  22054. * @param {Object} data - A JSON object representing the serialized geometry.
  22055. * @return {SphereGeometry} A new instance.
  22056. */
  22057. static fromJSON( data ) {
  22058. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  22059. }
  22060. }
  22061. /**
  22062. * A geometry class for representing an tetrahedron.
  22063. *
  22064. * ```js
  22065. * const geometry = new THREE.TetrahedronGeometry();
  22066. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22067. * const tetrahedron = new THREE.Mesh( geometry, material );
  22068. * scene.add( tetrahedron );
  22069. * ```
  22070. *
  22071. * @augments PolyhedronGeometry
  22072. */
  22073. class TetrahedronGeometry extends PolyhedronGeometry {
  22074. /**
  22075. * Constructs a new tetrahedron geometry.
  22076. *
  22077. * @param {number} [radius=1] - Radius of the tetrahedron.
  22078. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  22079. */
  22080. constructor( radius = 1, detail = 0 ) {
  22081. const vertices = [
  22082. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  22083. ];
  22084. const indices = [
  22085. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22086. ];
  22087. super( vertices, indices, radius, detail );
  22088. this.type = 'TetrahedronGeometry';
  22089. /**
  22090. * Holds the constructor parameters that have been
  22091. * used to generate the geometry. Any modification
  22092. * after instantiation does not change the geometry.
  22093. *
  22094. * @type {Object}
  22095. */
  22096. this.parameters = {
  22097. radius: radius,
  22098. detail: detail
  22099. };
  22100. }
  22101. /**
  22102. * Factory method for creating an instance of this class from the given
  22103. * JSON object.
  22104. *
  22105. * @param {Object} data - A JSON object representing the serialized geometry.
  22106. * @return {TetrahedronGeometry} A new instance.
  22107. */
  22108. static fromJSON( data ) {
  22109. return new TetrahedronGeometry( data.radius, data.detail );
  22110. }
  22111. }
  22112. /**
  22113. * A geometry class for representing an torus.
  22114. *
  22115. * ```js
  22116. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  22117. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22118. * const torus = new THREE.Mesh( geometry, material );
  22119. * scene.add( torus );
  22120. * ```
  22121. *
  22122. * @augments BufferGeometry
  22123. */
  22124. class TorusGeometry extends BufferGeometry {
  22125. /**
  22126. * Constructs a new torus geometry.
  22127. *
  22128. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  22129. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  22130. * @param {number} [radialSegments=12] - The number of radial segments.
  22131. * @param {number} [tubularSegments=48] - The number of tubular segments.
  22132. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  22133. */
  22134. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  22135. super();
  22136. this.type = 'TorusGeometry';
  22137. /**
  22138. * Holds the constructor parameters that have been
  22139. * used to generate the geometry. Any modification
  22140. * after instantiation does not change the geometry.
  22141. *
  22142. * @type {Object}
  22143. */
  22144. this.parameters = {
  22145. radius: radius,
  22146. tube: tube,
  22147. radialSegments: radialSegments,
  22148. tubularSegments: tubularSegments,
  22149. arc: arc
  22150. };
  22151. radialSegments = Math.floor( radialSegments );
  22152. tubularSegments = Math.floor( tubularSegments );
  22153. // buffers
  22154. const indices = [];
  22155. const vertices = [];
  22156. const normals = [];
  22157. const uvs = [];
  22158. // helper variables
  22159. const center = new Vector3();
  22160. const vertex = new Vector3();
  22161. const normal = new Vector3();
  22162. // generate vertices, normals and uvs
  22163. for ( let j = 0; j <= radialSegments; j ++ ) {
  22164. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22165. const u = i / tubularSegments * arc;
  22166. const v = j / radialSegments * Math.PI * 2;
  22167. // vertex
  22168. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22169. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22170. vertex.z = tube * Math.sin( v );
  22171. vertices.push( vertex.x, vertex.y, vertex.z );
  22172. // normal
  22173. center.x = radius * Math.cos( u );
  22174. center.y = radius * Math.sin( u );
  22175. normal.subVectors( vertex, center ).normalize();
  22176. normals.push( normal.x, normal.y, normal.z );
  22177. // uv
  22178. uvs.push( i / tubularSegments );
  22179. uvs.push( j / radialSegments );
  22180. }
  22181. }
  22182. // generate indices
  22183. for ( let j = 1; j <= radialSegments; j ++ ) {
  22184. for ( let i = 1; i <= tubularSegments; i ++ ) {
  22185. // indices
  22186. const a = ( tubularSegments + 1 ) * j + i - 1;
  22187. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22188. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22189. const d = ( tubularSegments + 1 ) * j + i;
  22190. // faces
  22191. indices.push( a, b, d );
  22192. indices.push( b, c, d );
  22193. }
  22194. }
  22195. // build geometry
  22196. this.setIndex( indices );
  22197. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22198. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22199. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22200. }
  22201. copy( source ) {
  22202. super.copy( source );
  22203. this.parameters = Object.assign( {}, source.parameters );
  22204. return this;
  22205. }
  22206. /**
  22207. * Factory method for creating an instance of this class from the given
  22208. * JSON object.
  22209. *
  22210. * @param {Object} data - A JSON object representing the serialized geometry.
  22211. * @return {TorusGeometry} A new instance.
  22212. */
  22213. static fromJSON( data ) {
  22214. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  22215. }
  22216. }
  22217. /**
  22218. * Creates a torus knot, the particular shape of which is defined by a pair
  22219. * of coprime integers, p and q. If p and q are not coprime, the result will
  22220. * be a torus link.
  22221. *
  22222. * ```js
  22223. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  22224. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22225. * const torusKnot = new THREE.Mesh( geometry, material );
  22226. * scene.add( torusKnot );
  22227. * ```
  22228. *
  22229. * @augments BufferGeometry
  22230. */
  22231. class TorusKnotGeometry extends BufferGeometry {
  22232. /**
  22233. * Constructs a new torus knot geometry.
  22234. *
  22235. * @param {number} [radius=1] - Radius of the torus knot.
  22236. * @param {number} [tube=0.4] - Radius of the tube.
  22237. * @param {number} [tubularSegments=64] - The number of tubular segments.
  22238. * @param {number} [radialSegments=8] - The number of radial segments.
  22239. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  22240. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  22241. */
  22242. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  22243. super();
  22244. this.type = 'TorusKnotGeometry';
  22245. /**
  22246. * Holds the constructor parameters that have been
  22247. * used to generate the geometry. Any modification
  22248. * after instantiation does not change the geometry.
  22249. *
  22250. * @type {Object}
  22251. */
  22252. this.parameters = {
  22253. radius: radius,
  22254. tube: tube,
  22255. tubularSegments: tubularSegments,
  22256. radialSegments: radialSegments,
  22257. p: p,
  22258. q: q
  22259. };
  22260. tubularSegments = Math.floor( tubularSegments );
  22261. radialSegments = Math.floor( radialSegments );
  22262. // buffers
  22263. const indices = [];
  22264. const vertices = [];
  22265. const normals = [];
  22266. const uvs = [];
  22267. // helper variables
  22268. const vertex = new Vector3();
  22269. const normal = new Vector3();
  22270. const P1 = new Vector3();
  22271. const P2 = new Vector3();
  22272. const B = new Vector3();
  22273. const T = new Vector3();
  22274. const N = new Vector3();
  22275. // generate vertices, normals and uvs
  22276. for ( let i = 0; i <= tubularSegments; ++ i ) {
  22277. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  22278. const u = i / tubularSegments * p * Math.PI * 2;
  22279. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22280. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22281. calculatePositionOnCurve( u, p, q, radius, P1 );
  22282. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  22283. // calculate orthonormal basis
  22284. T.subVectors( P2, P1 );
  22285. N.addVectors( P2, P1 );
  22286. B.crossVectors( T, N );
  22287. N.crossVectors( B, T );
  22288. // normalize B, N. T can be ignored, we don't use it
  22289. B.normalize();
  22290. N.normalize();
  22291. for ( let j = 0; j <= radialSegments; ++ j ) {
  22292. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22293. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22294. const v = j / radialSegments * Math.PI * 2;
  22295. const cx = - tube * Math.cos( v );
  22296. const cy = tube * Math.sin( v );
  22297. // now calculate the final vertex position.
  22298. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  22299. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  22300. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  22301. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  22302. vertices.push( vertex.x, vertex.y, vertex.z );
  22303. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22304. normal.subVectors( vertex, P1 ).normalize();
  22305. normals.push( normal.x, normal.y, normal.z );
  22306. // uv
  22307. uvs.push( i / tubularSegments );
  22308. uvs.push( j / radialSegments );
  22309. }
  22310. }
  22311. // generate indices
  22312. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22313. for ( let i = 1; i <= radialSegments; i ++ ) {
  22314. // indices
  22315. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22316. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22317. const c = ( radialSegments + 1 ) * j + i;
  22318. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22319. // faces
  22320. indices.push( a, b, d );
  22321. indices.push( b, c, d );
  22322. }
  22323. }
  22324. // build geometry
  22325. this.setIndex( indices );
  22326. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22327. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22328. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22329. // this function calculates the current position on the torus curve
  22330. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22331. const cu = Math.cos( u );
  22332. const su = Math.sin( u );
  22333. const quOverP = q / p * u;
  22334. const cs = Math.cos( quOverP );
  22335. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22336. position.y = radius * ( 2 + cs ) * su * 0.5;
  22337. position.z = radius * Math.sin( quOverP ) * 0.5;
  22338. }
  22339. }
  22340. copy( source ) {
  22341. super.copy( source );
  22342. this.parameters = Object.assign( {}, source.parameters );
  22343. return this;
  22344. }
  22345. /**
  22346. * Factory method for creating an instance of this class from the given
  22347. * JSON object.
  22348. *
  22349. * @param {Object} data - A JSON object representing the serialized geometry.
  22350. * @return {TorusKnotGeometry} A new instance.
  22351. */
  22352. static fromJSON( data ) {
  22353. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  22354. }
  22355. }
  22356. /**
  22357. * Creates a tube that extrudes along a 3D curve.
  22358. *
  22359. * ```js
  22360. * class CustomSinCurve extends THREE.Curve {
  22361. *
  22362. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  22363. *
  22364. * const tx = t * 3 - 1.5;
  22365. * const ty = Math.sin( 2 * Math.PI * t );
  22366. * const tz = 0;
  22367. *
  22368. * return optionalTarget.set( tx, ty, tz );
  22369. * }
  22370. *
  22371. * }
  22372. *
  22373. * const path = new CustomSinCurve( 10 );
  22374. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  22375. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22376. * const mesh = new THREE.Mesh( geometry, material );
  22377. * scene.add( mesh );
  22378. * ```
  22379. *
  22380. * @augments BufferGeometry
  22381. */
  22382. class TubeGeometry extends BufferGeometry {
  22383. /**
  22384. * Constructs a new tube geometry.
  22385. *
  22386. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  22387. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  22388. * @param {number} [radius=1] -The radius of the tube.
  22389. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  22390. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  22391. */
  22392. 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 ) {
  22393. super();
  22394. this.type = 'TubeGeometry';
  22395. /**
  22396. * Holds the constructor parameters that have been
  22397. * used to generate the geometry. Any modification
  22398. * after instantiation does not change the geometry.
  22399. *
  22400. * @type {Object}
  22401. */
  22402. this.parameters = {
  22403. path: path,
  22404. tubularSegments: tubularSegments,
  22405. radius: radius,
  22406. radialSegments: radialSegments,
  22407. closed: closed
  22408. };
  22409. const frames = path.computeFrenetFrames( tubularSegments, closed );
  22410. // expose internals
  22411. this.tangents = frames.tangents;
  22412. this.normals = frames.normals;
  22413. this.binormals = frames.binormals;
  22414. // helper variables
  22415. const vertex = new Vector3();
  22416. const normal = new Vector3();
  22417. const uv = new Vector2();
  22418. let P = new Vector3();
  22419. // buffer
  22420. const vertices = [];
  22421. const normals = [];
  22422. const uvs = [];
  22423. const indices = [];
  22424. // create buffer data
  22425. generateBufferData();
  22426. // build geometry
  22427. this.setIndex( indices );
  22428. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22429. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22430. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22431. // functions
  22432. function generateBufferData() {
  22433. for ( let i = 0; i < tubularSegments; i ++ ) {
  22434. generateSegment( i );
  22435. }
  22436. // if the geometry is not closed, generate the last row of vertices and normals
  22437. // at the regular position on the given path
  22438. //
  22439. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22440. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22441. // uvs are generated in a separate function.
  22442. // this makes it easy compute correct values for closed geometries
  22443. generateUVs();
  22444. // finally create faces
  22445. generateIndices();
  22446. }
  22447. function generateSegment( i ) {
  22448. // we use getPointAt to sample evenly distributed points from the given path
  22449. P = path.getPointAt( i / tubularSegments, P );
  22450. // retrieve corresponding normal and binormal
  22451. const N = frames.normals[ i ];
  22452. const B = frames.binormals[ i ];
  22453. // generate normals and vertices for the current segment
  22454. for ( let j = 0; j <= radialSegments; j ++ ) {
  22455. const v = j / radialSegments * Math.PI * 2;
  22456. const sin = Math.sin( v );
  22457. const cos = - Math.cos( v );
  22458. // normal
  22459. normal.x = ( cos * N.x + sin * B.x );
  22460. normal.y = ( cos * N.y + sin * B.y );
  22461. normal.z = ( cos * N.z + sin * B.z );
  22462. normal.normalize();
  22463. normals.push( normal.x, normal.y, normal.z );
  22464. // vertex
  22465. vertex.x = P.x + radius * normal.x;
  22466. vertex.y = P.y + radius * normal.y;
  22467. vertex.z = P.z + radius * normal.z;
  22468. vertices.push( vertex.x, vertex.y, vertex.z );
  22469. }
  22470. }
  22471. function generateIndices() {
  22472. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22473. for ( let i = 1; i <= radialSegments; i ++ ) {
  22474. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22475. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22476. const c = ( radialSegments + 1 ) * j + i;
  22477. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22478. // faces
  22479. indices.push( a, b, d );
  22480. indices.push( b, c, d );
  22481. }
  22482. }
  22483. }
  22484. function generateUVs() {
  22485. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22486. for ( let j = 0; j <= radialSegments; j ++ ) {
  22487. uv.x = i / tubularSegments;
  22488. uv.y = j / radialSegments;
  22489. uvs.push( uv.x, uv.y );
  22490. }
  22491. }
  22492. }
  22493. }
  22494. copy( source ) {
  22495. super.copy( source );
  22496. this.parameters = Object.assign( {}, source.parameters );
  22497. return this;
  22498. }
  22499. toJSON() {
  22500. const data = super.toJSON();
  22501. data.path = this.parameters.path.toJSON();
  22502. return data;
  22503. }
  22504. /**
  22505. * Factory method for creating an instance of this class from the given
  22506. * JSON object.
  22507. *
  22508. * @param {Object} data - A JSON object representing the serialized geometry.
  22509. * @return {TubeGeometry} A new instance.
  22510. */
  22511. static fromJSON( data ) {
  22512. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22513. // User defined curves or instances of CurvePath will not be deserialized.
  22514. return new TubeGeometry(
  22515. new Curves[ data.path.type ]().fromJSON( data.path ),
  22516. data.tubularSegments,
  22517. data.radius,
  22518. data.radialSegments,
  22519. data.closed
  22520. );
  22521. }
  22522. }
  22523. /**
  22524. * Can be used as a helper object to visualize a geometry as a wireframe.
  22525. *
  22526. * ```js
  22527. * const geometry = new THREE.SphereGeometry();
  22528. *
  22529. * const wireframe = new THREE.WireframeGeometry( geometry );
  22530. *
  22531. * const line = new THREE.LineSegments( wireframe );
  22532. * line.material.depthWrite = false;
  22533. * line.material.opacity = 0.25;
  22534. * line.material.transparent = true;
  22535. *
  22536. * scene.add( line );
  22537. * ```
  22538. *
  22539. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22540. *
  22541. * @augments BufferGeometry
  22542. */
  22543. class WireframeGeometry extends BufferGeometry {
  22544. /**
  22545. * Constructs a new wireframe geometry.
  22546. *
  22547. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22548. */
  22549. constructor( geometry = null ) {
  22550. super();
  22551. this.type = 'WireframeGeometry';
  22552. /**
  22553. * Holds the constructor parameters that have been
  22554. * used to generate the geometry. Any modification
  22555. * after instantiation does not change the geometry.
  22556. *
  22557. * @type {Object}
  22558. */
  22559. this.parameters = {
  22560. geometry: geometry
  22561. };
  22562. if ( geometry !== null ) {
  22563. // buffer
  22564. const vertices = [];
  22565. const edges = new Set();
  22566. // helper variables
  22567. const start = new Vector3();
  22568. const end = new Vector3();
  22569. if ( geometry.index !== null ) {
  22570. // indexed BufferGeometry
  22571. const position = geometry.attributes.position;
  22572. const indices = geometry.index;
  22573. let groups = geometry.groups;
  22574. if ( groups.length === 0 ) {
  22575. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22576. }
  22577. // create a data structure that contains all edges without duplicates
  22578. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22579. const group = groups[ o ];
  22580. const groupStart = group.start;
  22581. const groupCount = group.count;
  22582. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22583. for ( let j = 0; j < 3; j ++ ) {
  22584. const index1 = indices.getX( i + j );
  22585. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22586. start.fromBufferAttribute( position, index1 );
  22587. end.fromBufferAttribute( position, index2 );
  22588. if ( isUniqueEdge( start, end, edges ) === true ) {
  22589. vertices.push( start.x, start.y, start.z );
  22590. vertices.push( end.x, end.y, end.z );
  22591. }
  22592. }
  22593. }
  22594. }
  22595. } else {
  22596. // non-indexed BufferGeometry
  22597. const position = geometry.attributes.position;
  22598. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22599. for ( let j = 0; j < 3; j ++ ) {
  22600. // three edges per triangle, an edge is represented as (index1, index2)
  22601. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22602. const index1 = 3 * i + j;
  22603. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22604. start.fromBufferAttribute( position, index1 );
  22605. end.fromBufferAttribute( position, index2 );
  22606. if ( isUniqueEdge( start, end, edges ) === true ) {
  22607. vertices.push( start.x, start.y, start.z );
  22608. vertices.push( end.x, end.y, end.z );
  22609. }
  22610. }
  22611. }
  22612. }
  22613. // build geometry
  22614. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22615. }
  22616. }
  22617. copy( source ) {
  22618. super.copy( source );
  22619. this.parameters = Object.assign( {}, source.parameters );
  22620. return this;
  22621. }
  22622. }
  22623. function isUniqueEdge( start, end, edges ) {
  22624. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22625. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22626. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22627. return false;
  22628. } else {
  22629. edges.add( hash1 );
  22630. edges.add( hash2 );
  22631. return true;
  22632. }
  22633. }
  22634. var Geometries = /*#__PURE__*/Object.freeze({
  22635. __proto__: null,
  22636. BoxGeometry: BoxGeometry,
  22637. CapsuleGeometry: CapsuleGeometry,
  22638. CircleGeometry: CircleGeometry,
  22639. ConeGeometry: ConeGeometry,
  22640. CylinderGeometry: CylinderGeometry,
  22641. DodecahedronGeometry: DodecahedronGeometry,
  22642. EdgesGeometry: EdgesGeometry,
  22643. ExtrudeGeometry: ExtrudeGeometry,
  22644. IcosahedronGeometry: IcosahedronGeometry,
  22645. LatheGeometry: LatheGeometry,
  22646. OctahedronGeometry: OctahedronGeometry,
  22647. PlaneGeometry: PlaneGeometry,
  22648. PolyhedronGeometry: PolyhedronGeometry,
  22649. RingGeometry: RingGeometry,
  22650. ShapeGeometry: ShapeGeometry,
  22651. SphereGeometry: SphereGeometry,
  22652. TetrahedronGeometry: TetrahedronGeometry,
  22653. TorusGeometry: TorusGeometry,
  22654. TorusKnotGeometry: TorusKnotGeometry,
  22655. TubeGeometry: TubeGeometry,
  22656. WireframeGeometry: WireframeGeometry
  22657. });
  22658. class ShadowMaterial extends Material {
  22659. constructor( parameters ) {
  22660. super();
  22661. this.isShadowMaterial = true;
  22662. this.type = 'ShadowMaterial';
  22663. this.color = new Color( 0x000000 );
  22664. this.transparent = true;
  22665. this.fog = true;
  22666. this.setValues( parameters );
  22667. }
  22668. copy( source ) {
  22669. super.copy( source );
  22670. this.color.copy( source.color );
  22671. this.fog = source.fog;
  22672. return this;
  22673. }
  22674. }
  22675. class RawShaderMaterial extends ShaderMaterial {
  22676. constructor( parameters ) {
  22677. super( parameters );
  22678. this.isRawShaderMaterial = true;
  22679. this.type = 'RawShaderMaterial';
  22680. }
  22681. }
  22682. class MeshStandardMaterial extends Material {
  22683. constructor( parameters ) {
  22684. super();
  22685. this.isMeshStandardMaterial = true;
  22686. this.type = 'MeshStandardMaterial';
  22687. this.defines = { 'STANDARD': '' };
  22688. this.color = new Color( 0xffffff ); // diffuse
  22689. this.roughness = 1.0;
  22690. this.metalness = 0.0;
  22691. this.map = null;
  22692. this.lightMap = null;
  22693. this.lightMapIntensity = 1.0;
  22694. this.aoMap = null;
  22695. this.aoMapIntensity = 1.0;
  22696. this.emissive = new Color( 0x000000 );
  22697. this.emissiveIntensity = 1.0;
  22698. this.emissiveMap = null;
  22699. this.bumpMap = null;
  22700. this.bumpScale = 1;
  22701. this.normalMap = null;
  22702. this.normalMapType = TangentSpaceNormalMap;
  22703. this.normalScale = new Vector2( 1, 1 );
  22704. this.displacementMap = null;
  22705. this.displacementScale = 1;
  22706. this.displacementBias = 0;
  22707. this.roughnessMap = null;
  22708. this.metalnessMap = null;
  22709. this.alphaMap = null;
  22710. this.envMap = null;
  22711. this.envMapRotation = new Euler();
  22712. this.envMapIntensity = 1.0;
  22713. this.wireframe = false;
  22714. this.wireframeLinewidth = 1;
  22715. this.wireframeLinecap = 'round';
  22716. this.wireframeLinejoin = 'round';
  22717. this.flatShading = false;
  22718. this.fog = true;
  22719. this.setValues( parameters );
  22720. }
  22721. copy( source ) {
  22722. super.copy( source );
  22723. this.defines = { 'STANDARD': '' };
  22724. this.color.copy( source.color );
  22725. this.roughness = source.roughness;
  22726. this.metalness = source.metalness;
  22727. this.map = source.map;
  22728. this.lightMap = source.lightMap;
  22729. this.lightMapIntensity = source.lightMapIntensity;
  22730. this.aoMap = source.aoMap;
  22731. this.aoMapIntensity = source.aoMapIntensity;
  22732. this.emissive.copy( source.emissive );
  22733. this.emissiveMap = source.emissiveMap;
  22734. this.emissiveIntensity = source.emissiveIntensity;
  22735. this.bumpMap = source.bumpMap;
  22736. this.bumpScale = source.bumpScale;
  22737. this.normalMap = source.normalMap;
  22738. this.normalMapType = source.normalMapType;
  22739. this.normalScale.copy( source.normalScale );
  22740. this.displacementMap = source.displacementMap;
  22741. this.displacementScale = source.displacementScale;
  22742. this.displacementBias = source.displacementBias;
  22743. this.roughnessMap = source.roughnessMap;
  22744. this.metalnessMap = source.metalnessMap;
  22745. this.alphaMap = source.alphaMap;
  22746. this.envMap = source.envMap;
  22747. this.envMapRotation.copy( source.envMapRotation );
  22748. this.envMapIntensity = source.envMapIntensity;
  22749. this.wireframe = source.wireframe;
  22750. this.wireframeLinewidth = source.wireframeLinewidth;
  22751. this.wireframeLinecap = source.wireframeLinecap;
  22752. this.wireframeLinejoin = source.wireframeLinejoin;
  22753. this.flatShading = source.flatShading;
  22754. this.fog = source.fog;
  22755. return this;
  22756. }
  22757. }
  22758. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22759. constructor( parameters ) {
  22760. super();
  22761. this.isMeshPhysicalMaterial = true;
  22762. this.defines = {
  22763. 'STANDARD': '',
  22764. 'PHYSICAL': ''
  22765. };
  22766. this.type = 'MeshPhysicalMaterial';
  22767. this.anisotropyRotation = 0;
  22768. this.anisotropyMap = null;
  22769. this.clearcoatMap = null;
  22770. this.clearcoatRoughness = 0.0;
  22771. this.clearcoatRoughnessMap = null;
  22772. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22773. this.clearcoatNormalMap = null;
  22774. this.ior = 1.5;
  22775. Object.defineProperty( this, 'reflectivity', {
  22776. get: function () {
  22777. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22778. },
  22779. set: function ( reflectivity ) {
  22780. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22781. }
  22782. } );
  22783. this.iridescenceMap = null;
  22784. this.iridescenceIOR = 1.3;
  22785. this.iridescenceThicknessRange = [ 100, 400 ];
  22786. this.iridescenceThicknessMap = null;
  22787. this.sheenColor = new Color( 0x000000 );
  22788. this.sheenColorMap = null;
  22789. this.sheenRoughness = 1.0;
  22790. this.sheenRoughnessMap = null;
  22791. this.transmissionMap = null;
  22792. this.thickness = 0;
  22793. this.thicknessMap = null;
  22794. this.attenuationDistance = Infinity;
  22795. this.attenuationColor = new Color( 1, 1, 1 );
  22796. this.specularIntensity = 1.0;
  22797. this.specularIntensityMap = null;
  22798. this.specularColor = new Color( 1, 1, 1 );
  22799. this.specularColorMap = null;
  22800. this._anisotropy = 0;
  22801. this._clearcoat = 0;
  22802. this._dispersion = 0;
  22803. this._iridescence = 0;
  22804. this._sheen = 0.0;
  22805. this._transmission = 0;
  22806. this.setValues( parameters );
  22807. }
  22808. get anisotropy() {
  22809. return this._anisotropy;
  22810. }
  22811. set anisotropy( value ) {
  22812. if ( this._anisotropy > 0 !== value > 0 ) {
  22813. this.version ++;
  22814. }
  22815. this._anisotropy = value;
  22816. }
  22817. get clearcoat() {
  22818. return this._clearcoat;
  22819. }
  22820. set clearcoat( value ) {
  22821. if ( this._clearcoat > 0 !== value > 0 ) {
  22822. this.version ++;
  22823. }
  22824. this._clearcoat = value;
  22825. }
  22826. get iridescence() {
  22827. return this._iridescence;
  22828. }
  22829. set iridescence( value ) {
  22830. if ( this._iridescence > 0 !== value > 0 ) {
  22831. this.version ++;
  22832. }
  22833. this._iridescence = value;
  22834. }
  22835. get dispersion() {
  22836. return this._dispersion;
  22837. }
  22838. set dispersion( value ) {
  22839. if ( this._dispersion > 0 !== value > 0 ) {
  22840. this.version ++;
  22841. }
  22842. this._dispersion = value;
  22843. }
  22844. get sheen() {
  22845. return this._sheen;
  22846. }
  22847. set sheen( value ) {
  22848. if ( this._sheen > 0 !== value > 0 ) {
  22849. this.version ++;
  22850. }
  22851. this._sheen = value;
  22852. }
  22853. get transmission() {
  22854. return this._transmission;
  22855. }
  22856. set transmission( value ) {
  22857. if ( this._transmission > 0 !== value > 0 ) {
  22858. this.version ++;
  22859. }
  22860. this._transmission = value;
  22861. }
  22862. copy( source ) {
  22863. super.copy( source );
  22864. this.defines = {
  22865. 'STANDARD': '',
  22866. 'PHYSICAL': ''
  22867. };
  22868. this.anisotropy = source.anisotropy;
  22869. this.anisotropyRotation = source.anisotropyRotation;
  22870. this.anisotropyMap = source.anisotropyMap;
  22871. this.clearcoat = source.clearcoat;
  22872. this.clearcoatMap = source.clearcoatMap;
  22873. this.clearcoatRoughness = source.clearcoatRoughness;
  22874. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22875. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22876. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22877. this.dispersion = source.dispersion;
  22878. this.ior = source.ior;
  22879. this.iridescence = source.iridescence;
  22880. this.iridescenceMap = source.iridescenceMap;
  22881. this.iridescenceIOR = source.iridescenceIOR;
  22882. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22883. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22884. this.sheen = source.sheen;
  22885. this.sheenColor.copy( source.sheenColor );
  22886. this.sheenColorMap = source.sheenColorMap;
  22887. this.sheenRoughness = source.sheenRoughness;
  22888. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22889. this.transmission = source.transmission;
  22890. this.transmissionMap = source.transmissionMap;
  22891. this.thickness = source.thickness;
  22892. this.thicknessMap = source.thicknessMap;
  22893. this.attenuationDistance = source.attenuationDistance;
  22894. this.attenuationColor.copy( source.attenuationColor );
  22895. this.specularIntensity = source.specularIntensity;
  22896. this.specularIntensityMap = source.specularIntensityMap;
  22897. this.specularColor.copy( source.specularColor );
  22898. this.specularColorMap = source.specularColorMap;
  22899. return this;
  22900. }
  22901. }
  22902. class MeshPhongMaterial extends Material {
  22903. constructor( parameters ) {
  22904. super();
  22905. this.isMeshPhongMaterial = true;
  22906. this.type = 'MeshPhongMaterial';
  22907. this.color = new Color( 0xffffff ); // diffuse
  22908. this.specular = new Color( 0x111111 );
  22909. this.shininess = 30;
  22910. this.map = null;
  22911. this.lightMap = null;
  22912. this.lightMapIntensity = 1.0;
  22913. this.aoMap = null;
  22914. this.aoMapIntensity = 1.0;
  22915. this.emissive = new Color( 0x000000 );
  22916. this.emissiveIntensity = 1.0;
  22917. this.emissiveMap = null;
  22918. this.bumpMap = null;
  22919. this.bumpScale = 1;
  22920. this.normalMap = null;
  22921. this.normalMapType = TangentSpaceNormalMap;
  22922. this.normalScale = new Vector2( 1, 1 );
  22923. this.displacementMap = null;
  22924. this.displacementScale = 1;
  22925. this.displacementBias = 0;
  22926. this.specularMap = null;
  22927. this.alphaMap = null;
  22928. this.envMap = null;
  22929. this.envMapRotation = new Euler();
  22930. this.combine = MultiplyOperation;
  22931. this.reflectivity = 1;
  22932. this.refractionRatio = 0.98;
  22933. this.wireframe = false;
  22934. this.wireframeLinewidth = 1;
  22935. this.wireframeLinecap = 'round';
  22936. this.wireframeLinejoin = 'round';
  22937. this.flatShading = false;
  22938. this.fog = true;
  22939. this.setValues( parameters );
  22940. }
  22941. copy( source ) {
  22942. super.copy( source );
  22943. this.color.copy( source.color );
  22944. this.specular.copy( source.specular );
  22945. this.shininess = source.shininess;
  22946. this.map = source.map;
  22947. this.lightMap = source.lightMap;
  22948. this.lightMapIntensity = source.lightMapIntensity;
  22949. this.aoMap = source.aoMap;
  22950. this.aoMapIntensity = source.aoMapIntensity;
  22951. this.emissive.copy( source.emissive );
  22952. this.emissiveMap = source.emissiveMap;
  22953. this.emissiveIntensity = source.emissiveIntensity;
  22954. this.bumpMap = source.bumpMap;
  22955. this.bumpScale = source.bumpScale;
  22956. this.normalMap = source.normalMap;
  22957. this.normalMapType = source.normalMapType;
  22958. this.normalScale.copy( source.normalScale );
  22959. this.displacementMap = source.displacementMap;
  22960. this.displacementScale = source.displacementScale;
  22961. this.displacementBias = source.displacementBias;
  22962. this.specularMap = source.specularMap;
  22963. this.alphaMap = source.alphaMap;
  22964. this.envMap = source.envMap;
  22965. this.envMapRotation.copy( source.envMapRotation );
  22966. this.combine = source.combine;
  22967. this.reflectivity = source.reflectivity;
  22968. this.refractionRatio = source.refractionRatio;
  22969. this.wireframe = source.wireframe;
  22970. this.wireframeLinewidth = source.wireframeLinewidth;
  22971. this.wireframeLinecap = source.wireframeLinecap;
  22972. this.wireframeLinejoin = source.wireframeLinejoin;
  22973. this.flatShading = source.flatShading;
  22974. this.fog = source.fog;
  22975. return this;
  22976. }
  22977. }
  22978. class MeshToonMaterial extends Material {
  22979. constructor( parameters ) {
  22980. super();
  22981. this.isMeshToonMaterial = true;
  22982. this.defines = { 'TOON': '' };
  22983. this.type = 'MeshToonMaterial';
  22984. this.color = new Color( 0xffffff );
  22985. this.map = null;
  22986. this.gradientMap = null;
  22987. this.lightMap = null;
  22988. this.lightMapIntensity = 1.0;
  22989. this.aoMap = null;
  22990. this.aoMapIntensity = 1.0;
  22991. this.emissive = new Color( 0x000000 );
  22992. this.emissiveIntensity = 1.0;
  22993. this.emissiveMap = null;
  22994. this.bumpMap = null;
  22995. this.bumpScale = 1;
  22996. this.normalMap = null;
  22997. this.normalMapType = TangentSpaceNormalMap;
  22998. this.normalScale = new Vector2( 1, 1 );
  22999. this.displacementMap = null;
  23000. this.displacementScale = 1;
  23001. this.displacementBias = 0;
  23002. this.alphaMap = null;
  23003. this.wireframe = false;
  23004. this.wireframeLinewidth = 1;
  23005. this.wireframeLinecap = 'round';
  23006. this.wireframeLinejoin = 'round';
  23007. this.fog = true;
  23008. this.setValues( parameters );
  23009. }
  23010. copy( source ) {
  23011. super.copy( source );
  23012. this.color.copy( source.color );
  23013. this.map = source.map;
  23014. this.gradientMap = source.gradientMap;
  23015. this.lightMap = source.lightMap;
  23016. this.lightMapIntensity = source.lightMapIntensity;
  23017. this.aoMap = source.aoMap;
  23018. this.aoMapIntensity = source.aoMapIntensity;
  23019. this.emissive.copy( source.emissive );
  23020. this.emissiveMap = source.emissiveMap;
  23021. this.emissiveIntensity = source.emissiveIntensity;
  23022. this.bumpMap = source.bumpMap;
  23023. this.bumpScale = source.bumpScale;
  23024. this.normalMap = source.normalMap;
  23025. this.normalMapType = source.normalMapType;
  23026. this.normalScale.copy( source.normalScale );
  23027. this.displacementMap = source.displacementMap;
  23028. this.displacementScale = source.displacementScale;
  23029. this.displacementBias = source.displacementBias;
  23030. this.alphaMap = source.alphaMap;
  23031. this.wireframe = source.wireframe;
  23032. this.wireframeLinewidth = source.wireframeLinewidth;
  23033. this.wireframeLinecap = source.wireframeLinecap;
  23034. this.wireframeLinejoin = source.wireframeLinejoin;
  23035. this.fog = source.fog;
  23036. return this;
  23037. }
  23038. }
  23039. class MeshNormalMaterial extends Material {
  23040. constructor( parameters ) {
  23041. super();
  23042. this.isMeshNormalMaterial = true;
  23043. this.type = 'MeshNormalMaterial';
  23044. this.bumpMap = null;
  23045. this.bumpScale = 1;
  23046. this.normalMap = null;
  23047. this.normalMapType = TangentSpaceNormalMap;
  23048. this.normalScale = new Vector2( 1, 1 );
  23049. this.displacementMap = null;
  23050. this.displacementScale = 1;
  23051. this.displacementBias = 0;
  23052. this.wireframe = false;
  23053. this.wireframeLinewidth = 1;
  23054. this.flatShading = false;
  23055. this.setValues( parameters );
  23056. }
  23057. copy( source ) {
  23058. super.copy( source );
  23059. this.bumpMap = source.bumpMap;
  23060. this.bumpScale = source.bumpScale;
  23061. this.normalMap = source.normalMap;
  23062. this.normalMapType = source.normalMapType;
  23063. this.normalScale.copy( source.normalScale );
  23064. this.displacementMap = source.displacementMap;
  23065. this.displacementScale = source.displacementScale;
  23066. this.displacementBias = source.displacementBias;
  23067. this.wireframe = source.wireframe;
  23068. this.wireframeLinewidth = source.wireframeLinewidth;
  23069. this.flatShading = source.flatShading;
  23070. return this;
  23071. }
  23072. }
  23073. class MeshLambertMaterial extends Material {
  23074. constructor( parameters ) {
  23075. super();
  23076. this.isMeshLambertMaterial = true;
  23077. this.type = 'MeshLambertMaterial';
  23078. this.color = new Color( 0xffffff ); // diffuse
  23079. this.map = null;
  23080. this.lightMap = null;
  23081. this.lightMapIntensity = 1.0;
  23082. this.aoMap = null;
  23083. this.aoMapIntensity = 1.0;
  23084. this.emissive = new Color( 0x000000 );
  23085. this.emissiveIntensity = 1.0;
  23086. this.emissiveMap = null;
  23087. this.bumpMap = null;
  23088. this.bumpScale = 1;
  23089. this.normalMap = null;
  23090. this.normalMapType = TangentSpaceNormalMap;
  23091. this.normalScale = new Vector2( 1, 1 );
  23092. this.displacementMap = null;
  23093. this.displacementScale = 1;
  23094. this.displacementBias = 0;
  23095. this.specularMap = null;
  23096. this.alphaMap = null;
  23097. this.envMap = null;
  23098. this.envMapRotation = new Euler();
  23099. this.combine = MultiplyOperation;
  23100. this.reflectivity = 1;
  23101. this.refractionRatio = 0.98;
  23102. this.wireframe = false;
  23103. this.wireframeLinewidth = 1;
  23104. this.wireframeLinecap = 'round';
  23105. this.wireframeLinejoin = 'round';
  23106. this.flatShading = false;
  23107. this.fog = true;
  23108. this.setValues( parameters );
  23109. }
  23110. copy( source ) {
  23111. super.copy( source );
  23112. this.color.copy( source.color );
  23113. this.map = source.map;
  23114. this.lightMap = source.lightMap;
  23115. this.lightMapIntensity = source.lightMapIntensity;
  23116. this.aoMap = source.aoMap;
  23117. this.aoMapIntensity = source.aoMapIntensity;
  23118. this.emissive.copy( source.emissive );
  23119. this.emissiveMap = source.emissiveMap;
  23120. this.emissiveIntensity = source.emissiveIntensity;
  23121. this.bumpMap = source.bumpMap;
  23122. this.bumpScale = source.bumpScale;
  23123. this.normalMap = source.normalMap;
  23124. this.normalMapType = source.normalMapType;
  23125. this.normalScale.copy( source.normalScale );
  23126. this.displacementMap = source.displacementMap;
  23127. this.displacementScale = source.displacementScale;
  23128. this.displacementBias = source.displacementBias;
  23129. this.specularMap = source.specularMap;
  23130. this.alphaMap = source.alphaMap;
  23131. this.envMap = source.envMap;
  23132. this.envMapRotation.copy( source.envMapRotation );
  23133. this.combine = source.combine;
  23134. this.reflectivity = source.reflectivity;
  23135. this.refractionRatio = source.refractionRatio;
  23136. this.wireframe = source.wireframe;
  23137. this.wireframeLinewidth = source.wireframeLinewidth;
  23138. this.wireframeLinecap = source.wireframeLinecap;
  23139. this.wireframeLinejoin = source.wireframeLinejoin;
  23140. this.flatShading = source.flatShading;
  23141. this.fog = source.fog;
  23142. return this;
  23143. }
  23144. }
  23145. class MeshDepthMaterial extends Material {
  23146. constructor( parameters ) {
  23147. super();
  23148. this.isMeshDepthMaterial = true;
  23149. this.type = 'MeshDepthMaterial';
  23150. this.depthPacking = BasicDepthPacking;
  23151. this.map = null;
  23152. this.alphaMap = null;
  23153. this.displacementMap = null;
  23154. this.displacementScale = 1;
  23155. this.displacementBias = 0;
  23156. this.wireframe = false;
  23157. this.wireframeLinewidth = 1;
  23158. this.setValues( parameters );
  23159. }
  23160. copy( source ) {
  23161. super.copy( source );
  23162. this.depthPacking = source.depthPacking;
  23163. this.map = source.map;
  23164. this.alphaMap = source.alphaMap;
  23165. this.displacementMap = source.displacementMap;
  23166. this.displacementScale = source.displacementScale;
  23167. this.displacementBias = source.displacementBias;
  23168. this.wireframe = source.wireframe;
  23169. this.wireframeLinewidth = source.wireframeLinewidth;
  23170. return this;
  23171. }
  23172. }
  23173. class MeshDistanceMaterial extends Material {
  23174. constructor( parameters ) {
  23175. super();
  23176. this.isMeshDistanceMaterial = true;
  23177. this.type = 'MeshDistanceMaterial';
  23178. this.map = null;
  23179. this.alphaMap = null;
  23180. this.displacementMap = null;
  23181. this.displacementScale = 1;
  23182. this.displacementBias = 0;
  23183. this.setValues( parameters );
  23184. }
  23185. copy( source ) {
  23186. super.copy( source );
  23187. this.map = source.map;
  23188. this.alphaMap = source.alphaMap;
  23189. this.displacementMap = source.displacementMap;
  23190. this.displacementScale = source.displacementScale;
  23191. this.displacementBias = source.displacementBias;
  23192. return this;
  23193. }
  23194. }
  23195. class MeshMatcapMaterial extends Material {
  23196. constructor( parameters ) {
  23197. super();
  23198. this.isMeshMatcapMaterial = true;
  23199. this.defines = { 'MATCAP': '' };
  23200. this.type = 'MeshMatcapMaterial';
  23201. this.color = new Color( 0xffffff ); // diffuse
  23202. this.matcap = null;
  23203. this.map = null;
  23204. this.bumpMap = null;
  23205. this.bumpScale = 1;
  23206. this.normalMap = null;
  23207. this.normalMapType = TangentSpaceNormalMap;
  23208. this.normalScale = new Vector2( 1, 1 );
  23209. this.displacementMap = null;
  23210. this.displacementScale = 1;
  23211. this.displacementBias = 0;
  23212. this.alphaMap = null;
  23213. this.flatShading = false;
  23214. this.fog = true;
  23215. this.setValues( parameters );
  23216. }
  23217. copy( source ) {
  23218. super.copy( source );
  23219. this.defines = { 'MATCAP': '' };
  23220. this.color.copy( source.color );
  23221. this.matcap = source.matcap;
  23222. this.map = source.map;
  23223. this.bumpMap = source.bumpMap;
  23224. this.bumpScale = source.bumpScale;
  23225. this.normalMap = source.normalMap;
  23226. this.normalMapType = source.normalMapType;
  23227. this.normalScale.copy( source.normalScale );
  23228. this.displacementMap = source.displacementMap;
  23229. this.displacementScale = source.displacementScale;
  23230. this.displacementBias = source.displacementBias;
  23231. this.alphaMap = source.alphaMap;
  23232. this.flatShading = source.flatShading;
  23233. this.fog = source.fog;
  23234. return this;
  23235. }
  23236. }
  23237. class LineDashedMaterial extends LineBasicMaterial {
  23238. constructor( parameters ) {
  23239. super();
  23240. this.isLineDashedMaterial = true;
  23241. this.type = 'LineDashedMaterial';
  23242. this.scale = 1;
  23243. this.dashSize = 3;
  23244. this.gapSize = 1;
  23245. this.setValues( parameters );
  23246. }
  23247. copy( source ) {
  23248. super.copy( source );
  23249. this.scale = source.scale;
  23250. this.dashSize = source.dashSize;
  23251. this.gapSize = source.gapSize;
  23252. return this;
  23253. }
  23254. }
  23255. // converts an array to a specific type
  23256. function convertArray( array, type, forceClone ) {
  23257. if ( ! array || // let 'undefined' and 'null' pass
  23258. ! forceClone && array.constructor === type ) return array;
  23259. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  23260. return new type( array ); // create typed array
  23261. }
  23262. return Array.prototype.slice.call( array ); // create Array
  23263. }
  23264. function isTypedArray( object ) {
  23265. return ArrayBuffer.isView( object ) &&
  23266. ! ( object instanceof DataView );
  23267. }
  23268. // returns an array by which times and values can be sorted
  23269. function getKeyframeOrder( times ) {
  23270. function compareTime( i, j ) {
  23271. return times[ i ] - times[ j ];
  23272. }
  23273. const n = times.length;
  23274. const result = new Array( n );
  23275. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  23276. result.sort( compareTime );
  23277. return result;
  23278. }
  23279. // uses the array previously returned by 'getKeyframeOrder' to sort data
  23280. function sortedArray( values, stride, order ) {
  23281. const nValues = values.length;
  23282. const result = new values.constructor( nValues );
  23283. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  23284. const srcOffset = order[ i ] * stride;
  23285. for ( let j = 0; j !== stride; ++ j ) {
  23286. result[ dstOffset ++ ] = values[ srcOffset + j ];
  23287. }
  23288. }
  23289. return result;
  23290. }
  23291. // function for parsing AOS keyframe formats
  23292. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  23293. let i = 1, key = jsonKeys[ 0 ];
  23294. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  23295. key = jsonKeys[ i ++ ];
  23296. }
  23297. if ( key === undefined ) return; // no data
  23298. let value = key[ valuePropertyName ];
  23299. if ( value === undefined ) return; // no data
  23300. if ( Array.isArray( value ) ) {
  23301. do {
  23302. value = key[ valuePropertyName ];
  23303. if ( value !== undefined ) {
  23304. times.push( key.time );
  23305. values.push( ...value ); // push all elements
  23306. }
  23307. key = jsonKeys[ i ++ ];
  23308. } while ( key !== undefined );
  23309. } else if ( value.toArray !== undefined ) {
  23310. // ...assume THREE.Math-ish
  23311. do {
  23312. value = key[ valuePropertyName ];
  23313. if ( value !== undefined ) {
  23314. times.push( key.time );
  23315. value.toArray( values, values.length );
  23316. }
  23317. key = jsonKeys[ i ++ ];
  23318. } while ( key !== undefined );
  23319. } else {
  23320. // otherwise push as-is
  23321. do {
  23322. value = key[ valuePropertyName ];
  23323. if ( value !== undefined ) {
  23324. times.push( key.time );
  23325. values.push( value );
  23326. }
  23327. key = jsonKeys[ i ++ ];
  23328. } while ( key !== undefined );
  23329. }
  23330. }
  23331. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  23332. const clip = sourceClip.clone();
  23333. clip.name = name;
  23334. const tracks = [];
  23335. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23336. const track = clip.tracks[ i ];
  23337. const valueSize = track.getValueSize();
  23338. const times = [];
  23339. const values = [];
  23340. for ( let j = 0; j < track.times.length; ++ j ) {
  23341. const frame = track.times[ j ] * fps;
  23342. if ( frame < startFrame || frame >= endFrame ) continue;
  23343. times.push( track.times[ j ] );
  23344. for ( let k = 0; k < valueSize; ++ k ) {
  23345. values.push( track.values[ j * valueSize + k ] );
  23346. }
  23347. }
  23348. if ( times.length === 0 ) continue;
  23349. track.times = convertArray( times, track.times.constructor );
  23350. track.values = convertArray( values, track.values.constructor );
  23351. tracks.push( track );
  23352. }
  23353. clip.tracks = tracks;
  23354. // find minimum .times value across all tracks in the trimmed clip
  23355. let minStartTime = Infinity;
  23356. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23357. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  23358. minStartTime = clip.tracks[ i ].times[ 0 ];
  23359. }
  23360. }
  23361. // shift all tracks such that clip begins at t=0
  23362. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23363. clip.tracks[ i ].shift( -1 * minStartTime );
  23364. }
  23365. clip.resetDuration();
  23366. return clip;
  23367. }
  23368. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  23369. if ( fps <= 0 ) fps = 30;
  23370. const numTracks = referenceClip.tracks.length;
  23371. const referenceTime = referenceFrame / fps;
  23372. // Make each track's values relative to the values at the reference frame
  23373. for ( let i = 0; i < numTracks; ++ i ) {
  23374. const referenceTrack = referenceClip.tracks[ i ];
  23375. const referenceTrackType = referenceTrack.ValueTypeName;
  23376. // Skip this track if it's non-numeric
  23377. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  23378. // Find the track in the target clip whose name and type matches the reference track
  23379. const targetTrack = targetClip.tracks.find( function ( track ) {
  23380. return track.name === referenceTrack.name
  23381. && track.ValueTypeName === referenceTrackType;
  23382. } );
  23383. if ( targetTrack === undefined ) continue;
  23384. let referenceOffset = 0;
  23385. const referenceValueSize = referenceTrack.getValueSize();
  23386. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23387. referenceOffset = referenceValueSize / 3;
  23388. }
  23389. let targetOffset = 0;
  23390. const targetValueSize = targetTrack.getValueSize();
  23391. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23392. targetOffset = targetValueSize / 3;
  23393. }
  23394. const lastIndex = referenceTrack.times.length - 1;
  23395. let referenceValue;
  23396. // Find the value to subtract out of the track
  23397. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  23398. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23399. const startIndex = referenceOffset;
  23400. const endIndex = referenceValueSize - referenceOffset;
  23401. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  23402. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  23403. // Reference frame is after the last keyframe, so just use the last keyframe
  23404. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23405. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23406. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  23407. } else {
  23408. // Interpolate to the reference value
  23409. const interpolant = referenceTrack.createInterpolant();
  23410. const startIndex = referenceOffset;
  23411. const endIndex = referenceValueSize - referenceOffset;
  23412. interpolant.evaluate( referenceTime );
  23413. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  23414. }
  23415. // Conjugate the quaternion
  23416. if ( referenceTrackType === 'quaternion' ) {
  23417. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  23418. referenceQuat.toArray( referenceValue );
  23419. }
  23420. // Subtract the reference value from all of the track values
  23421. const numTimes = targetTrack.times.length;
  23422. for ( let j = 0; j < numTimes; ++ j ) {
  23423. const valueStart = j * targetValueSize + targetOffset;
  23424. if ( referenceTrackType === 'quaternion' ) {
  23425. // Multiply the conjugate for quaternion track types
  23426. Quaternion.multiplyQuaternionsFlat(
  23427. targetTrack.values,
  23428. valueStart,
  23429. referenceValue,
  23430. 0,
  23431. targetTrack.values,
  23432. valueStart
  23433. );
  23434. } else {
  23435. const valueEnd = targetValueSize - targetOffset * 2;
  23436. // Subtract each value for all other numeric track types
  23437. for ( let k = 0; k < valueEnd; ++ k ) {
  23438. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  23439. }
  23440. }
  23441. }
  23442. }
  23443. targetClip.blendMode = AdditiveAnimationBlendMode;
  23444. return targetClip;
  23445. }
  23446. const AnimationUtils = {
  23447. convertArray: convertArray,
  23448. isTypedArray: isTypedArray,
  23449. getKeyframeOrder: getKeyframeOrder,
  23450. sortedArray: sortedArray,
  23451. flattenJSON: flattenJSON,
  23452. subclip: subclip,
  23453. makeClipAdditive: makeClipAdditive
  23454. };
  23455. /**
  23456. * Abstract base class of interpolants over parametric samples.
  23457. *
  23458. * The parameter domain is one dimensional, typically the time or a path
  23459. * along a curve defined by the data.
  23460. *
  23461. * The sample values can have any dimensionality and derived classes may
  23462. * apply special interpretations to the data.
  23463. *
  23464. * This class provides the interval seek in a Template Method, deferring
  23465. * the actual interpolation to derived classes.
  23466. *
  23467. * Time complexity is O(1) for linear access crossing at most two points
  23468. * and O(log N) for random access, where N is the number of positions.
  23469. *
  23470. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  23471. *
  23472. * @abstract
  23473. */
  23474. class Interpolant {
  23475. /**
  23476. * Constructs a new interpolant.
  23477. *
  23478. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  23479. * @param {TypedArray} sampleValues - The sample values.
  23480. * @param {number} sampleSize - The sample size
  23481. * @param {TypedArray} [resultBuffer] - The result buffer.
  23482. */
  23483. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23484. /**
  23485. * The parameter positions.
  23486. *
  23487. * @type {TypedArray}
  23488. */
  23489. this.parameterPositions = parameterPositions;
  23490. /**
  23491. * A cache index.
  23492. *
  23493. * @private
  23494. * @type {number}
  23495. * @default 0
  23496. */
  23497. this._cachedIndex = 0;
  23498. /**
  23499. * The result buffer.
  23500. *
  23501. * @type {TypedArray}
  23502. */
  23503. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  23504. /**
  23505. * The sample values.
  23506. *
  23507. * @type {TypedArray}
  23508. */
  23509. this.sampleValues = sampleValues;
  23510. /**
  23511. * The value size.
  23512. *
  23513. * @type {TypedArray}
  23514. */
  23515. this.valueSize = sampleSize;
  23516. /**
  23517. * The interpolation settings.
  23518. *
  23519. * @type {?Object}
  23520. * @default null
  23521. */
  23522. this.settings = null;
  23523. /**
  23524. * The default settings object.
  23525. *
  23526. * @type {Object}
  23527. */
  23528. this.DefaultSettings_ = {};
  23529. }
  23530. /**
  23531. * Evaluate the interpolant at position `t`.
  23532. *
  23533. * @param {number} t - The interpolation factor.
  23534. * @return {TypedArray} The result buffer.
  23535. */
  23536. evaluate( t ) {
  23537. const pp = this.parameterPositions;
  23538. let i1 = this._cachedIndex,
  23539. t1 = pp[ i1 ],
  23540. t0 = pp[ i1 - 1 ];
  23541. validate_interval: {
  23542. seek: {
  23543. let right;
  23544. linear_scan: {
  23545. //- See http://jsperf.com/comparison-to-undefined/3
  23546. //- slower code:
  23547. //-
  23548. //- if ( t >= t1 || t1 === undefined ) {
  23549. forward_scan: if ( ! ( t < t1 ) ) {
  23550. for ( let giveUpAt = i1 + 2; ; ) {
  23551. if ( t1 === undefined ) {
  23552. if ( t < t0 ) break forward_scan;
  23553. // after end
  23554. i1 = pp.length;
  23555. this._cachedIndex = i1;
  23556. return this.copySampleValue_( i1 - 1 );
  23557. }
  23558. if ( i1 === giveUpAt ) break; // this loop
  23559. t0 = t1;
  23560. t1 = pp[ ++ i1 ];
  23561. if ( t < t1 ) {
  23562. // we have arrived at the sought interval
  23563. break seek;
  23564. }
  23565. }
  23566. // prepare binary search on the right side of the index
  23567. right = pp.length;
  23568. break linear_scan;
  23569. }
  23570. //- slower code:
  23571. //- if ( t < t0 || t0 === undefined ) {
  23572. if ( ! ( t >= t0 ) ) {
  23573. // looping?
  23574. const t1global = pp[ 1 ];
  23575. if ( t < t1global ) {
  23576. i1 = 2; // + 1, using the scan for the details
  23577. t0 = t1global;
  23578. }
  23579. // linear reverse scan
  23580. for ( let giveUpAt = i1 - 2; ; ) {
  23581. if ( t0 === undefined ) {
  23582. // before start
  23583. this._cachedIndex = 0;
  23584. return this.copySampleValue_( 0 );
  23585. }
  23586. if ( i1 === giveUpAt ) break; // this loop
  23587. t1 = t0;
  23588. t0 = pp[ -- i1 - 1 ];
  23589. if ( t >= t0 ) {
  23590. // we have arrived at the sought interval
  23591. break seek;
  23592. }
  23593. }
  23594. // prepare binary search on the left side of the index
  23595. right = i1;
  23596. i1 = 0;
  23597. break linear_scan;
  23598. }
  23599. // the interval is valid
  23600. break validate_interval;
  23601. } // linear scan
  23602. // binary search
  23603. while ( i1 < right ) {
  23604. const mid = ( i1 + right ) >>> 1;
  23605. if ( t < pp[ mid ] ) {
  23606. right = mid;
  23607. } else {
  23608. i1 = mid + 1;
  23609. }
  23610. }
  23611. t1 = pp[ i1 ];
  23612. t0 = pp[ i1 - 1 ];
  23613. // check boundary cases, again
  23614. if ( t0 === undefined ) {
  23615. this._cachedIndex = 0;
  23616. return this.copySampleValue_( 0 );
  23617. }
  23618. if ( t1 === undefined ) {
  23619. i1 = pp.length;
  23620. this._cachedIndex = i1;
  23621. return this.copySampleValue_( i1 - 1 );
  23622. }
  23623. } // seek
  23624. this._cachedIndex = i1;
  23625. this.intervalChanged_( i1, t0, t1 );
  23626. } // validate_interval
  23627. return this.interpolate_( i1, t0, t, t1 );
  23628. }
  23629. /**
  23630. * Returns the interpolation settings.
  23631. *
  23632. * @return {Object} The interpolation settings.
  23633. */
  23634. getSettings_() {
  23635. return this.settings || this.DefaultSettings_;
  23636. }
  23637. /**
  23638. * Copies a sample value to the result buffer.
  23639. *
  23640. * @param {number} index - An index into the sample value buffer.
  23641. * @return {TypedArray} The result buffer.
  23642. */
  23643. copySampleValue_( index ) {
  23644. // copies a sample value to the result buffer
  23645. const result = this.resultBuffer,
  23646. values = this.sampleValues,
  23647. stride = this.valueSize,
  23648. offset = index * stride;
  23649. for ( let i = 0; i !== stride; ++ i ) {
  23650. result[ i ] = values[ offset + i ];
  23651. }
  23652. return result;
  23653. }
  23654. /**
  23655. * Copies a sample value to the result buffer.
  23656. *
  23657. * @abstract
  23658. * @param {number} i1 - An index into the sample value buffer.
  23659. * @param {number} t0 - The previous interpolation factor.
  23660. * @param {number} t - The current interpolation factor.
  23661. * @param {number} t1 - The next interpolation factor.
  23662. * @return {TypedArray} The result buffer.
  23663. */
  23664. interpolate_( /* i1, t0, t, t1 */ ) {
  23665. throw new Error( 'call to abstract method' );
  23666. // implementations shall return this.resultBuffer
  23667. }
  23668. /**
  23669. * Optional method that is executed when the interval has changed.
  23670. *
  23671. * @param {number} i1 - An index into the sample value buffer.
  23672. * @param {number} t0 - The previous interpolation factor.
  23673. * @param {number} t - The current interpolation factor.
  23674. */
  23675. intervalChanged_( /* i1, t0, t1 */ ) {
  23676. // empty
  23677. }
  23678. }
  23679. /**
  23680. * Fast and simple cubic spline interpolant.
  23681. *
  23682. * It was derived from a Hermitian construction setting the first derivative
  23683. * at each sample position to the linear slope between neighboring positions
  23684. * over their parameter interval.
  23685. *
  23686. * @augments Interpolant
  23687. */
  23688. class CubicInterpolant extends Interpolant {
  23689. /**
  23690. * Constructs a new cubic interpolant.
  23691. *
  23692. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  23693. * @param {TypedArray} sampleValues - The sample values.
  23694. * @param {number} sampleSize - The sample size
  23695. * @param {TypedArray} [resultBuffer] - The result buffer.
  23696. */
  23697. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23698. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23699. this._weightPrev = -0;
  23700. this._offsetPrev = -0;
  23701. this._weightNext = -0;
  23702. this._offsetNext = -0;
  23703. this.DefaultSettings_ = {
  23704. endingStart: ZeroCurvatureEnding,
  23705. endingEnd: ZeroCurvatureEnding
  23706. };
  23707. }
  23708. intervalChanged_( i1, t0, t1 ) {
  23709. const pp = this.parameterPositions;
  23710. let iPrev = i1 - 2,
  23711. iNext = i1 + 1,
  23712. tPrev = pp[ iPrev ],
  23713. tNext = pp[ iNext ];
  23714. if ( tPrev === undefined ) {
  23715. switch ( this.getSettings_().endingStart ) {
  23716. case ZeroSlopeEnding:
  23717. // f'(t0) = 0
  23718. iPrev = i1;
  23719. tPrev = 2 * t0 - t1;
  23720. break;
  23721. case WrapAroundEnding:
  23722. // use the other end of the curve
  23723. iPrev = pp.length - 2;
  23724. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23725. break;
  23726. default: // ZeroCurvatureEnding
  23727. // f''(t0) = 0 a.k.a. Natural Spline
  23728. iPrev = i1;
  23729. tPrev = t1;
  23730. }
  23731. }
  23732. if ( tNext === undefined ) {
  23733. switch ( this.getSettings_().endingEnd ) {
  23734. case ZeroSlopeEnding:
  23735. // f'(tN) = 0
  23736. iNext = i1;
  23737. tNext = 2 * t1 - t0;
  23738. break;
  23739. case WrapAroundEnding:
  23740. // use the other end of the curve
  23741. iNext = 1;
  23742. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23743. break;
  23744. default: // ZeroCurvatureEnding
  23745. // f''(tN) = 0, a.k.a. Natural Spline
  23746. iNext = i1 - 1;
  23747. tNext = t0;
  23748. }
  23749. }
  23750. const halfDt = ( t1 - t0 ) * 0.5,
  23751. stride = this.valueSize;
  23752. this._weightPrev = halfDt / ( t0 - tPrev );
  23753. this._weightNext = halfDt / ( tNext - t1 );
  23754. this._offsetPrev = iPrev * stride;
  23755. this._offsetNext = iNext * stride;
  23756. }
  23757. interpolate_( i1, t0, t, t1 ) {
  23758. const result = this.resultBuffer,
  23759. values = this.sampleValues,
  23760. stride = this.valueSize,
  23761. o1 = i1 * stride, o0 = o1 - stride,
  23762. oP = this._offsetPrev, oN = this._offsetNext,
  23763. wP = this._weightPrev, wN = this._weightNext,
  23764. p = ( t - t0 ) / ( t1 - t0 ),
  23765. pp = p * p,
  23766. ppp = pp * p;
  23767. // evaluate polynomials
  23768. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23769. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  23770. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23771. const sN = wN * ppp - wN * pp;
  23772. // combine data linearly
  23773. for ( let i = 0; i !== stride; ++ i ) {
  23774. result[ i ] =
  23775. sP * values[ oP + i ] +
  23776. s0 * values[ o0 + i ] +
  23777. s1 * values[ o1 + i ] +
  23778. sN * values[ oN + i ];
  23779. }
  23780. return result;
  23781. }
  23782. }
  23783. /**
  23784. * A basic linear interpolant.
  23785. *
  23786. * @augments Interpolant
  23787. */
  23788. class LinearInterpolant extends Interpolant {
  23789. /**
  23790. * Constructs a new linear interpolant.
  23791. *
  23792. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  23793. * @param {TypedArray} sampleValues - The sample values.
  23794. * @param {number} sampleSize - The sample size
  23795. * @param {TypedArray} [resultBuffer] - The result buffer.
  23796. */
  23797. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23798. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23799. }
  23800. interpolate_( i1, t0, t, t1 ) {
  23801. const result = this.resultBuffer,
  23802. values = this.sampleValues,
  23803. stride = this.valueSize,
  23804. offset1 = i1 * stride,
  23805. offset0 = offset1 - stride,
  23806. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23807. weight0 = 1 - weight1;
  23808. for ( let i = 0; i !== stride; ++ i ) {
  23809. result[ i ] =
  23810. values[ offset0 + i ] * weight0 +
  23811. values[ offset1 + i ] * weight1;
  23812. }
  23813. return result;
  23814. }
  23815. }
  23816. /**
  23817. * Interpolant that evaluates to the sample value at the position preceding
  23818. * the parameter.
  23819. *
  23820. * @augments Interpolant
  23821. */
  23822. class DiscreteInterpolant extends Interpolant {
  23823. /**
  23824. * Constructs a new discrete interpolant.
  23825. *
  23826. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  23827. * @param {TypedArray} sampleValues - The sample values.
  23828. * @param {number} sampleSize - The sample size
  23829. * @param {TypedArray} [resultBuffer] - The result buffer.
  23830. */
  23831. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23832. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23833. }
  23834. interpolate_( i1 /*, t0, t, t1 */ ) {
  23835. return this.copySampleValue_( i1 - 1 );
  23836. }
  23837. }
  23838. class KeyframeTrack {
  23839. constructor( name, times, values, interpolation ) {
  23840. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23841. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23842. this.name = name;
  23843. this.times = convertArray( times, this.TimeBufferType );
  23844. this.values = convertArray( values, this.ValueBufferType );
  23845. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23846. }
  23847. // Serialization (in static context, because of constructor invocation
  23848. // and automatic invocation of .toJSON):
  23849. static toJSON( track ) {
  23850. const trackType = track.constructor;
  23851. let json;
  23852. // derived classes can define a static toJSON method
  23853. if ( trackType.toJSON !== this.toJSON ) {
  23854. json = trackType.toJSON( track );
  23855. } else {
  23856. // by default, we assume the data can be serialized as-is
  23857. json = {
  23858. 'name': track.name,
  23859. 'times': convertArray( track.times, Array ),
  23860. 'values': convertArray( track.values, Array )
  23861. };
  23862. const interpolation = track.getInterpolation();
  23863. if ( interpolation !== track.DefaultInterpolation ) {
  23864. json.interpolation = interpolation;
  23865. }
  23866. }
  23867. json.type = track.ValueTypeName; // mandatory
  23868. return json;
  23869. }
  23870. InterpolantFactoryMethodDiscrete( result ) {
  23871. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23872. }
  23873. InterpolantFactoryMethodLinear( result ) {
  23874. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23875. }
  23876. InterpolantFactoryMethodSmooth( result ) {
  23877. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23878. }
  23879. setInterpolation( interpolation ) {
  23880. let factoryMethod;
  23881. switch ( interpolation ) {
  23882. case InterpolateDiscrete:
  23883. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23884. break;
  23885. case InterpolateLinear:
  23886. factoryMethod = this.InterpolantFactoryMethodLinear;
  23887. break;
  23888. case InterpolateSmooth:
  23889. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23890. break;
  23891. }
  23892. if ( factoryMethod === undefined ) {
  23893. const message = 'unsupported interpolation for ' +
  23894. this.ValueTypeName + ' keyframe track named ' + this.name;
  23895. if ( this.createInterpolant === undefined ) {
  23896. // fall back to default, unless the default itself is messed up
  23897. if ( interpolation !== this.DefaultInterpolation ) {
  23898. this.setInterpolation( this.DefaultInterpolation );
  23899. } else {
  23900. throw new Error( message ); // fatal, in this case
  23901. }
  23902. }
  23903. console.warn( 'THREE.KeyframeTrack:', message );
  23904. return this;
  23905. }
  23906. this.createInterpolant = factoryMethod;
  23907. return this;
  23908. }
  23909. getInterpolation() {
  23910. switch ( this.createInterpolant ) {
  23911. case this.InterpolantFactoryMethodDiscrete:
  23912. return InterpolateDiscrete;
  23913. case this.InterpolantFactoryMethodLinear:
  23914. return InterpolateLinear;
  23915. case this.InterpolantFactoryMethodSmooth:
  23916. return InterpolateSmooth;
  23917. }
  23918. }
  23919. getValueSize() {
  23920. return this.values.length / this.times.length;
  23921. }
  23922. // move all keyframes either forwards or backwards in time
  23923. shift( timeOffset ) {
  23924. if ( timeOffset !== 0.0 ) {
  23925. const times = this.times;
  23926. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23927. times[ i ] += timeOffset;
  23928. }
  23929. }
  23930. return this;
  23931. }
  23932. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23933. scale( timeScale ) {
  23934. if ( timeScale !== 1.0 ) {
  23935. const times = this.times;
  23936. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23937. times[ i ] *= timeScale;
  23938. }
  23939. }
  23940. return this;
  23941. }
  23942. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23943. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23944. trim( startTime, endTime ) {
  23945. const times = this.times,
  23946. nKeys = times.length;
  23947. let from = 0,
  23948. to = nKeys - 1;
  23949. while ( from !== nKeys && times[ from ] < startTime ) {
  23950. ++ from;
  23951. }
  23952. while ( to !== -1 && times[ to ] > endTime ) {
  23953. -- to;
  23954. }
  23955. ++ to; // inclusive -> exclusive bound
  23956. if ( from !== 0 || to !== nKeys ) {
  23957. // empty tracks are forbidden, so keep at least one keyframe
  23958. if ( from >= to ) {
  23959. to = Math.max( to, 1 );
  23960. from = to - 1;
  23961. }
  23962. const stride = this.getValueSize();
  23963. this.times = times.slice( from, to );
  23964. this.values = this.values.slice( from * stride, to * stride );
  23965. }
  23966. return this;
  23967. }
  23968. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23969. validate() {
  23970. let valid = true;
  23971. const valueSize = this.getValueSize();
  23972. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23973. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23974. valid = false;
  23975. }
  23976. const times = this.times,
  23977. values = this.values,
  23978. nKeys = times.length;
  23979. if ( nKeys === 0 ) {
  23980. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23981. valid = false;
  23982. }
  23983. let prevTime = null;
  23984. for ( let i = 0; i !== nKeys; i ++ ) {
  23985. const currTime = times[ i ];
  23986. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23987. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23988. valid = false;
  23989. break;
  23990. }
  23991. if ( prevTime !== null && prevTime > currTime ) {
  23992. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23993. valid = false;
  23994. break;
  23995. }
  23996. prevTime = currTime;
  23997. }
  23998. if ( values !== undefined ) {
  23999. if ( isTypedArray( values ) ) {
  24000. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  24001. const value = values[ i ];
  24002. if ( isNaN( value ) ) {
  24003. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  24004. valid = false;
  24005. break;
  24006. }
  24007. }
  24008. }
  24009. }
  24010. return valid;
  24011. }
  24012. // removes equivalent sequential keys as common in morph target sequences
  24013. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  24014. optimize() {
  24015. // times or values may be shared with other tracks, so overwriting is unsafe
  24016. const times = this.times.slice(),
  24017. values = this.values.slice(),
  24018. stride = this.getValueSize(),
  24019. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  24020. lastIndex = times.length - 1;
  24021. let writeIndex = 1;
  24022. for ( let i = 1; i < lastIndex; ++ i ) {
  24023. let keep = false;
  24024. const time = times[ i ];
  24025. const timeNext = times[ i + 1 ];
  24026. // remove adjacent keyframes scheduled at the same time
  24027. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  24028. if ( ! smoothInterpolation ) {
  24029. // remove unnecessary keyframes same as their neighbors
  24030. const offset = i * stride,
  24031. offsetP = offset - stride,
  24032. offsetN = offset + stride;
  24033. for ( let j = 0; j !== stride; ++ j ) {
  24034. const value = values[ offset + j ];
  24035. if ( value !== values[ offsetP + j ] ||
  24036. value !== values[ offsetN + j ] ) {
  24037. keep = true;
  24038. break;
  24039. }
  24040. }
  24041. } else {
  24042. keep = true;
  24043. }
  24044. }
  24045. // in-place compaction
  24046. if ( keep ) {
  24047. if ( i !== writeIndex ) {
  24048. times[ writeIndex ] = times[ i ];
  24049. const readOffset = i * stride,
  24050. writeOffset = writeIndex * stride;
  24051. for ( let j = 0; j !== stride; ++ j ) {
  24052. values[ writeOffset + j ] = values[ readOffset + j ];
  24053. }
  24054. }
  24055. ++ writeIndex;
  24056. }
  24057. }
  24058. // flush last keyframe (compaction looks ahead)
  24059. if ( lastIndex > 0 ) {
  24060. times[ writeIndex ] = times[ lastIndex ];
  24061. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  24062. values[ writeOffset + j ] = values[ readOffset + j ];
  24063. }
  24064. ++ writeIndex;
  24065. }
  24066. if ( writeIndex !== times.length ) {
  24067. this.times = times.slice( 0, writeIndex );
  24068. this.values = values.slice( 0, writeIndex * stride );
  24069. } else {
  24070. this.times = times;
  24071. this.values = values;
  24072. }
  24073. return this;
  24074. }
  24075. clone() {
  24076. const times = this.times.slice();
  24077. const values = this.values.slice();
  24078. const TypedKeyframeTrack = this.constructor;
  24079. const track = new TypedKeyframeTrack( this.name, times, values );
  24080. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  24081. track.createInterpolant = this.createInterpolant;
  24082. return track;
  24083. }
  24084. }
  24085. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  24086. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  24087. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  24088. /**
  24089. * A Track of Boolean keyframe values.
  24090. */
  24091. class BooleanKeyframeTrack extends KeyframeTrack {
  24092. // No interpolation parameter because only InterpolateDiscrete is valid.
  24093. constructor( name, times, values ) {
  24094. super( name, times, values );
  24095. }
  24096. }
  24097. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  24098. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  24099. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  24100. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  24101. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24102. /**
  24103. * A Track of keyframe values that represent color.
  24104. */
  24105. class ColorKeyframeTrack extends KeyframeTrack {}
  24106. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  24107. /**
  24108. * A Track of numeric keyframe values.
  24109. */
  24110. class NumberKeyframeTrack extends KeyframeTrack {}
  24111. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  24112. /**
  24113. * Spherical linear unit quaternion interpolant.
  24114. *
  24115. * @augments Interpolant
  24116. */
  24117. class QuaternionLinearInterpolant extends Interpolant {
  24118. /**
  24119. * Constructs a new SLERP interpolant.
  24120. *
  24121. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  24122. * @param {TypedArray} sampleValues - The sample values.
  24123. * @param {number} sampleSize - The sample size
  24124. * @param {TypedArray} [resultBuffer] - The result buffer.
  24125. */
  24126. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24127. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24128. }
  24129. interpolate_( i1, t0, t, t1 ) {
  24130. const result = this.resultBuffer,
  24131. values = this.sampleValues,
  24132. stride = this.valueSize,
  24133. alpha = ( t - t0 ) / ( t1 - t0 );
  24134. let offset = i1 * stride;
  24135. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  24136. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  24137. }
  24138. return result;
  24139. }
  24140. }
  24141. /**
  24142. * A Track of quaternion keyframe values.
  24143. */
  24144. class QuaternionKeyframeTrack extends KeyframeTrack {
  24145. InterpolantFactoryMethodLinear( result ) {
  24146. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24147. }
  24148. }
  24149. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  24150. // ValueBufferType is inherited
  24151. // DefaultInterpolation is inherited;
  24152. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24153. /**
  24154. * A Track that interpolates Strings
  24155. */
  24156. class StringKeyframeTrack extends KeyframeTrack {
  24157. // No interpolation parameter because only InterpolateDiscrete is valid.
  24158. constructor( name, times, values ) {
  24159. super( name, times, values );
  24160. }
  24161. }
  24162. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  24163. StringKeyframeTrack.prototype.ValueBufferType = Array;
  24164. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  24165. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  24166. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24167. /**
  24168. * A Track of vectored keyframe values.
  24169. */
  24170. class VectorKeyframeTrack extends KeyframeTrack {}
  24171. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  24172. class AnimationClip {
  24173. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  24174. this.name = name;
  24175. this.tracks = tracks;
  24176. this.duration = duration;
  24177. this.blendMode = blendMode;
  24178. this.uuid = generateUUID();
  24179. // this means it should figure out its duration by scanning the tracks
  24180. if ( this.duration < 0 ) {
  24181. this.resetDuration();
  24182. }
  24183. }
  24184. static parse( json ) {
  24185. const tracks = [],
  24186. jsonTracks = json.tracks,
  24187. frameTime = 1.0 / ( json.fps || 1.0 );
  24188. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  24189. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  24190. }
  24191. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  24192. clip.uuid = json.uuid;
  24193. return clip;
  24194. }
  24195. static toJSON( clip ) {
  24196. const tracks = [],
  24197. clipTracks = clip.tracks;
  24198. const json = {
  24199. 'name': clip.name,
  24200. 'duration': clip.duration,
  24201. 'tracks': tracks,
  24202. 'uuid': clip.uuid,
  24203. 'blendMode': clip.blendMode
  24204. };
  24205. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  24206. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  24207. }
  24208. return json;
  24209. }
  24210. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  24211. const numMorphTargets = morphTargetSequence.length;
  24212. const tracks = [];
  24213. for ( let i = 0; i < numMorphTargets; i ++ ) {
  24214. let times = [];
  24215. let values = [];
  24216. times.push(
  24217. ( i + numMorphTargets - 1 ) % numMorphTargets,
  24218. i,
  24219. ( i + 1 ) % numMorphTargets );
  24220. values.push( 0, 1, 0 );
  24221. const order = getKeyframeOrder( times );
  24222. times = sortedArray( times, 1, order );
  24223. values = sortedArray( values, 1, order );
  24224. // if there is a key at the first frame, duplicate it as the
  24225. // last frame as well for perfect loop.
  24226. if ( ! noLoop && times[ 0 ] === 0 ) {
  24227. times.push( numMorphTargets );
  24228. values.push( values[ 0 ] );
  24229. }
  24230. tracks.push(
  24231. new NumberKeyframeTrack(
  24232. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  24233. times, values
  24234. ).scale( 1.0 / fps ) );
  24235. }
  24236. return new this( name, -1, tracks );
  24237. }
  24238. static findByName( objectOrClipArray, name ) {
  24239. let clipArray = objectOrClipArray;
  24240. if ( ! Array.isArray( objectOrClipArray ) ) {
  24241. const o = objectOrClipArray;
  24242. clipArray = o.geometry && o.geometry.animations || o.animations;
  24243. }
  24244. for ( let i = 0; i < clipArray.length; i ++ ) {
  24245. if ( clipArray[ i ].name === name ) {
  24246. return clipArray[ i ];
  24247. }
  24248. }
  24249. return null;
  24250. }
  24251. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  24252. const animationToMorphTargets = {};
  24253. // tested with https://regex101.com/ on trick sequences
  24254. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  24255. const pattern = /^([\w-]*?)([\d]+)$/;
  24256. // sort morph target names into animation groups based
  24257. // patterns like Walk_001, Walk_002, Run_001, Run_002
  24258. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  24259. const morphTarget = morphTargets[ i ];
  24260. const parts = morphTarget.name.match( pattern );
  24261. if ( parts && parts.length > 1 ) {
  24262. const name = parts[ 1 ];
  24263. let animationMorphTargets = animationToMorphTargets[ name ];
  24264. if ( ! animationMorphTargets ) {
  24265. animationToMorphTargets[ name ] = animationMorphTargets = [];
  24266. }
  24267. animationMorphTargets.push( morphTarget );
  24268. }
  24269. }
  24270. const clips = [];
  24271. for ( const name in animationToMorphTargets ) {
  24272. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  24273. }
  24274. return clips;
  24275. }
  24276. // parse the animation.hierarchy format
  24277. static parseAnimation( animation, bones ) {
  24278. if ( ! animation ) {
  24279. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  24280. return null;
  24281. }
  24282. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  24283. // only return track if there are actually keys.
  24284. if ( animationKeys.length !== 0 ) {
  24285. const times = [];
  24286. const values = [];
  24287. flattenJSON( animationKeys, times, values, propertyName );
  24288. // empty keys are filtered out, so check again
  24289. if ( times.length !== 0 ) {
  24290. destTracks.push( new trackType( trackName, times, values ) );
  24291. }
  24292. }
  24293. };
  24294. const tracks = [];
  24295. const clipName = animation.name || 'default';
  24296. const fps = animation.fps || 30;
  24297. const blendMode = animation.blendMode;
  24298. // automatic length determination in AnimationClip.
  24299. let duration = animation.length || -1;
  24300. const hierarchyTracks = animation.hierarchy || [];
  24301. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  24302. const animationKeys = hierarchyTracks[ h ].keys;
  24303. // skip empty tracks
  24304. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  24305. // process morph targets
  24306. if ( animationKeys[ 0 ].morphTargets ) {
  24307. // figure out all morph targets used in this track
  24308. const morphTargetNames = {};
  24309. let k;
  24310. for ( k = 0; k < animationKeys.length; k ++ ) {
  24311. if ( animationKeys[ k ].morphTargets ) {
  24312. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  24313. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  24314. }
  24315. }
  24316. }
  24317. // create a track for each morph target with all zero
  24318. // morphTargetInfluences except for the keys in which
  24319. // the morphTarget is named.
  24320. for ( const morphTargetName in morphTargetNames ) {
  24321. const times = [];
  24322. const values = [];
  24323. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  24324. const animationKey = animationKeys[ k ];
  24325. times.push( animationKey.time );
  24326. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  24327. }
  24328. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  24329. }
  24330. duration = morphTargetNames.length * fps;
  24331. } else {
  24332. // ...assume skeletal animation
  24333. const boneName = '.bones[' + bones[ h ].name + ']';
  24334. addNonemptyTrack(
  24335. VectorKeyframeTrack, boneName + '.position',
  24336. animationKeys, 'pos', tracks );
  24337. addNonemptyTrack(
  24338. QuaternionKeyframeTrack, boneName + '.quaternion',
  24339. animationKeys, 'rot', tracks );
  24340. addNonemptyTrack(
  24341. VectorKeyframeTrack, boneName + '.scale',
  24342. animationKeys, 'scl', tracks );
  24343. }
  24344. }
  24345. if ( tracks.length === 0 ) {
  24346. return null;
  24347. }
  24348. const clip = new this( clipName, duration, tracks, blendMode );
  24349. return clip;
  24350. }
  24351. resetDuration() {
  24352. const tracks = this.tracks;
  24353. let duration = 0;
  24354. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  24355. const track = this.tracks[ i ];
  24356. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  24357. }
  24358. this.duration = duration;
  24359. return this;
  24360. }
  24361. trim() {
  24362. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24363. this.tracks[ i ].trim( 0, this.duration );
  24364. }
  24365. return this;
  24366. }
  24367. validate() {
  24368. let valid = true;
  24369. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24370. valid = valid && this.tracks[ i ].validate();
  24371. }
  24372. return valid;
  24373. }
  24374. optimize() {
  24375. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24376. this.tracks[ i ].optimize();
  24377. }
  24378. return this;
  24379. }
  24380. clone() {
  24381. const tracks = [];
  24382. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24383. tracks.push( this.tracks[ i ].clone() );
  24384. }
  24385. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  24386. }
  24387. toJSON() {
  24388. return this.constructor.toJSON( this );
  24389. }
  24390. }
  24391. function getTrackTypeForValueTypeName( typeName ) {
  24392. switch ( typeName.toLowerCase() ) {
  24393. case 'scalar':
  24394. case 'double':
  24395. case 'float':
  24396. case 'number':
  24397. case 'integer':
  24398. return NumberKeyframeTrack;
  24399. case 'vector':
  24400. case 'vector2':
  24401. case 'vector3':
  24402. case 'vector4':
  24403. return VectorKeyframeTrack;
  24404. case 'color':
  24405. return ColorKeyframeTrack;
  24406. case 'quaternion':
  24407. return QuaternionKeyframeTrack;
  24408. case 'bool':
  24409. case 'boolean':
  24410. return BooleanKeyframeTrack;
  24411. case 'string':
  24412. return StringKeyframeTrack;
  24413. }
  24414. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  24415. }
  24416. function parseKeyframeTrack( json ) {
  24417. if ( json.type === undefined ) {
  24418. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  24419. }
  24420. const trackType = getTrackTypeForValueTypeName( json.type );
  24421. if ( json.times === undefined ) {
  24422. const times = [], values = [];
  24423. flattenJSON( json.keys, times, values, 'value' );
  24424. json.times = times;
  24425. json.values = values;
  24426. }
  24427. // derived classes can define a static parse method
  24428. if ( trackType.parse !== undefined ) {
  24429. return trackType.parse( json );
  24430. } else {
  24431. // by default, we assume a constructor compatible with the base
  24432. return new trackType( json.name, json.times, json.values, json.interpolation );
  24433. }
  24434. }
  24435. const Cache = {
  24436. enabled: false,
  24437. files: {},
  24438. add: function ( key, file ) {
  24439. if ( this.enabled === false ) return;
  24440. // console.log( 'THREE.Cache', 'Adding key:', key );
  24441. this.files[ key ] = file;
  24442. },
  24443. get: function ( key ) {
  24444. if ( this.enabled === false ) return;
  24445. // console.log( 'THREE.Cache', 'Checking key:', key );
  24446. return this.files[ key ];
  24447. },
  24448. remove: function ( key ) {
  24449. delete this.files[ key ];
  24450. },
  24451. clear: function () {
  24452. this.files = {};
  24453. }
  24454. };
  24455. class LoadingManager {
  24456. constructor( onLoad, onProgress, onError ) {
  24457. const scope = this;
  24458. let isLoading = false;
  24459. let itemsLoaded = 0;
  24460. let itemsTotal = 0;
  24461. let urlModifier = undefined;
  24462. const handlers = [];
  24463. // Refer to #5689 for the reason why we don't set .onStart
  24464. // in the constructor
  24465. this.onStart = undefined;
  24466. this.onLoad = onLoad;
  24467. this.onProgress = onProgress;
  24468. this.onError = onError;
  24469. this.itemStart = function ( url ) {
  24470. itemsTotal ++;
  24471. if ( isLoading === false ) {
  24472. if ( scope.onStart !== undefined ) {
  24473. scope.onStart( url, itemsLoaded, itemsTotal );
  24474. }
  24475. }
  24476. isLoading = true;
  24477. };
  24478. this.itemEnd = function ( url ) {
  24479. itemsLoaded ++;
  24480. if ( scope.onProgress !== undefined ) {
  24481. scope.onProgress( url, itemsLoaded, itemsTotal );
  24482. }
  24483. if ( itemsLoaded === itemsTotal ) {
  24484. isLoading = false;
  24485. if ( scope.onLoad !== undefined ) {
  24486. scope.onLoad();
  24487. }
  24488. }
  24489. };
  24490. this.itemError = function ( url ) {
  24491. if ( scope.onError !== undefined ) {
  24492. scope.onError( url );
  24493. }
  24494. };
  24495. this.resolveURL = function ( url ) {
  24496. if ( urlModifier ) {
  24497. return urlModifier( url );
  24498. }
  24499. return url;
  24500. };
  24501. this.setURLModifier = function ( transform ) {
  24502. urlModifier = transform;
  24503. return this;
  24504. };
  24505. this.addHandler = function ( regex, loader ) {
  24506. handlers.push( regex, loader );
  24507. return this;
  24508. };
  24509. this.removeHandler = function ( regex ) {
  24510. const index = handlers.indexOf( regex );
  24511. if ( index !== -1 ) {
  24512. handlers.splice( index, 2 );
  24513. }
  24514. return this;
  24515. };
  24516. this.getHandler = function ( file ) {
  24517. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  24518. const regex = handlers[ i ];
  24519. const loader = handlers[ i + 1 ];
  24520. if ( regex.global ) regex.lastIndex = 0; // see #17920
  24521. if ( regex.test( file ) ) {
  24522. return loader;
  24523. }
  24524. }
  24525. return null;
  24526. };
  24527. }
  24528. }
  24529. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  24530. /**
  24531. * Abstract base class for loaders.
  24532. *
  24533. * @abstract
  24534. */
  24535. class Loader {
  24536. /**
  24537. * Constructs a new loader.
  24538. *
  24539. * @param {LoadingManager} [manager] - The loading manager.
  24540. */
  24541. constructor( manager ) {
  24542. /**
  24543. * The loading manager.
  24544. *
  24545. * @type {LoadingManager}
  24546. * @default DefaultLoadingManager
  24547. */
  24548. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24549. /**
  24550. * The crossOrigin string to implement CORS for loading the url from a
  24551. * different domain that allows CORS.
  24552. *
  24553. * @type {string}
  24554. * @default 'anonymous'
  24555. */
  24556. this.crossOrigin = 'anonymous';
  24557. /**
  24558. * Whether the XMLHttpRequest uses credentials.
  24559. *
  24560. * @type {boolean}
  24561. * @default false
  24562. */
  24563. this.withCredentials = false;
  24564. /**
  24565. * The base path from which the asset will be loaded.
  24566. *
  24567. * @type {string}
  24568. */
  24569. this.path = '';
  24570. /**
  24571. * The base path from which additional resources like textures will be loaded.
  24572. *
  24573. * @type {string}
  24574. */
  24575. this.resourcePath = '';
  24576. /**
  24577. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  24578. * used in HTTP request.
  24579. *
  24580. * @type {Object}
  24581. */
  24582. this.requestHeader = {};
  24583. }
  24584. /**
  24585. * This method needs to be implemented by all concrete loaders. It holds the
  24586. * logic for loading assets from the backend.
  24587. *
  24588. * @param {string} url - The path/URL of the file to be loaded.
  24589. * @param {Function} onLoad - Executed when the loading process has been finished.
  24590. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  24591. * @param {onErrorCallback} onError - Executed when errors occur.
  24592. */
  24593. load( /* url, onLoad, onProgress, onError */ ) {}
  24594. /**
  24595. * A async version of {@link Loader#load}.
  24596. *
  24597. * @param {string} url - The path/URL of the file to be loaded.
  24598. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  24599. * @return {Promise} A Promise that resolves when the asset has been loaded.
  24600. */
  24601. loadAsync( url, onProgress ) {
  24602. const scope = this;
  24603. return new Promise( function ( resolve, reject ) {
  24604. scope.load( url, resolve, onProgress, reject );
  24605. } );
  24606. }
  24607. /**
  24608. * This method needs to be implemented by all concrete loaders. It holds the
  24609. * logic for parsing the asset into three.js entities.
  24610. *
  24611. * @param {any} data - The data to parse.
  24612. */
  24613. parse( /* data */ ) {}
  24614. /**
  24615. * Sets the `crossOrigin` String to implement CORS for loading the URL
  24616. * from a different domain that allows CORS.
  24617. *
  24618. * @param {string} crossOrigin - The `crossOrigin` value.
  24619. * @return {Loader} A reference to this instance.
  24620. */
  24621. setCrossOrigin( crossOrigin ) {
  24622. this.crossOrigin = crossOrigin;
  24623. return this;
  24624. }
  24625. /**
  24626. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  24627. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  24628. *
  24629. * Note: This setting has no effect if you are loading files locally or from the same domain.
  24630. *
  24631. * @param {boolean} value - The `withCredentials` value.
  24632. * @return {Loader} A reference to this instance.
  24633. */
  24634. setWithCredentials( value ) {
  24635. this.withCredentials = value;
  24636. return this;
  24637. }
  24638. /**
  24639. * Sets the base path for the asset.
  24640. *
  24641. * @param {string} path - The base path.
  24642. * @return {Loader} A reference to this instance.
  24643. */
  24644. setPath( path ) {
  24645. this.path = path;
  24646. return this;
  24647. }
  24648. /**
  24649. * Sets the base path for dependent resources like textures.
  24650. *
  24651. * @param {string} resourcePath - The resource path.
  24652. * @return {Loader} A reference to this instance.
  24653. */
  24654. setResourcePath( resourcePath ) {
  24655. this.resourcePath = resourcePath;
  24656. return this;
  24657. }
  24658. /**
  24659. * Sets the given request header.
  24660. *
  24661. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  24662. * for configuring the HTTP request.
  24663. * @return {Loader} A reference to this instance.
  24664. */
  24665. setRequestHeader( requestHeader ) {
  24666. this.requestHeader = requestHeader;
  24667. return this;
  24668. }
  24669. }
  24670. /**
  24671. * Callback for onProgress in loaders.
  24672. *
  24673. *
  24674. * @callback onProgressCallback
  24675. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  24676. */
  24677. /**
  24678. * Callback for onError in loaders.
  24679. *
  24680. *
  24681. * @callback onErrorCallback
  24682. * @param {Error} error - The error which occurred during the loading process.
  24683. */
  24684. /**
  24685. * The default material name that is used by loaders
  24686. * when creating materials for loaded 3D objects.
  24687. *
  24688. * Note: Not all loaders might honor this setting.
  24689. *
  24690. * @static
  24691. * @type {string}
  24692. * @default '__DEFAULT'
  24693. */
  24694. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  24695. const loading = {};
  24696. class HttpError extends Error {
  24697. constructor( message, response ) {
  24698. super( message );
  24699. this.response = response;
  24700. }
  24701. }
  24702. class FileLoader extends Loader {
  24703. constructor( manager ) {
  24704. super( manager );
  24705. }
  24706. load( url, onLoad, onProgress, onError ) {
  24707. if ( url === undefined ) url = '';
  24708. if ( this.path !== undefined ) url = this.path + url;
  24709. url = this.manager.resolveURL( url );
  24710. const cached = Cache.get( url );
  24711. if ( cached !== undefined ) {
  24712. this.manager.itemStart( url );
  24713. setTimeout( () => {
  24714. if ( onLoad ) onLoad( cached );
  24715. this.manager.itemEnd( url );
  24716. }, 0 );
  24717. return cached;
  24718. }
  24719. // Check if request is duplicate
  24720. if ( loading[ url ] !== undefined ) {
  24721. loading[ url ].push( {
  24722. onLoad: onLoad,
  24723. onProgress: onProgress,
  24724. onError: onError
  24725. } );
  24726. return;
  24727. }
  24728. // Initialise array for duplicate requests
  24729. loading[ url ] = [];
  24730. loading[ url ].push( {
  24731. onLoad: onLoad,
  24732. onProgress: onProgress,
  24733. onError: onError,
  24734. } );
  24735. // create request
  24736. const req = new Request( url, {
  24737. headers: new Headers( this.requestHeader ),
  24738. credentials: this.withCredentials ? 'include' : 'same-origin',
  24739. // An abort controller could be added within a future PR
  24740. } );
  24741. // record states ( avoid data race )
  24742. const mimeType = this.mimeType;
  24743. const responseType = this.responseType;
  24744. // start the fetch
  24745. fetch( req )
  24746. .then( response => {
  24747. if ( response.status === 200 || response.status === 0 ) {
  24748. // Some browsers return HTTP Status 0 when using non-http protocol
  24749. // e.g. 'file://' or 'data://'. Handle as success.
  24750. if ( response.status === 0 ) {
  24751. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24752. }
  24753. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24754. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  24755. return response;
  24756. }
  24757. const callbacks = loading[ url ];
  24758. const reader = response.body.getReader();
  24759. // Nginx needs X-File-Size check
  24760. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24761. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  24762. const total = contentLength ? parseInt( contentLength ) : 0;
  24763. const lengthComputable = total !== 0;
  24764. let loaded = 0;
  24765. // periodically read data into the new stream tracking while download progress
  24766. const stream = new ReadableStream( {
  24767. start( controller ) {
  24768. readData();
  24769. function readData() {
  24770. reader.read().then( ( { done, value } ) => {
  24771. if ( done ) {
  24772. controller.close();
  24773. } else {
  24774. loaded += value.byteLength;
  24775. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  24776. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24777. const callback = callbacks[ i ];
  24778. if ( callback.onProgress ) callback.onProgress( event );
  24779. }
  24780. controller.enqueue( value );
  24781. readData();
  24782. }
  24783. }, ( e ) => {
  24784. controller.error( e );
  24785. } );
  24786. }
  24787. }
  24788. } );
  24789. return new Response( stream );
  24790. } else {
  24791. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  24792. }
  24793. } )
  24794. .then( response => {
  24795. switch ( responseType ) {
  24796. case 'arraybuffer':
  24797. return response.arrayBuffer();
  24798. case 'blob':
  24799. return response.blob();
  24800. case 'document':
  24801. return response.text()
  24802. .then( text => {
  24803. const parser = new DOMParser();
  24804. return parser.parseFromString( text, mimeType );
  24805. } );
  24806. case 'json':
  24807. return response.json();
  24808. default:
  24809. if ( mimeType === undefined ) {
  24810. return response.text();
  24811. } else {
  24812. // sniff encoding
  24813. const re = /charset="?([^;"\s]*)"?/i;
  24814. const exec = re.exec( mimeType );
  24815. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  24816. const decoder = new TextDecoder( label );
  24817. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  24818. }
  24819. }
  24820. } )
  24821. .then( data => {
  24822. // Add to cache only on HTTP success, so that we do not cache
  24823. // error response bodies as proper responses to requests.
  24824. Cache.add( url, data );
  24825. const callbacks = loading[ url ];
  24826. delete loading[ url ];
  24827. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24828. const callback = callbacks[ i ];
  24829. if ( callback.onLoad ) callback.onLoad( data );
  24830. }
  24831. } )
  24832. .catch( err => {
  24833. // Abort errors and other errors are handled the same
  24834. const callbacks = loading[ url ];
  24835. if ( callbacks === undefined ) {
  24836. // When onLoad was called and url was deleted in `loading`
  24837. this.manager.itemError( url );
  24838. throw err;
  24839. }
  24840. delete loading[ url ];
  24841. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24842. const callback = callbacks[ i ];
  24843. if ( callback.onError ) callback.onError( err );
  24844. }
  24845. this.manager.itemError( url );
  24846. } )
  24847. .finally( () => {
  24848. this.manager.itemEnd( url );
  24849. } );
  24850. this.manager.itemStart( url );
  24851. }
  24852. setResponseType( value ) {
  24853. this.responseType = value;
  24854. return this;
  24855. }
  24856. setMimeType( value ) {
  24857. this.mimeType = value;
  24858. return this;
  24859. }
  24860. }
  24861. class AnimationLoader extends Loader {
  24862. constructor( manager ) {
  24863. super( manager );
  24864. }
  24865. load( url, onLoad, onProgress, onError ) {
  24866. const scope = this;
  24867. const loader = new FileLoader( this.manager );
  24868. loader.setPath( this.path );
  24869. loader.setRequestHeader( this.requestHeader );
  24870. loader.setWithCredentials( this.withCredentials );
  24871. loader.load( url, function ( text ) {
  24872. try {
  24873. onLoad( scope.parse( JSON.parse( text ) ) );
  24874. } catch ( e ) {
  24875. if ( onError ) {
  24876. onError( e );
  24877. } else {
  24878. console.error( e );
  24879. }
  24880. scope.manager.itemError( url );
  24881. }
  24882. }, onProgress, onError );
  24883. }
  24884. parse( json ) {
  24885. const animations = [];
  24886. for ( let i = 0; i < json.length; i ++ ) {
  24887. const clip = AnimationClip.parse( json[ i ] );
  24888. animations.push( clip );
  24889. }
  24890. return animations;
  24891. }
  24892. }
  24893. /**
  24894. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24895. *
  24896. * Sub classes have to implement the parse() method which will be used in load().
  24897. */
  24898. class CompressedTextureLoader extends Loader {
  24899. constructor( manager ) {
  24900. super( manager );
  24901. }
  24902. load( url, onLoad, onProgress, onError ) {
  24903. const scope = this;
  24904. const images = [];
  24905. const texture = new CompressedTexture();
  24906. const loader = new FileLoader( this.manager );
  24907. loader.setPath( this.path );
  24908. loader.setResponseType( 'arraybuffer' );
  24909. loader.setRequestHeader( this.requestHeader );
  24910. loader.setWithCredentials( scope.withCredentials );
  24911. let loaded = 0;
  24912. function loadTexture( i ) {
  24913. loader.load( url[ i ], function ( buffer ) {
  24914. const texDatas = scope.parse( buffer, true );
  24915. images[ i ] = {
  24916. width: texDatas.width,
  24917. height: texDatas.height,
  24918. format: texDatas.format,
  24919. mipmaps: texDatas.mipmaps
  24920. };
  24921. loaded += 1;
  24922. if ( loaded === 6 ) {
  24923. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24924. texture.image = images;
  24925. texture.format = texDatas.format;
  24926. texture.needsUpdate = true;
  24927. if ( onLoad ) onLoad( texture );
  24928. }
  24929. }, onProgress, onError );
  24930. }
  24931. if ( Array.isArray( url ) ) {
  24932. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24933. loadTexture( i );
  24934. }
  24935. } else {
  24936. // compressed cubemap texture stored in a single DDS file
  24937. loader.load( url, function ( buffer ) {
  24938. const texDatas = scope.parse( buffer, true );
  24939. if ( texDatas.isCubemap ) {
  24940. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24941. for ( let f = 0; f < faces; f ++ ) {
  24942. images[ f ] = { mipmaps: [] };
  24943. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24944. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24945. images[ f ].format = texDatas.format;
  24946. images[ f ].width = texDatas.width;
  24947. images[ f ].height = texDatas.height;
  24948. }
  24949. }
  24950. texture.image = images;
  24951. } else {
  24952. texture.image.width = texDatas.width;
  24953. texture.image.height = texDatas.height;
  24954. texture.mipmaps = texDatas.mipmaps;
  24955. }
  24956. if ( texDatas.mipmapCount === 1 ) {
  24957. texture.minFilter = LinearFilter;
  24958. }
  24959. texture.format = texDatas.format;
  24960. texture.needsUpdate = true;
  24961. if ( onLoad ) onLoad( texture );
  24962. }, onProgress, onError );
  24963. }
  24964. return texture;
  24965. }
  24966. }
  24967. class ImageLoader extends Loader {
  24968. constructor( manager ) {
  24969. super( manager );
  24970. }
  24971. load( url, onLoad, onProgress, onError ) {
  24972. if ( this.path !== undefined ) url = this.path + url;
  24973. url = this.manager.resolveURL( url );
  24974. const scope = this;
  24975. const cached = Cache.get( url );
  24976. if ( cached !== undefined ) {
  24977. scope.manager.itemStart( url );
  24978. setTimeout( function () {
  24979. if ( onLoad ) onLoad( cached );
  24980. scope.manager.itemEnd( url );
  24981. }, 0 );
  24982. return cached;
  24983. }
  24984. const image = createElementNS( 'img' );
  24985. function onImageLoad() {
  24986. removeEventListeners();
  24987. Cache.add( url, this );
  24988. if ( onLoad ) onLoad( this );
  24989. scope.manager.itemEnd( url );
  24990. }
  24991. function onImageError( event ) {
  24992. removeEventListeners();
  24993. if ( onError ) onError( event );
  24994. scope.manager.itemError( url );
  24995. scope.manager.itemEnd( url );
  24996. }
  24997. function removeEventListeners() {
  24998. image.removeEventListener( 'load', onImageLoad, false );
  24999. image.removeEventListener( 'error', onImageError, false );
  25000. }
  25001. image.addEventListener( 'load', onImageLoad, false );
  25002. image.addEventListener( 'error', onImageError, false );
  25003. if ( url.slice( 0, 5 ) !== 'data:' ) {
  25004. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  25005. }
  25006. scope.manager.itemStart( url );
  25007. image.src = url;
  25008. return image;
  25009. }
  25010. }
  25011. class CubeTextureLoader extends Loader {
  25012. constructor( manager ) {
  25013. super( manager );
  25014. }
  25015. load( urls, onLoad, onProgress, onError ) {
  25016. const texture = new CubeTexture();
  25017. texture.colorSpace = SRGBColorSpace;
  25018. const loader = new ImageLoader( this.manager );
  25019. loader.setCrossOrigin( this.crossOrigin );
  25020. loader.setPath( this.path );
  25021. let loaded = 0;
  25022. function loadTexture( i ) {
  25023. loader.load( urls[ i ], function ( image ) {
  25024. texture.images[ i ] = image;
  25025. loaded ++;
  25026. if ( loaded === 6 ) {
  25027. texture.needsUpdate = true;
  25028. if ( onLoad ) onLoad( texture );
  25029. }
  25030. }, undefined, onError );
  25031. }
  25032. for ( let i = 0; i < urls.length; ++ i ) {
  25033. loadTexture( i );
  25034. }
  25035. return texture;
  25036. }
  25037. }
  25038. /**
  25039. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  25040. *
  25041. * Sub classes have to implement the parse() method which will be used in load().
  25042. */
  25043. class DataTextureLoader extends Loader {
  25044. constructor( manager ) {
  25045. super( manager );
  25046. }
  25047. load( url, onLoad, onProgress, onError ) {
  25048. const scope = this;
  25049. const texture = new DataTexture();
  25050. const loader = new FileLoader( this.manager );
  25051. loader.setResponseType( 'arraybuffer' );
  25052. loader.setRequestHeader( this.requestHeader );
  25053. loader.setPath( this.path );
  25054. loader.setWithCredentials( scope.withCredentials );
  25055. loader.load( url, function ( buffer ) {
  25056. let texData;
  25057. try {
  25058. texData = scope.parse( buffer );
  25059. } catch ( error ) {
  25060. if ( onError !== undefined ) {
  25061. onError( error );
  25062. } else {
  25063. console.error( error );
  25064. return;
  25065. }
  25066. }
  25067. if ( texData.image !== undefined ) {
  25068. texture.image = texData.image;
  25069. } else if ( texData.data !== undefined ) {
  25070. texture.image.width = texData.width;
  25071. texture.image.height = texData.height;
  25072. texture.image.data = texData.data;
  25073. }
  25074. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  25075. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  25076. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  25077. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  25078. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  25079. if ( texData.colorSpace !== undefined ) {
  25080. texture.colorSpace = texData.colorSpace;
  25081. }
  25082. if ( texData.flipY !== undefined ) {
  25083. texture.flipY = texData.flipY;
  25084. }
  25085. if ( texData.format !== undefined ) {
  25086. texture.format = texData.format;
  25087. }
  25088. if ( texData.type !== undefined ) {
  25089. texture.type = texData.type;
  25090. }
  25091. if ( texData.mipmaps !== undefined ) {
  25092. texture.mipmaps = texData.mipmaps;
  25093. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  25094. }
  25095. if ( texData.mipmapCount === 1 ) {
  25096. texture.minFilter = LinearFilter;
  25097. }
  25098. if ( texData.generateMipmaps !== undefined ) {
  25099. texture.generateMipmaps = texData.generateMipmaps;
  25100. }
  25101. texture.needsUpdate = true;
  25102. if ( onLoad ) onLoad( texture, texData );
  25103. }, onProgress, onError );
  25104. return texture;
  25105. }
  25106. }
  25107. class TextureLoader extends Loader {
  25108. constructor( manager ) {
  25109. super( manager );
  25110. }
  25111. load( url, onLoad, onProgress, onError ) {
  25112. const texture = new Texture();
  25113. const loader = new ImageLoader( this.manager );
  25114. loader.setCrossOrigin( this.crossOrigin );
  25115. loader.setPath( this.path );
  25116. loader.load( url, function ( image ) {
  25117. texture.image = image;
  25118. texture.needsUpdate = true;
  25119. if ( onLoad !== undefined ) {
  25120. onLoad( texture );
  25121. }
  25122. }, onProgress, onError );
  25123. return texture;
  25124. }
  25125. }
  25126. /**
  25127. * Abstract base class for lights - all other light types inherit the
  25128. * properties and methods described here.
  25129. *
  25130. * @abstract
  25131. * @augments Object3D
  25132. */
  25133. class Light extends Object3D {
  25134. /**
  25135. * Constructs a new light.
  25136. *
  25137. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  25138. * @param {number} [intensity=1] - The light's strength/intensity.
  25139. */
  25140. constructor( color, intensity = 1 ) {
  25141. super();
  25142. /**
  25143. * This flag can be used for type testing.
  25144. *
  25145. * @type {boolean}
  25146. * @readonly
  25147. * @default true
  25148. */
  25149. this.isLight = true;
  25150. this.type = 'Light';
  25151. /**
  25152. * The light's color.
  25153. *
  25154. * @type {Color}
  25155. */
  25156. this.color = new Color( color );
  25157. /**
  25158. * The light's intensity.
  25159. *
  25160. * @type {number}
  25161. * @default 1
  25162. */
  25163. this.intensity = intensity;
  25164. }
  25165. /**
  25166. * Frees the GPU-related resources allocated by this instance. Call this
  25167. * method whenever this instance is no longer used in your app.
  25168. */
  25169. dispose() {
  25170. // Empty here in base class; some subclasses override.
  25171. }
  25172. copy( source, recursive ) {
  25173. super.copy( source, recursive );
  25174. this.color.copy( source.color );
  25175. this.intensity = source.intensity;
  25176. return this;
  25177. }
  25178. toJSON( meta ) {
  25179. const data = super.toJSON( meta );
  25180. data.object.color = this.color.getHex();
  25181. data.object.intensity = this.intensity;
  25182. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  25183. if ( this.distance !== undefined ) data.object.distance = this.distance;
  25184. if ( this.angle !== undefined ) data.object.angle = this.angle;
  25185. if ( this.decay !== undefined ) data.object.decay = this.decay;
  25186. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  25187. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  25188. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  25189. return data;
  25190. }
  25191. }
  25192. /**
  25193. * A light source positioned directly above the scene, with color fading from
  25194. * the sky color to the ground color.
  25195. *
  25196. * This light cannot be used to cast shadows.
  25197. *
  25198. * ```js
  25199. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  25200. * scene.add( light );
  25201. * ```
  25202. *
  25203. * @augments Light
  25204. */
  25205. class HemisphereLight extends Light {
  25206. /**
  25207. * Constructs a new hemisphere light.
  25208. *
  25209. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  25210. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  25211. * @param {number} [intensity=1] - The light's strength/intensity.
  25212. */
  25213. constructor( skyColor, groundColor, intensity ) {
  25214. super( skyColor, intensity );
  25215. /**
  25216. * This flag can be used for type testing.
  25217. *
  25218. * @type {boolean}
  25219. * @readonly
  25220. * @default true
  25221. */
  25222. this.isHemisphereLight = true;
  25223. this.type = 'HemisphereLight';
  25224. this.position.copy( Object3D.DEFAULT_UP );
  25225. this.updateMatrix();
  25226. /**
  25227. * The light's ground color.
  25228. *
  25229. * @type {Color}
  25230. */
  25231. this.groundColor = new Color( groundColor );
  25232. }
  25233. copy( source, recursive ) {
  25234. super.copy( source, recursive );
  25235. this.groundColor.copy( source.groundColor );
  25236. return this;
  25237. }
  25238. }
  25239. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  25240. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  25241. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  25242. /**
  25243. * Abstract base class for light shadow classes. These classes
  25244. * represent the shadow configuration for different ligth types.
  25245. *
  25246. * @abstract
  25247. */
  25248. class LightShadow {
  25249. /**
  25250. * Constructs a new light shadow.
  25251. *
  25252. * @param {Camera} camera - The light's view of the world.
  25253. */
  25254. constructor( camera ) {
  25255. /**
  25256. * The light's view of the world.
  25257. *
  25258. * @type {Camera}
  25259. */
  25260. this.camera = camera;
  25261. /**
  25262. * The intensity of the shadow. The default is `1`.
  25263. * Valid values are in the range `[0, 1]`.
  25264. *
  25265. * @type {number}
  25266. * @default 1
  25267. */
  25268. this.intensity = 1;
  25269. /**
  25270. * Shadow map bias, how much to add or subtract from the normalized depth
  25271. * when deciding whether a surface is in shadow.
  25272. *
  25273. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  25274. * may help reduce artifacts in shadows.
  25275. *
  25276. * @type {number}
  25277. * @default 0
  25278. */
  25279. this.bias = 0;
  25280. /**
  25281. * Defines how much the position used to query the shadow map is offset along
  25282. * the object normal. The default is `0`. Increasing this value can be used to
  25283. * reduce shadow acne especially in large scenes where light shines onto
  25284. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  25285. *
  25286. * @type {number}
  25287. * @default 0
  25288. */
  25289. this.normalBias = 0;
  25290. /**
  25291. * Setting this to values greater than 1 will blur the edges of the shadow.
  25292. * High values will cause unwanted banding effects in the shadows - a greater
  25293. * map size will allow for a higher value to be used here before these effects
  25294. * become visible.
  25295. *
  25296. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  25297. * and it is recommended to increase softness by decreasing the shadow map size instead.
  25298. *
  25299. * The property has no effect when the shadow map type is `BasicShadowMap`.
  25300. *
  25301. * @type {number}
  25302. * @default 1
  25303. */
  25304. this.radius = 1;
  25305. /**
  25306. * The amount of samples to use when blurring a VSM shadow map.
  25307. *
  25308. * @type {number}
  25309. * @default 8
  25310. */
  25311. this.blurSamples = 8;
  25312. /**
  25313. * Defines the width and height of the shadow map. Higher values give better quality
  25314. * shadows at the cost of computation time. Values must be powers of two.
  25315. *
  25316. * @type {Vector2}
  25317. * @default (512,512)
  25318. */
  25319. this.mapSize = new Vector2( 512, 512 );
  25320. /**
  25321. * The depth map generated using the internal camera; a location beyond a
  25322. * pixel's depth is in shadow. Computed internally during rendering.
  25323. *
  25324. * @type {?RenderTarget}
  25325. * @default null
  25326. */
  25327. this.map = null;
  25328. /**
  25329. * The distribution map generated using the internal camera; an occlusion is
  25330. * calculated based on the distribution of depths. Computed internally during
  25331. * rendering.
  25332. *
  25333. * @type {?RenderTarget}
  25334. * @default null
  25335. */
  25336. this.mapPass = null;
  25337. /**
  25338. * Model to shadow camera space, to compute location and depth in shadow map.
  25339. * This is computed internally during rendering.
  25340. *
  25341. * @type {Matrix4}
  25342. */
  25343. this.matrix = new Matrix4();
  25344. /**
  25345. * Enables automatic updates of the light's shadow. If you do not require dynamic
  25346. * lighting / shadows, you may set this to `false`.
  25347. *
  25348. * @type {boolean}
  25349. * @default true
  25350. */
  25351. this.autoUpdate = true;
  25352. /**
  25353. * When set to `true`, shadow maps will be updated in the next `render` call.
  25354. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  25355. * set this property to `true` and then make a render call to update the light's shadow.
  25356. *
  25357. * @type {boolean}
  25358. * @default false
  25359. */
  25360. this.needsUpdate = false;
  25361. this._frustum = new Frustum();
  25362. this._frameExtents = new Vector2( 1, 1 );
  25363. this._viewportCount = 1;
  25364. this._viewports = [
  25365. new Vector4( 0, 0, 1, 1 )
  25366. ];
  25367. }
  25368. /**
  25369. * Used internally by the renderer to get the number of viewports that need
  25370. * to be rendered for this shadow.
  25371. *
  25372. * @return {number} The viewport count.
  25373. */
  25374. getViewportCount() {
  25375. return this._viewportCount;
  25376. }
  25377. /**
  25378. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  25379. *
  25380. * @return {Frustum} The shadow camera frustum.
  25381. */
  25382. getFrustum() {
  25383. return this._frustum;
  25384. }
  25385. /**
  25386. * Update the matrices for the camera and shadow, used internally by the renderer.
  25387. *
  25388. * @param {Light} light - The light for which the shadow is being rendered.
  25389. */
  25390. updateMatrices( light ) {
  25391. const shadowCamera = this.camera;
  25392. const shadowMatrix = this.matrix;
  25393. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  25394. shadowCamera.position.copy( _lightPositionWorld$1 );
  25395. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  25396. shadowCamera.lookAt( _lookTarget$1 );
  25397. shadowCamera.updateMatrixWorld();
  25398. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  25399. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  25400. shadowMatrix.set(
  25401. 0.5, 0.0, 0.0, 0.5,
  25402. 0.0, 0.5, 0.0, 0.5,
  25403. 0.0, 0.0, 0.5, 0.5,
  25404. 0.0, 0.0, 0.0, 1.0
  25405. );
  25406. shadowMatrix.multiply( _projScreenMatrix$1 );
  25407. }
  25408. /**
  25409. * Returns a viewport definition for the given viewport index.
  25410. *
  25411. * @param {number} viewportIndex - The viewport index.
  25412. * @return {Vector4} The viewport.
  25413. */
  25414. getViewport( viewportIndex ) {
  25415. return this._viewports[ viewportIndex ];
  25416. }
  25417. /**
  25418. * Returns the frame extends.
  25419. *
  25420. * @return {Vector2} The frame extends.
  25421. */
  25422. getFrameExtents() {
  25423. return this._frameExtents;
  25424. }
  25425. /**
  25426. * Frees the GPU-related resources allocated by this instance. Call this
  25427. * method whenever this instance is no longer used in your app.
  25428. */
  25429. dispose() {
  25430. if ( this.map ) {
  25431. this.map.dispose();
  25432. }
  25433. if ( this.mapPass ) {
  25434. this.mapPass.dispose();
  25435. }
  25436. }
  25437. /**
  25438. * Copies the values of the given light shadow instance to this instance.
  25439. *
  25440. * @param {LightShadow} source - The light shadow to copy.
  25441. * @return {LightShadow} A reference to this light shadow instance.
  25442. */
  25443. copy( source ) {
  25444. this.camera = source.camera.clone();
  25445. this.intensity = source.intensity;
  25446. this.bias = source.bias;
  25447. this.radius = source.radius;
  25448. this.mapSize.copy( source.mapSize );
  25449. return this;
  25450. }
  25451. /**
  25452. * Returns a new light shadow instance with copied values from this instance.
  25453. *
  25454. * @return {LightShadow} A clone of this instance.
  25455. */
  25456. clone() {
  25457. return new this.constructor().copy( this );
  25458. }
  25459. /**
  25460. * Serializes the light shadow into JSON.
  25461. *
  25462. * @return {Object} A JSON object representing the serialized light shadow.
  25463. * @see {@link ObjectLoader#parse}
  25464. */
  25465. toJSON() {
  25466. const object = {};
  25467. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  25468. if ( this.bias !== 0 ) object.bias = this.bias;
  25469. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  25470. if ( this.radius !== 1 ) object.radius = this.radius;
  25471. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  25472. object.camera = this.camera.toJSON( false ).object;
  25473. delete object.camera.matrix;
  25474. return object;
  25475. }
  25476. }
  25477. /**
  25478. * Represents the shadow configuration of directional lights.
  25479. *
  25480. * @augments LightShadow
  25481. */
  25482. class SpotLightShadow extends LightShadow {
  25483. /**
  25484. * Constructs a new spot light shadow.
  25485. */
  25486. constructor() {
  25487. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  25488. /**
  25489. * This flag can be used for type testing.
  25490. *
  25491. * @type {boolean}
  25492. * @readonly
  25493. * @default true
  25494. */
  25495. this.isSpotLightShadow = true;
  25496. /**
  25497. * Used to focus the shadow camera. The camera's field of view is set as a
  25498. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  25499. *
  25500. * @type {number}
  25501. * @default 1
  25502. */
  25503. this.focus = 1;
  25504. }
  25505. updateMatrices( light ) {
  25506. const camera = this.camera;
  25507. const fov = RAD2DEG * 2 * light.angle * this.focus;
  25508. const aspect = this.mapSize.width / this.mapSize.height;
  25509. const far = light.distance || camera.far;
  25510. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  25511. camera.fov = fov;
  25512. camera.aspect = aspect;
  25513. camera.far = far;
  25514. camera.updateProjectionMatrix();
  25515. }
  25516. super.updateMatrices( light );
  25517. }
  25518. copy( source ) {
  25519. super.copy( source );
  25520. this.focus = source.focus;
  25521. return this;
  25522. }
  25523. }
  25524. /**
  25525. * This light gets emitted from a single point in one direction, along a cone
  25526. * that increases in size the further from the light it gets.
  25527. *
  25528. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  25529. *
  25530. * ```js
  25531. * // white spotlight shining from the side, modulated by a texture
  25532. * const spotLight = new THREE.SpotLight( 0xffffff );
  25533. * spotLight.position.set( 100, 1000, 100 );
  25534. * spotLight.map = new THREE.TextureLoader().load( url );
  25535. *
  25536. * spotLight.castShadow = true;
  25537. * spotLight.shadow.mapSize.width = 1024;
  25538. * spotLight.shadow.mapSize.height = 1024;
  25539. * spotLight.shadow.camera.near = 500;
  25540. * spotLight.shadow.camera.far = 4000;
  25541. * spotLight.shadow.camera.fov = 30;s
  25542. * ```
  25543. *
  25544. * @augments Light
  25545. */
  25546. class SpotLight extends Light {
  25547. /**
  25548. * Constructs a new spot light.
  25549. *
  25550. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  25551. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  25552. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  25553. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  25554. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  25555. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  25556. */
  25557. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  25558. super( color, intensity );
  25559. /**
  25560. * This flag can be used for type testing.
  25561. *
  25562. * @type {boolean}
  25563. * @readonly
  25564. * @default true
  25565. */
  25566. this.isSpotLight = true;
  25567. this.type = 'SpotLight';
  25568. this.position.copy( Object3D.DEFAULT_UP );
  25569. this.updateMatrix();
  25570. /**
  25571. * The spot light points from its position to the
  25572. * target's position.
  25573. *
  25574. * For the target's position to be changed to anything other
  25575. * than the default, it must be added to the scene.
  25576. *
  25577. * It is also possible to set the target to be another 3D object
  25578. * in the scene. The light will now track the target object.
  25579. *
  25580. * @type {Object3D}
  25581. */
  25582. this.target = new Object3D();
  25583. /**
  25584. * Maximum range of the light. `0` means no limit.
  25585. *
  25586. * @type {number}
  25587. * @default 0
  25588. */
  25589. this.distance = distance;
  25590. /**
  25591. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  25592. *
  25593. * @type {number}
  25594. * @default Math.PI/3
  25595. */
  25596. this.angle = angle;
  25597. /**
  25598. * Percent of the spotlight cone that is attenuated due to penumbra.
  25599. * Value range is `[0,1]`.
  25600. *
  25601. * @type {number}
  25602. * @default 0
  25603. */
  25604. this.penumbra = penumbra;
  25605. /**
  25606. * The amount the light dims along the distance of the light. In context of
  25607. * physically-correct rendering the default value should not be changed.
  25608. *
  25609. * @type {number}
  25610. * @default 2
  25611. */
  25612. this.decay = decay;
  25613. /**
  25614. * A texture used to modulate the color of the light. The spot light
  25615. * color is mixed with the RGB value of this texture, with a ratio
  25616. * corresponding to its alpha value. The cookie-like masking effect is
  25617. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  25618. *
  25619. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  25620. *
  25621. * @type {?Texture}
  25622. * @default null
  25623. */
  25624. this.map = null;
  25625. /**
  25626. * This property holds the light's shadow configuration.
  25627. *
  25628. * @type {SpotLightShadow}
  25629. */
  25630. this.shadow = new SpotLightShadow();
  25631. }
  25632. /**
  25633. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  25634. * Changing the power will also change the light's intensity.
  25635. *
  25636. * @type {number}
  25637. */
  25638. get power() {
  25639. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25640. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  25641. return this.intensity * Math.PI;
  25642. }
  25643. set power( power ) {
  25644. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25645. this.intensity = power / Math.PI;
  25646. }
  25647. dispose() {
  25648. this.shadow.dispose();
  25649. }
  25650. copy( source, recursive ) {
  25651. super.copy( source, recursive );
  25652. this.distance = source.distance;
  25653. this.angle = source.angle;
  25654. this.penumbra = source.penumbra;
  25655. this.decay = source.decay;
  25656. this.target = source.target.clone();
  25657. this.shadow = source.shadow.clone();
  25658. return this;
  25659. }
  25660. }
  25661. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  25662. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  25663. const _lookTarget = /*@__PURE__*/ new Vector3();
  25664. /**
  25665. * Represents the shadow configuration of point lights.
  25666. *
  25667. * @augments LightShadow
  25668. */
  25669. class PointLightShadow extends LightShadow {
  25670. /**
  25671. * Constructs a new point light shadow.
  25672. */
  25673. constructor() {
  25674. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  25675. /**
  25676. * This flag can be used for type testing.
  25677. *
  25678. * @type {boolean}
  25679. * @readonly
  25680. * @default true
  25681. */
  25682. this.isPointLightShadow = true;
  25683. this._frameExtents = new Vector2( 4, 2 );
  25684. this._viewportCount = 6;
  25685. this._viewports = [
  25686. // These viewports map a cube-map onto a 2D texture with the
  25687. // following orientation:
  25688. //
  25689. // xzXZ
  25690. // y Y
  25691. //
  25692. // X - Positive x direction
  25693. // x - Negative x direction
  25694. // Y - Positive y direction
  25695. // y - Negative y direction
  25696. // Z - Positive z direction
  25697. // z - Negative z direction
  25698. // positive X
  25699. new Vector4( 2, 1, 1, 1 ),
  25700. // negative X
  25701. new Vector4( 0, 1, 1, 1 ),
  25702. // positive Z
  25703. new Vector4( 3, 1, 1, 1 ),
  25704. // negative Z
  25705. new Vector4( 1, 1, 1, 1 ),
  25706. // positive Y
  25707. new Vector4( 3, 0, 1, 1 ),
  25708. // negative Y
  25709. new Vector4( 1, 0, 1, 1 )
  25710. ];
  25711. this._cubeDirections = [
  25712. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  25713. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  25714. ];
  25715. this._cubeUps = [
  25716. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  25717. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  25718. ];
  25719. }
  25720. /**
  25721. * Update the matrices for the camera and shadow, used internally by the renderer.
  25722. *
  25723. * @param {Light} light - The light for which the shadow is being rendered.
  25724. * @param {number} [viewportIndex=0] - The viewport index.
  25725. */
  25726. updateMatrices( light, viewportIndex = 0 ) {
  25727. const camera = this.camera;
  25728. const shadowMatrix = this.matrix;
  25729. const far = light.distance || camera.far;
  25730. if ( far !== camera.far ) {
  25731. camera.far = far;
  25732. camera.updateProjectionMatrix();
  25733. }
  25734. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  25735. camera.position.copy( _lightPositionWorld );
  25736. _lookTarget.copy( camera.position );
  25737. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  25738. camera.up.copy( this._cubeUps[ viewportIndex ] );
  25739. camera.lookAt( _lookTarget );
  25740. camera.updateMatrixWorld();
  25741. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  25742. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  25743. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  25744. }
  25745. }
  25746. /**
  25747. * A light that gets emitted from a single point in all directions. A common
  25748. * use case for this is to replicate the light emitted from a bare
  25749. * lightbulb.
  25750. *
  25751. * This light can cast shadows - see the {@link PointLightShadow} for details.
  25752. *
  25753. * ```js
  25754. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  25755. * light.position.set( 50, 50, 50 );
  25756. * scene.add( light );
  25757. * ```
  25758. *
  25759. * @augments Light
  25760. */
  25761. class PointLight extends Light {
  25762. /**
  25763. * Constructs a new point light.
  25764. *
  25765. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  25766. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  25767. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  25768. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  25769. */
  25770. constructor( color, intensity, distance = 0, decay = 2 ) {
  25771. super( color, intensity );
  25772. /**
  25773. * This flag can be used for type testing.
  25774. *
  25775. * @type {boolean}
  25776. * @readonly
  25777. * @default true
  25778. */
  25779. this.isPointLight = true;
  25780. this.type = 'PointLight';
  25781. /**
  25782. * When distance is zero, light will attenuate according to inverse-square
  25783. * law to infinite distance. When distance is non-zero, light will attenuate
  25784. * according to inverse-square law until near the distance cutoff, where it
  25785. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  25786. * physically correct.
  25787. *
  25788. * @type {number}
  25789. * @default 0
  25790. */
  25791. this.distance = distance;
  25792. /**
  25793. * The amount the light dims along the distance of the light. In context of
  25794. * physically-correct rendering the default value should not be changed.
  25795. *
  25796. * @type {number}
  25797. * @default 2
  25798. */
  25799. this.decay = decay;
  25800. /**
  25801. * This property holds the light's shadow configuration.
  25802. *
  25803. * @type {PointLightShadow}
  25804. */
  25805. this.shadow = new PointLightShadow();
  25806. }
  25807. /**
  25808. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  25809. * Changing the power will also change the light's intensity.
  25810. *
  25811. * @type {number}
  25812. */
  25813. get power() {
  25814. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25815. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  25816. return this.intensity * 4 * Math.PI;
  25817. }
  25818. set power( power ) {
  25819. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25820. this.intensity = power / ( 4 * Math.PI );
  25821. }
  25822. dispose() {
  25823. this.shadow.dispose();
  25824. }
  25825. copy( source, recursive ) {
  25826. super.copy( source, recursive );
  25827. this.distance = source.distance;
  25828. this.decay = source.decay;
  25829. this.shadow = source.shadow.clone();
  25830. return this;
  25831. }
  25832. }
  25833. /**
  25834. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  25835. *
  25836. * In this projection mode, an object's size in the rendered image stays
  25837. * constant regardless of its distance from the camera. This can be useful
  25838. * for rendering 2D scenes and UI elements, amongst other things.
  25839. *
  25840. * ```js
  25841. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  25842. * scene.add( camera );
  25843. * ```
  25844. *
  25845. * @augments Camera
  25846. */
  25847. class OrthographicCamera extends Camera {
  25848. /**
  25849. * Constructs a new orthographic camera.
  25850. *
  25851. * @param {number} [left=-1] - The left plane of the camera's frustum.
  25852. * @param {number} [right=1] - The right plane of the camera's frustum.
  25853. * @param {number} [top=1] - The top plane of the camera's frustum.
  25854. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  25855. * @param {number} [near=0.1] - The camera's near plane.
  25856. * @param {number} [far=2000] - The camera's far plane.
  25857. */
  25858. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  25859. super();
  25860. /**
  25861. * This flag can be used for type testing.
  25862. *
  25863. * @type {boolean}
  25864. * @readonly
  25865. * @default true
  25866. */
  25867. this.isOrthographicCamera = true;
  25868. this.type = 'OrthographicCamera';
  25869. /**
  25870. * The zoom factor of the camera.
  25871. *
  25872. * @type {number}
  25873. * @default 1
  25874. */
  25875. this.zoom = 1;
  25876. /**
  25877. * Represents the frustum window specification. This property should not be edited
  25878. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  25879. *
  25880. * @type {?Object}
  25881. * @default null
  25882. */
  25883. this.view = null;
  25884. /**
  25885. * The left plane of the camera's frustum.
  25886. *
  25887. * @type {number}
  25888. * @default -1
  25889. */
  25890. this.left = left;
  25891. /**
  25892. * The right plane of the camera's frustum.
  25893. *
  25894. * @type {number}
  25895. * @default 1
  25896. */
  25897. this.right = right;
  25898. /**
  25899. * The top plane of the camera's frustum.
  25900. *
  25901. * @type {number}
  25902. * @default 1
  25903. */
  25904. this.top = top;
  25905. /**
  25906. * The bottom plane of the camera's frustum.
  25907. *
  25908. * @type {number}
  25909. * @default -1
  25910. */
  25911. this.bottom = bottom;
  25912. /**
  25913. * The camera's near plane. The valid range is greater than `0`
  25914. * and less than the current value of {@link OrthographicCamera#far}.
  25915. *
  25916. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  25917. * valid value for an orthographic camera's near plane.
  25918. *
  25919. * @type {number}
  25920. * @default 0.1
  25921. */
  25922. this.near = near;
  25923. /**
  25924. * The camera's far plane. Must be greater than the
  25925. * current value of {@link OrthographicCamera#near}.
  25926. *
  25927. * @type {number}
  25928. * @default 2000
  25929. */
  25930. this.far = far;
  25931. this.updateProjectionMatrix();
  25932. }
  25933. copy( source, recursive ) {
  25934. super.copy( source, recursive );
  25935. this.left = source.left;
  25936. this.right = source.right;
  25937. this.top = source.top;
  25938. this.bottom = source.bottom;
  25939. this.near = source.near;
  25940. this.far = source.far;
  25941. this.zoom = source.zoom;
  25942. this.view = source.view === null ? null : Object.assign( {}, source.view );
  25943. return this;
  25944. }
  25945. /**
  25946. * Sets an offset in a larger frustum. This is useful for multi-window or
  25947. * multi-monitor/multi-machine setups.
  25948. *
  25949. * @param {number} fullWidth - The full width of multiview setup.
  25950. * @param {number} fullHeight - The full height of multiview setup.
  25951. * @param {number} x - The horizontal offset of the subcamera.
  25952. * @param {number} y - The vertical offset of the subcamera.
  25953. * @param {number} width - The width of subcamera.
  25954. * @param {number} height - The height of subcamera.
  25955. * @see {@link PerspectiveCamera#setViewOffset}
  25956. */
  25957. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  25958. if ( this.view === null ) {
  25959. this.view = {
  25960. enabled: true,
  25961. fullWidth: 1,
  25962. fullHeight: 1,
  25963. offsetX: 0,
  25964. offsetY: 0,
  25965. width: 1,
  25966. height: 1
  25967. };
  25968. }
  25969. this.view.enabled = true;
  25970. this.view.fullWidth = fullWidth;
  25971. this.view.fullHeight = fullHeight;
  25972. this.view.offsetX = x;
  25973. this.view.offsetY = y;
  25974. this.view.width = width;
  25975. this.view.height = height;
  25976. this.updateProjectionMatrix();
  25977. }
  25978. /**
  25979. * Removes the view offset from the projection matrix.
  25980. */
  25981. clearViewOffset() {
  25982. if ( this.view !== null ) {
  25983. this.view.enabled = false;
  25984. }
  25985. this.updateProjectionMatrix();
  25986. }
  25987. /**
  25988. * Updates the camera's projection matrix. Must be called after any change of
  25989. * camera properties.
  25990. */
  25991. updateProjectionMatrix() {
  25992. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  25993. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  25994. const cx = ( this.right + this.left ) / 2;
  25995. const cy = ( this.top + this.bottom ) / 2;
  25996. let left = cx - dx;
  25997. let right = cx + dx;
  25998. let top = cy + dy;
  25999. let bottom = cy - dy;
  26000. if ( this.view !== null && this.view.enabled ) {
  26001. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  26002. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  26003. left += scaleW * this.view.offsetX;
  26004. right = left + scaleW * this.view.width;
  26005. top -= scaleH * this.view.offsetY;
  26006. bottom = top - scaleH * this.view.height;
  26007. }
  26008. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  26009. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  26010. }
  26011. toJSON( meta ) {
  26012. const data = super.toJSON( meta );
  26013. data.object.zoom = this.zoom;
  26014. data.object.left = this.left;
  26015. data.object.right = this.right;
  26016. data.object.top = this.top;
  26017. data.object.bottom = this.bottom;
  26018. data.object.near = this.near;
  26019. data.object.far = this.far;
  26020. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  26021. return data;
  26022. }
  26023. }
  26024. /**
  26025. * Represents the shadow configuration of directional lights.
  26026. *
  26027. * @augments LightShadow
  26028. */
  26029. class DirectionalLightShadow extends LightShadow {
  26030. /**
  26031. * Constructs a new directional light shadow.
  26032. */
  26033. constructor() {
  26034. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  26035. /**
  26036. * This flag can be used for type testing.
  26037. *
  26038. * @type {boolean}
  26039. * @readonly
  26040. * @default true
  26041. */
  26042. this.isDirectionalLightShadow = true;
  26043. }
  26044. }
  26045. /**
  26046. * A light that gets emitted in a specific direction. This light will behave
  26047. * as though it is infinitely far away and the rays produced from it are all
  26048. * parallel. The common use case for this is to simulate daylight; the sun is
  26049. * far enough away that its position can be considered to be infinite, and
  26050. * all light rays coming from it are parallel.
  26051. *
  26052. * A common point of confusion for directional lights is that setting the
  26053. * rotation has no effect. This is because three.js's DirectionalLight is the
  26054. * equivalent to what is often called a 'Target Direct Light' in other
  26055. * applications.
  26056. *
  26057. * This means that its direction is calculated as pointing from the light's
  26058. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  26059. * (as opposed to a 'Free Direct Light' that just has a rotation
  26060. * component).
  26061. *
  26062. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  26063. *
  26064. * ```js
  26065. * // White directional light at half intensity shining from the top.
  26066. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  26067. * scene.add( directionalLight );
  26068. * ```
  26069. *
  26070. * @augments Light
  26071. */
  26072. class DirectionalLight extends Light {
  26073. /**
  26074. * Constructs a new directional light.
  26075. *
  26076. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  26077. * @param {number} [intensity=1] - The light's strength/intensity.
  26078. */
  26079. constructor( color, intensity ) {
  26080. super( color, intensity );
  26081. /**
  26082. * This flag can be used for type testing.
  26083. *
  26084. * @type {boolean}
  26085. * @readonly
  26086. * @default true
  26087. */
  26088. this.isDirectionalLight = true;
  26089. this.type = 'DirectionalLight';
  26090. this.position.copy( Object3D.DEFAULT_UP );
  26091. this.updateMatrix();
  26092. /**
  26093. * The directional light points from its position to the
  26094. * target's position.
  26095. *
  26096. * For the target's position to be changed to anything other
  26097. * than the default, it must be added to the scene.
  26098. *
  26099. * It is also possible to set the target to be another 3D object
  26100. * in the scene. The light will now track the target object.
  26101. *
  26102. * @type {Object3D}
  26103. */
  26104. this.target = new Object3D();
  26105. /**
  26106. * This property holds the light's shadow configuration.
  26107. *
  26108. * @type {DirectionalLightShadow}
  26109. */
  26110. this.shadow = new DirectionalLightShadow();
  26111. }
  26112. dispose() {
  26113. this.shadow.dispose();
  26114. }
  26115. copy( source ) {
  26116. super.copy( source );
  26117. this.target = source.target.clone();
  26118. this.shadow = source.shadow.clone();
  26119. return this;
  26120. }
  26121. }
  26122. /**
  26123. * This light globally illuminates all objects in the scene equally.
  26124. *
  26125. * It cannot be used to cast shadows as it does not have a direction.
  26126. *
  26127. * ```js
  26128. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  26129. * scene.add( light );
  26130. * ```
  26131. *
  26132. * @augments Light
  26133. */
  26134. class AmbientLight extends Light {
  26135. /**
  26136. * Constructs a new ambient light.
  26137. *
  26138. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  26139. * @param {number} [intensity=1] - The light's strength/intensity.
  26140. */
  26141. constructor( color, intensity ) {
  26142. super( color, intensity );
  26143. /**
  26144. * This flag can be used for type testing.
  26145. *
  26146. * @type {boolean}
  26147. * @readonly
  26148. * @default true
  26149. */
  26150. this.isAmbientLight = true;
  26151. this.type = 'AmbientLight';
  26152. }
  26153. }
  26154. /**
  26155. * This class emits light uniformly across the face a rectangular plane.
  26156. * This light type can be used to simulate light sources such as bright
  26157. * windows or strip lighting.
  26158. *
  26159. * Important Notes:
  26160. *
  26161. * - There is no shadow support.
  26162. * - Only PBR materials are supported.
  26163. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  26164. * into your app and init the uniforms/textures.
  26165. *
  26166. * ```js
  26167. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  26168. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  26169. *
  26170. * const intensity = 1; const width = 10; const height = 10;
  26171. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  26172. * rectLight.position.set( 5, 5, 0 );
  26173. * rectLight.lookAt( 0, 0, 0 );
  26174. * scene.add( rectLight )
  26175. * ```
  26176. *
  26177. * @augments Light
  26178. */
  26179. class RectAreaLight extends Light {
  26180. /**
  26181. * Constructs a new area light.
  26182. *
  26183. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  26184. * @param {number} [intensity=1] - The light's strength/intensity.
  26185. * @param {number} [width=10] - The width of the light.
  26186. * @param {number} [height=10] - The height of the light.
  26187. */
  26188. constructor( color, intensity, width = 10, height = 10 ) {
  26189. super( color, intensity );
  26190. /**
  26191. * This flag can be used for type testing.
  26192. *
  26193. * @type {boolean}
  26194. * @readonly
  26195. * @default true
  26196. */
  26197. this.isRectAreaLight = true;
  26198. this.type = 'RectAreaLight';
  26199. /**
  26200. * The width of the light.
  26201. *
  26202. * @type {number}
  26203. * @default 10
  26204. */
  26205. this.width = width;
  26206. /**
  26207. * The height of the light.
  26208. *
  26209. * @type {number}
  26210. * @default 10
  26211. */
  26212. this.height = height;
  26213. }
  26214. /**
  26215. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  26216. * Changing the power will also change the light's intensity.
  26217. *
  26218. * @type {number}
  26219. */
  26220. get power() {
  26221. // compute the light's luminous power (in lumens) from its intensity (in nits)
  26222. return this.intensity * this.width * this.height * Math.PI;
  26223. }
  26224. set power( power ) {
  26225. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  26226. this.intensity = power / ( this.width * this.height * Math.PI );
  26227. }
  26228. copy( source ) {
  26229. super.copy( source );
  26230. this.width = source.width;
  26231. this.height = source.height;
  26232. return this;
  26233. }
  26234. toJSON( meta ) {
  26235. const data = super.toJSON( meta );
  26236. data.object.width = this.width;
  26237. data.object.height = this.height;
  26238. return data;
  26239. }
  26240. }
  26241. /**
  26242. * Represents a third-order spherical harmonics (SH). Light probes use this class
  26243. * to encode lighting information.
  26244. *
  26245. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  26246. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  26247. */
  26248. class SphericalHarmonics3 {
  26249. /**
  26250. * Constructs a new spherical harmonics.
  26251. */
  26252. constructor() {
  26253. /**
  26254. * This flag can be used for type testing.
  26255. *
  26256. * @type {boolean}
  26257. * @readonly
  26258. * @default true
  26259. */
  26260. this.isSphericalHarmonics3 = true;
  26261. /**
  26262. * An array holding the (9) SH coefficients.
  26263. *
  26264. * @type {Array<Vector3>}
  26265. */
  26266. this.coefficients = [];
  26267. for ( let i = 0; i < 9; i ++ ) {
  26268. this.coefficients.push( new Vector3() );
  26269. }
  26270. }
  26271. /**
  26272. * Sets the given SH coefficients to this instance by copying
  26273. * the values.
  26274. *
  26275. * @param {Array<Vector3>} coefficients - The SH coefficients.
  26276. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26277. */
  26278. set( coefficients ) {
  26279. for ( let i = 0; i < 9; i ++ ) {
  26280. this.coefficients[ i ].copy( coefficients[ i ] );
  26281. }
  26282. return this;
  26283. }
  26284. /**
  26285. * Sets all SH coefficients to `0`.
  26286. *
  26287. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26288. */
  26289. zero() {
  26290. for ( let i = 0; i < 9; i ++ ) {
  26291. this.coefficients[ i ].set( 0, 0, 0 );
  26292. }
  26293. return this;
  26294. }
  26295. /**
  26296. * Returns the radiance in the direction of the given normal.
  26297. *
  26298. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  26299. * @param {Vector3} target - The target vector that is used to store the method's result.
  26300. * @return {Vector3} The radiance.
  26301. */
  26302. getAt( normal, target ) {
  26303. // normal is assumed to be unit length
  26304. const x = normal.x, y = normal.y, z = normal.z;
  26305. const coeff = this.coefficients;
  26306. // band 0
  26307. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  26308. // band 1
  26309. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  26310. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  26311. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  26312. // band 2
  26313. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  26314. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  26315. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  26316. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  26317. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  26318. return target;
  26319. }
  26320. /**
  26321. * Returns the irradiance (radiance convolved with cosine lobe) in the
  26322. * direction of the given normal.
  26323. *
  26324. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  26325. * @param {Vector3} target - The target vector that is used to store the method's result.
  26326. * @return {Vector3} The irradiance.
  26327. */
  26328. getIrradianceAt( normal, target ) {
  26329. // normal is assumed to be unit length
  26330. const x = normal.x, y = normal.y, z = normal.z;
  26331. const coeff = this.coefficients;
  26332. // band 0
  26333. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  26334. // band 1
  26335. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  26336. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  26337. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  26338. // band 2
  26339. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  26340. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  26341. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  26342. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  26343. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  26344. return target;
  26345. }
  26346. /**
  26347. * Adds the given SH to this instance.
  26348. *
  26349. * @param {SphericalHarmonics3} sh - The SH to add.
  26350. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26351. */
  26352. add( sh ) {
  26353. for ( let i = 0; i < 9; i ++ ) {
  26354. this.coefficients[ i ].add( sh.coefficients[ i ] );
  26355. }
  26356. return this;
  26357. }
  26358. /**
  26359. * A convenience method for performing {@link SphericalHarmonics3#add} and
  26360. * {@link SphericalHarmonics3#scale} at once.
  26361. *
  26362. * @param {SphericalHarmonics3} sh - The SH to add.
  26363. * @param {number} s - The scale factor.
  26364. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26365. */
  26366. addScaledSH( sh, s ) {
  26367. for ( let i = 0; i < 9; i ++ ) {
  26368. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  26369. }
  26370. return this;
  26371. }
  26372. /**
  26373. * Scales this SH by the given scale factor.
  26374. *
  26375. * @param {number} s - The scale factor.
  26376. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26377. */
  26378. scale( s ) {
  26379. for ( let i = 0; i < 9; i ++ ) {
  26380. this.coefficients[ i ].multiplyScalar( s );
  26381. }
  26382. return this;
  26383. }
  26384. /**
  26385. * Linear interpolates between the given SH and this instance by the given
  26386. * alpha factor.
  26387. *
  26388. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  26389. * @param {number} alpha - The alpha factor.
  26390. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26391. */
  26392. lerp( sh, alpha ) {
  26393. for ( let i = 0; i < 9; i ++ ) {
  26394. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  26395. }
  26396. return this;
  26397. }
  26398. /**
  26399. * Returns `true` if this spherical harmonics is equal with the given one.
  26400. *
  26401. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  26402. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  26403. */
  26404. equals( sh ) {
  26405. for ( let i = 0; i < 9; i ++ ) {
  26406. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  26407. return false;
  26408. }
  26409. }
  26410. return true;
  26411. }
  26412. /**
  26413. * Copies the values of the given spherical harmonics to this instance.
  26414. *
  26415. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  26416. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26417. */
  26418. copy( sh ) {
  26419. return this.set( sh.coefficients );
  26420. }
  26421. /**
  26422. * Returns a new spherical harmonics with copied values from this instance.
  26423. *
  26424. * @return {SphericalHarmonics3} A clone of this instance.
  26425. */
  26426. clone() {
  26427. return new this.constructor().copy( this );
  26428. }
  26429. /**
  26430. * Sets the SH coefficients of this instance from the given array.
  26431. *
  26432. * @param {Array<number>} array - An array holding the SH coefficients.
  26433. * @param {number} [offset=0] - The array offset where to start copying.
  26434. * @return {SphericalHarmonics3} A clone of this instance.
  26435. */
  26436. fromArray( array, offset = 0 ) {
  26437. const coefficients = this.coefficients;
  26438. for ( let i = 0; i < 9; i ++ ) {
  26439. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  26440. }
  26441. return this;
  26442. }
  26443. /**
  26444. * Returns an array with the SH coefficients, or copies them into the provided
  26445. * array. The coefficients are represented as numbers.
  26446. *
  26447. * @param {Array<number>} [array=[]] - The target array.
  26448. * @param {number} [offset=0] - The array offset where to start copying.
  26449. * @return {Array<number>} An array with flat SH coefficients.
  26450. */
  26451. toArray( array = [], offset = 0 ) {
  26452. const coefficients = this.coefficients;
  26453. for ( let i = 0; i < 9; i ++ ) {
  26454. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  26455. }
  26456. return array;
  26457. }
  26458. /**
  26459. * Computes the SH basis for the given normal vector.
  26460. *
  26461. * @param {Vector3} normal - The normal.
  26462. * @param {Array<number>} shBasis - The target array holding the SH basis.
  26463. */
  26464. static getBasisAt( normal, shBasis ) {
  26465. // normal is assumed to be unit length
  26466. const x = normal.x, y = normal.y, z = normal.z;
  26467. // band 0
  26468. shBasis[ 0 ] = 0.282095;
  26469. // band 1
  26470. shBasis[ 1 ] = 0.488603 * y;
  26471. shBasis[ 2 ] = 0.488603 * z;
  26472. shBasis[ 3 ] = 0.488603 * x;
  26473. // band 2
  26474. shBasis[ 4 ] = 1.092548 * x * y;
  26475. shBasis[ 5 ] = 1.092548 * y * z;
  26476. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  26477. shBasis[ 7 ] = 1.092548 * x * z;
  26478. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  26479. }
  26480. }
  26481. /**
  26482. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  26483. * classical light sources (e.g. directional, point or spot lights), light
  26484. * probes do not emit light. Instead they store information about light
  26485. * passing through 3D space. During rendering, the light that hits a 3D
  26486. * object is approximated by using the data from the light probe.
  26487. *
  26488. * Light probes are usually created from (radiance) environment maps. The
  26489. * class {@link LightProbeGenerator} can be used to create light probes from
  26490. * cube textures or render targets. However, light estimation data could also
  26491. * be provided in other forms e.g. by WebXR. This enables the rendering of
  26492. * augmented reality content that reacts to real world lighting.
  26493. *
  26494. * The current probe implementation in three.js supports so-called diffuse
  26495. * light probes. This type of light probe is functionally equivalent to an
  26496. * irradiance environment map.
  26497. *
  26498. * @augments Light
  26499. */
  26500. class LightProbe extends Light {
  26501. /**
  26502. * Constructs a new light probe.
  26503. *
  26504. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  26505. * @param {number} [intensity=1] - The light's strength/intensity.
  26506. */
  26507. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  26508. super( undefined, intensity );
  26509. /**
  26510. * This flag can be used for type testing.
  26511. *
  26512. * @type {boolean}
  26513. * @readonly
  26514. * @default true
  26515. */
  26516. this.isLightProbe = true;
  26517. /**
  26518. * A light probe uses spherical harmonics to encode lighting information.
  26519. *
  26520. * @type {SphericalHarmonics3}
  26521. */
  26522. this.sh = sh;
  26523. }
  26524. copy( source ) {
  26525. super.copy( source );
  26526. this.sh.copy( source.sh );
  26527. return this;
  26528. }
  26529. /**
  26530. * Deserializes the light prove from the given JSON.
  26531. *
  26532. * @param {Object} json - The JSON holding the serialized light probe.
  26533. * @return {LightProbe} A reference to this light probe.
  26534. */
  26535. fromJSON( json ) {
  26536. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  26537. this.sh.fromArray( json.sh );
  26538. return this;
  26539. }
  26540. toJSON( meta ) {
  26541. const data = super.toJSON( meta );
  26542. data.object.sh = this.sh.toArray();
  26543. return data;
  26544. }
  26545. }
  26546. class MaterialLoader extends Loader {
  26547. constructor( manager ) {
  26548. super( manager );
  26549. this.textures = {};
  26550. }
  26551. load( url, onLoad, onProgress, onError ) {
  26552. const scope = this;
  26553. const loader = new FileLoader( scope.manager );
  26554. loader.setPath( scope.path );
  26555. loader.setRequestHeader( scope.requestHeader );
  26556. loader.setWithCredentials( scope.withCredentials );
  26557. loader.load( url, function ( text ) {
  26558. try {
  26559. onLoad( scope.parse( JSON.parse( text ) ) );
  26560. } catch ( e ) {
  26561. if ( onError ) {
  26562. onError( e );
  26563. } else {
  26564. console.error( e );
  26565. }
  26566. scope.manager.itemError( url );
  26567. }
  26568. }, onProgress, onError );
  26569. }
  26570. parse( json ) {
  26571. const textures = this.textures;
  26572. function getTexture( name ) {
  26573. if ( textures[ name ] === undefined ) {
  26574. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  26575. }
  26576. return textures[ name ];
  26577. }
  26578. const material = this.createMaterialFromType( json.type );
  26579. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  26580. if ( json.name !== undefined ) material.name = json.name;
  26581. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  26582. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  26583. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  26584. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  26585. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  26586. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  26587. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  26588. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  26589. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  26590. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  26591. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  26592. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  26593. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  26594. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  26595. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  26596. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  26597. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  26598. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  26599. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  26600. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  26601. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  26602. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  26603. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  26604. if ( json.fog !== undefined ) material.fog = json.fog;
  26605. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  26606. if ( json.blending !== undefined ) material.blending = json.blending;
  26607. if ( json.combine !== undefined ) material.combine = json.combine;
  26608. if ( json.side !== undefined ) material.side = json.side;
  26609. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  26610. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  26611. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  26612. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  26613. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  26614. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  26615. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  26616. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  26617. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  26618. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  26619. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  26620. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  26621. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  26622. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  26623. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  26624. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  26625. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  26626. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  26627. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  26628. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  26629. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  26630. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  26631. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  26632. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  26633. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  26634. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  26635. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  26636. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  26637. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  26638. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  26639. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  26640. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  26641. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  26642. if ( json.scale !== undefined ) material.scale = json.scale;
  26643. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  26644. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  26645. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  26646. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  26647. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  26648. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  26649. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  26650. if ( json.visible !== undefined ) material.visible = json.visible;
  26651. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  26652. if ( json.userData !== undefined ) material.userData = json.userData;
  26653. if ( json.vertexColors !== undefined ) {
  26654. if ( typeof json.vertexColors === 'number' ) {
  26655. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  26656. } else {
  26657. material.vertexColors = json.vertexColors;
  26658. }
  26659. }
  26660. // Shader Material
  26661. if ( json.uniforms !== undefined ) {
  26662. for ( const name in json.uniforms ) {
  26663. const uniform = json.uniforms[ name ];
  26664. material.uniforms[ name ] = {};
  26665. switch ( uniform.type ) {
  26666. case 't':
  26667. material.uniforms[ name ].value = getTexture( uniform.value );
  26668. break;
  26669. case 'c':
  26670. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  26671. break;
  26672. case 'v2':
  26673. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  26674. break;
  26675. case 'v3':
  26676. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  26677. break;
  26678. case 'v4':
  26679. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  26680. break;
  26681. case 'm3':
  26682. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  26683. break;
  26684. case 'm4':
  26685. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  26686. break;
  26687. default:
  26688. material.uniforms[ name ].value = uniform.value;
  26689. }
  26690. }
  26691. }
  26692. if ( json.defines !== undefined ) material.defines = json.defines;
  26693. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  26694. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  26695. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  26696. if ( json.extensions !== undefined ) {
  26697. for ( const key in json.extensions ) {
  26698. material.extensions[ key ] = json.extensions[ key ];
  26699. }
  26700. }
  26701. if ( json.lights !== undefined ) material.lights = json.lights;
  26702. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  26703. // for PointsMaterial
  26704. if ( json.size !== undefined ) material.size = json.size;
  26705. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  26706. // maps
  26707. if ( json.map !== undefined ) material.map = getTexture( json.map );
  26708. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  26709. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  26710. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  26711. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  26712. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  26713. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  26714. if ( json.normalScale !== undefined ) {
  26715. let normalScale = json.normalScale;
  26716. if ( Array.isArray( normalScale ) === false ) {
  26717. // Blender exporter used to export a scalar. See #7459
  26718. normalScale = [ normalScale, normalScale ];
  26719. }
  26720. material.normalScale = new Vector2().fromArray( normalScale );
  26721. }
  26722. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  26723. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  26724. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  26725. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  26726. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  26727. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  26728. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  26729. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  26730. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  26731. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  26732. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  26733. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  26734. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  26735. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  26736. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  26737. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  26738. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  26739. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  26740. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  26741. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  26742. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  26743. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  26744. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  26745. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  26746. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  26747. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  26748. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  26749. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  26750. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  26751. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  26752. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  26753. return material;
  26754. }
  26755. setTextures( value ) {
  26756. this.textures = value;
  26757. return this;
  26758. }
  26759. createMaterialFromType( type ) {
  26760. return MaterialLoader.createMaterialFromType( type );
  26761. }
  26762. static createMaterialFromType( type ) {
  26763. const materialLib = {
  26764. ShadowMaterial,
  26765. SpriteMaterial,
  26766. RawShaderMaterial,
  26767. ShaderMaterial,
  26768. PointsMaterial,
  26769. MeshPhysicalMaterial,
  26770. MeshStandardMaterial,
  26771. MeshPhongMaterial,
  26772. MeshToonMaterial,
  26773. MeshNormalMaterial,
  26774. MeshLambertMaterial,
  26775. MeshDepthMaterial,
  26776. MeshDistanceMaterial,
  26777. MeshBasicMaterial,
  26778. MeshMatcapMaterial,
  26779. LineDashedMaterial,
  26780. LineBasicMaterial,
  26781. Material
  26782. };
  26783. return new materialLib[ type ]();
  26784. }
  26785. }
  26786. class LoaderUtils {
  26787. static decodeText( array ) { // @deprecated, r165
  26788. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  26789. if ( typeof TextDecoder !== 'undefined' ) {
  26790. return new TextDecoder().decode( array );
  26791. }
  26792. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  26793. // throws a "maximum call stack size exceeded" error for large arrays.
  26794. let s = '';
  26795. for ( let i = 0, il = array.length; i < il; i ++ ) {
  26796. // Implicitly assumes little-endian.
  26797. s += String.fromCharCode( array[ i ] );
  26798. }
  26799. try {
  26800. // merges multi-byte utf-8 characters.
  26801. return decodeURIComponent( escape( s ) );
  26802. } catch ( e ) { // see #16358
  26803. return s;
  26804. }
  26805. }
  26806. static extractUrlBase( url ) {
  26807. const index = url.lastIndexOf( '/' );
  26808. if ( index === -1 ) return './';
  26809. return url.slice( 0, index + 1 );
  26810. }
  26811. static resolveURL( url, path ) {
  26812. // Invalid URL
  26813. if ( typeof url !== 'string' || url === '' ) return '';
  26814. // Host Relative URL
  26815. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  26816. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  26817. }
  26818. // Absolute URL http://,https://,//
  26819. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  26820. // Data URI
  26821. if ( /^data:.*,.*$/i.test( url ) ) return url;
  26822. // Blob URL
  26823. if ( /^blob:.*$/i.test( url ) ) return url;
  26824. // Relative URL
  26825. return path + url;
  26826. }
  26827. }
  26828. class InstancedBufferGeometry extends BufferGeometry {
  26829. constructor() {
  26830. super();
  26831. this.isInstancedBufferGeometry = true;
  26832. this.type = 'InstancedBufferGeometry';
  26833. this.instanceCount = Infinity;
  26834. }
  26835. copy( source ) {
  26836. super.copy( source );
  26837. this.instanceCount = source.instanceCount;
  26838. return this;
  26839. }
  26840. toJSON() {
  26841. const data = super.toJSON();
  26842. data.instanceCount = this.instanceCount;
  26843. data.isInstancedBufferGeometry = true;
  26844. return data;
  26845. }
  26846. }
  26847. class BufferGeometryLoader extends Loader {
  26848. constructor( manager ) {
  26849. super( manager );
  26850. }
  26851. load( url, onLoad, onProgress, onError ) {
  26852. const scope = this;
  26853. const loader = new FileLoader( scope.manager );
  26854. loader.setPath( scope.path );
  26855. loader.setRequestHeader( scope.requestHeader );
  26856. loader.setWithCredentials( scope.withCredentials );
  26857. loader.load( url, function ( text ) {
  26858. try {
  26859. onLoad( scope.parse( JSON.parse( text ) ) );
  26860. } catch ( e ) {
  26861. if ( onError ) {
  26862. onError( e );
  26863. } else {
  26864. console.error( e );
  26865. }
  26866. scope.manager.itemError( url );
  26867. }
  26868. }, onProgress, onError );
  26869. }
  26870. parse( json ) {
  26871. const interleavedBufferMap = {};
  26872. const arrayBufferMap = {};
  26873. function getInterleavedBuffer( json, uuid ) {
  26874. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  26875. const interleavedBuffers = json.interleavedBuffers;
  26876. const interleavedBuffer = interleavedBuffers[ uuid ];
  26877. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  26878. const array = getTypedArray( interleavedBuffer.type, buffer );
  26879. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  26880. ib.uuid = interleavedBuffer.uuid;
  26881. interleavedBufferMap[ uuid ] = ib;
  26882. return ib;
  26883. }
  26884. function getArrayBuffer( json, uuid ) {
  26885. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  26886. const arrayBuffers = json.arrayBuffers;
  26887. const arrayBuffer = arrayBuffers[ uuid ];
  26888. const ab = new Uint32Array( arrayBuffer ).buffer;
  26889. arrayBufferMap[ uuid ] = ab;
  26890. return ab;
  26891. }
  26892. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  26893. const index = json.data.index;
  26894. if ( index !== undefined ) {
  26895. const typedArray = getTypedArray( index.type, index.array );
  26896. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  26897. }
  26898. const attributes = json.data.attributes;
  26899. for ( const key in attributes ) {
  26900. const attribute = attributes[ key ];
  26901. let bufferAttribute;
  26902. if ( attribute.isInterleavedBufferAttribute ) {
  26903. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  26904. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  26905. } else {
  26906. const typedArray = getTypedArray( attribute.type, attribute.array );
  26907. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  26908. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  26909. }
  26910. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  26911. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  26912. geometry.setAttribute( key, bufferAttribute );
  26913. }
  26914. const morphAttributes = json.data.morphAttributes;
  26915. if ( morphAttributes ) {
  26916. for ( const key in morphAttributes ) {
  26917. const attributeArray = morphAttributes[ key ];
  26918. const array = [];
  26919. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  26920. const attribute = attributeArray[ i ];
  26921. let bufferAttribute;
  26922. if ( attribute.isInterleavedBufferAttribute ) {
  26923. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  26924. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  26925. } else {
  26926. const typedArray = getTypedArray( attribute.type, attribute.array );
  26927. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  26928. }
  26929. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  26930. array.push( bufferAttribute );
  26931. }
  26932. geometry.morphAttributes[ key ] = array;
  26933. }
  26934. }
  26935. const morphTargetsRelative = json.data.morphTargetsRelative;
  26936. if ( morphTargetsRelative ) {
  26937. geometry.morphTargetsRelative = true;
  26938. }
  26939. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  26940. if ( groups !== undefined ) {
  26941. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  26942. const group = groups[ i ];
  26943. geometry.addGroup( group.start, group.count, group.materialIndex );
  26944. }
  26945. }
  26946. const boundingSphere = json.data.boundingSphere;
  26947. if ( boundingSphere !== undefined ) {
  26948. const center = new Vector3();
  26949. if ( boundingSphere.center !== undefined ) {
  26950. center.fromArray( boundingSphere.center );
  26951. }
  26952. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  26953. }
  26954. if ( json.name ) geometry.name = json.name;
  26955. if ( json.userData ) geometry.userData = json.userData;
  26956. return geometry;
  26957. }
  26958. }
  26959. class ObjectLoader extends Loader {
  26960. constructor( manager ) {
  26961. super( manager );
  26962. }
  26963. load( url, onLoad, onProgress, onError ) {
  26964. const scope = this;
  26965. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26966. this.resourcePath = this.resourcePath || path;
  26967. const loader = new FileLoader( this.manager );
  26968. loader.setPath( this.path );
  26969. loader.setRequestHeader( this.requestHeader );
  26970. loader.setWithCredentials( this.withCredentials );
  26971. loader.load( url, function ( text ) {
  26972. let json = null;
  26973. try {
  26974. json = JSON.parse( text );
  26975. } catch ( error ) {
  26976. if ( onError !== undefined ) onError( error );
  26977. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  26978. return;
  26979. }
  26980. const metadata = json.metadata;
  26981. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26982. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  26983. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  26984. return;
  26985. }
  26986. scope.parse( json, onLoad );
  26987. }, onProgress, onError );
  26988. }
  26989. async loadAsync( url, onProgress ) {
  26990. const scope = this;
  26991. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26992. this.resourcePath = this.resourcePath || path;
  26993. const loader = new FileLoader( this.manager );
  26994. loader.setPath( this.path );
  26995. loader.setRequestHeader( this.requestHeader );
  26996. loader.setWithCredentials( this.withCredentials );
  26997. const text = await loader.loadAsync( url, onProgress );
  26998. const json = JSON.parse( text );
  26999. const metadata = json.metadata;
  27000. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27001. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27002. }
  27003. return await scope.parseAsync( json );
  27004. }
  27005. parse( json, onLoad ) {
  27006. const animations = this.parseAnimations( json.animations );
  27007. const shapes = this.parseShapes( json.shapes );
  27008. const geometries = this.parseGeometries( json.geometries, shapes );
  27009. const images = this.parseImages( json.images, function () {
  27010. if ( onLoad !== undefined ) onLoad( object );
  27011. } );
  27012. const textures = this.parseTextures( json.textures, images );
  27013. const materials = this.parseMaterials( json.materials, textures );
  27014. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27015. const skeletons = this.parseSkeletons( json.skeletons, object );
  27016. this.bindSkeletons( object, skeletons );
  27017. this.bindLightTargets( object );
  27018. //
  27019. if ( onLoad !== undefined ) {
  27020. let hasImages = false;
  27021. for ( const uuid in images ) {
  27022. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  27023. hasImages = true;
  27024. break;
  27025. }
  27026. }
  27027. if ( hasImages === false ) onLoad( object );
  27028. }
  27029. return object;
  27030. }
  27031. async parseAsync( json ) {
  27032. const animations = this.parseAnimations( json.animations );
  27033. const shapes = this.parseShapes( json.shapes );
  27034. const geometries = this.parseGeometries( json.geometries, shapes );
  27035. const images = await this.parseImagesAsync( json.images );
  27036. const textures = this.parseTextures( json.textures, images );
  27037. const materials = this.parseMaterials( json.materials, textures );
  27038. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27039. const skeletons = this.parseSkeletons( json.skeletons, object );
  27040. this.bindSkeletons( object, skeletons );
  27041. this.bindLightTargets( object );
  27042. return object;
  27043. }
  27044. parseShapes( json ) {
  27045. const shapes = {};
  27046. if ( json !== undefined ) {
  27047. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27048. const shape = new Shape().fromJSON( json[ i ] );
  27049. shapes[ shape.uuid ] = shape;
  27050. }
  27051. }
  27052. return shapes;
  27053. }
  27054. parseSkeletons( json, object ) {
  27055. const skeletons = {};
  27056. const bones = {};
  27057. // generate bone lookup table
  27058. object.traverse( function ( child ) {
  27059. if ( child.isBone ) bones[ child.uuid ] = child;
  27060. } );
  27061. // create skeletons
  27062. if ( json !== undefined ) {
  27063. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27064. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  27065. skeletons[ skeleton.uuid ] = skeleton;
  27066. }
  27067. }
  27068. return skeletons;
  27069. }
  27070. parseGeometries( json, shapes ) {
  27071. const geometries = {};
  27072. if ( json !== undefined ) {
  27073. const bufferGeometryLoader = new BufferGeometryLoader();
  27074. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27075. let geometry;
  27076. const data = json[ i ];
  27077. switch ( data.type ) {
  27078. case 'BufferGeometry':
  27079. case 'InstancedBufferGeometry':
  27080. geometry = bufferGeometryLoader.parse( data );
  27081. break;
  27082. default:
  27083. if ( data.type in Geometries ) {
  27084. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  27085. } else {
  27086. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  27087. }
  27088. }
  27089. geometry.uuid = data.uuid;
  27090. if ( data.name !== undefined ) geometry.name = data.name;
  27091. if ( data.userData !== undefined ) geometry.userData = data.userData;
  27092. geometries[ data.uuid ] = geometry;
  27093. }
  27094. }
  27095. return geometries;
  27096. }
  27097. parseMaterials( json, textures ) {
  27098. const cache = {}; // MultiMaterial
  27099. const materials = {};
  27100. if ( json !== undefined ) {
  27101. const loader = new MaterialLoader();
  27102. loader.setTextures( textures );
  27103. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27104. const data = json[ i ];
  27105. if ( cache[ data.uuid ] === undefined ) {
  27106. cache[ data.uuid ] = loader.parse( data );
  27107. }
  27108. materials[ data.uuid ] = cache[ data.uuid ];
  27109. }
  27110. }
  27111. return materials;
  27112. }
  27113. parseAnimations( json ) {
  27114. const animations = {};
  27115. if ( json !== undefined ) {
  27116. for ( let i = 0; i < json.length; i ++ ) {
  27117. const data = json[ i ];
  27118. const clip = AnimationClip.parse( data );
  27119. animations[ clip.uuid ] = clip;
  27120. }
  27121. }
  27122. return animations;
  27123. }
  27124. parseImages( json, onLoad ) {
  27125. const scope = this;
  27126. const images = {};
  27127. let loader;
  27128. function loadImage( url ) {
  27129. scope.manager.itemStart( url );
  27130. return loader.load( url, function () {
  27131. scope.manager.itemEnd( url );
  27132. }, undefined, function () {
  27133. scope.manager.itemError( url );
  27134. scope.manager.itemEnd( url );
  27135. } );
  27136. }
  27137. function deserializeImage( image ) {
  27138. if ( typeof image === 'string' ) {
  27139. const url = image;
  27140. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27141. return loadImage( path );
  27142. } else {
  27143. if ( image.data ) {
  27144. return {
  27145. data: getTypedArray( image.type, image.data ),
  27146. width: image.width,
  27147. height: image.height
  27148. };
  27149. } else {
  27150. return null;
  27151. }
  27152. }
  27153. }
  27154. if ( json !== undefined && json.length > 0 ) {
  27155. const manager = new LoadingManager( onLoad );
  27156. loader = new ImageLoader( manager );
  27157. loader.setCrossOrigin( this.crossOrigin );
  27158. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27159. const image = json[ i ];
  27160. const url = image.url;
  27161. if ( Array.isArray( url ) ) {
  27162. // load array of images e.g CubeTexture
  27163. const imageArray = [];
  27164. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27165. const currentUrl = url[ j ];
  27166. const deserializedImage = deserializeImage( currentUrl );
  27167. if ( deserializedImage !== null ) {
  27168. if ( deserializedImage instanceof HTMLImageElement ) {
  27169. imageArray.push( deserializedImage );
  27170. } else {
  27171. // special case: handle array of data textures for cube textures
  27172. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27173. }
  27174. }
  27175. }
  27176. images[ image.uuid ] = new Source( imageArray );
  27177. } else {
  27178. // load single image
  27179. const deserializedImage = deserializeImage( image.url );
  27180. images[ image.uuid ] = new Source( deserializedImage );
  27181. }
  27182. }
  27183. }
  27184. return images;
  27185. }
  27186. async parseImagesAsync( json ) {
  27187. const scope = this;
  27188. const images = {};
  27189. let loader;
  27190. async function deserializeImage( image ) {
  27191. if ( typeof image === 'string' ) {
  27192. const url = image;
  27193. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27194. return await loader.loadAsync( path );
  27195. } else {
  27196. if ( image.data ) {
  27197. return {
  27198. data: getTypedArray( image.type, image.data ),
  27199. width: image.width,
  27200. height: image.height
  27201. };
  27202. } else {
  27203. return null;
  27204. }
  27205. }
  27206. }
  27207. if ( json !== undefined && json.length > 0 ) {
  27208. loader = new ImageLoader( this.manager );
  27209. loader.setCrossOrigin( this.crossOrigin );
  27210. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27211. const image = json[ i ];
  27212. const url = image.url;
  27213. if ( Array.isArray( url ) ) {
  27214. // load array of images e.g CubeTexture
  27215. const imageArray = [];
  27216. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27217. const currentUrl = url[ j ];
  27218. const deserializedImage = await deserializeImage( currentUrl );
  27219. if ( deserializedImage !== null ) {
  27220. if ( deserializedImage instanceof HTMLImageElement ) {
  27221. imageArray.push( deserializedImage );
  27222. } else {
  27223. // special case: handle array of data textures for cube textures
  27224. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27225. }
  27226. }
  27227. }
  27228. images[ image.uuid ] = new Source( imageArray );
  27229. } else {
  27230. // load single image
  27231. const deserializedImage = await deserializeImage( image.url );
  27232. images[ image.uuid ] = new Source( deserializedImage );
  27233. }
  27234. }
  27235. }
  27236. return images;
  27237. }
  27238. parseTextures( json, images ) {
  27239. function parseConstant( value, type ) {
  27240. if ( typeof value === 'number' ) return value;
  27241. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  27242. return type[ value ];
  27243. }
  27244. const textures = {};
  27245. if ( json !== undefined ) {
  27246. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27247. const data = json[ i ];
  27248. if ( data.image === undefined ) {
  27249. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  27250. }
  27251. if ( images[ data.image ] === undefined ) {
  27252. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  27253. }
  27254. const source = images[ data.image ];
  27255. const image = source.data;
  27256. let texture;
  27257. if ( Array.isArray( image ) ) {
  27258. texture = new CubeTexture();
  27259. if ( image.length === 6 ) texture.needsUpdate = true;
  27260. } else {
  27261. if ( image && image.data ) {
  27262. texture = new DataTexture();
  27263. } else {
  27264. texture = new Texture();
  27265. }
  27266. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  27267. }
  27268. texture.source = source;
  27269. texture.uuid = data.uuid;
  27270. if ( data.name !== undefined ) texture.name = data.name;
  27271. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  27272. if ( data.channel !== undefined ) texture.channel = data.channel;
  27273. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  27274. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  27275. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  27276. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  27277. if ( data.wrap !== undefined ) {
  27278. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  27279. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  27280. }
  27281. if ( data.format !== undefined ) texture.format = data.format;
  27282. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  27283. if ( data.type !== undefined ) texture.type = data.type;
  27284. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  27285. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  27286. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  27287. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  27288. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  27289. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  27290. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  27291. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  27292. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  27293. if ( data.userData !== undefined ) texture.userData = data.userData;
  27294. textures[ data.uuid ] = texture;
  27295. }
  27296. }
  27297. return textures;
  27298. }
  27299. parseObject( data, geometries, materials, textures, animations ) {
  27300. let object;
  27301. function getGeometry( name ) {
  27302. if ( geometries[ name ] === undefined ) {
  27303. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  27304. }
  27305. return geometries[ name ];
  27306. }
  27307. function getMaterial( name ) {
  27308. if ( name === undefined ) return undefined;
  27309. if ( Array.isArray( name ) ) {
  27310. const array = [];
  27311. for ( let i = 0, l = name.length; i < l; i ++ ) {
  27312. const uuid = name[ i ];
  27313. if ( materials[ uuid ] === undefined ) {
  27314. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  27315. }
  27316. array.push( materials[ uuid ] );
  27317. }
  27318. return array;
  27319. }
  27320. if ( materials[ name ] === undefined ) {
  27321. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  27322. }
  27323. return materials[ name ];
  27324. }
  27325. function getTexture( uuid ) {
  27326. if ( textures[ uuid ] === undefined ) {
  27327. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  27328. }
  27329. return textures[ uuid ];
  27330. }
  27331. let geometry, material;
  27332. switch ( data.type ) {
  27333. case 'Scene':
  27334. object = new Scene();
  27335. if ( data.background !== undefined ) {
  27336. if ( Number.isInteger( data.background ) ) {
  27337. object.background = new Color( data.background );
  27338. } else {
  27339. object.background = getTexture( data.background );
  27340. }
  27341. }
  27342. if ( data.environment !== undefined ) {
  27343. object.environment = getTexture( data.environment );
  27344. }
  27345. if ( data.fog !== undefined ) {
  27346. if ( data.fog.type === 'Fog' ) {
  27347. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  27348. } else if ( data.fog.type === 'FogExp2' ) {
  27349. object.fog = new FogExp2( data.fog.color, data.fog.density );
  27350. }
  27351. if ( data.fog.name !== '' ) {
  27352. object.fog.name = data.fog.name;
  27353. }
  27354. }
  27355. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  27356. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  27357. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  27358. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  27359. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  27360. break;
  27361. case 'PerspectiveCamera':
  27362. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  27363. if ( data.focus !== undefined ) object.focus = data.focus;
  27364. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27365. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  27366. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  27367. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27368. break;
  27369. case 'OrthographicCamera':
  27370. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  27371. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27372. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27373. break;
  27374. case 'AmbientLight':
  27375. object = new AmbientLight( data.color, data.intensity );
  27376. break;
  27377. case 'DirectionalLight':
  27378. object = new DirectionalLight( data.color, data.intensity );
  27379. object.target = data.target || '';
  27380. break;
  27381. case 'PointLight':
  27382. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  27383. break;
  27384. case 'RectAreaLight':
  27385. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  27386. break;
  27387. case 'SpotLight':
  27388. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  27389. object.target = data.target || '';
  27390. break;
  27391. case 'HemisphereLight':
  27392. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  27393. break;
  27394. case 'LightProbe':
  27395. object = new LightProbe().fromJSON( data );
  27396. break;
  27397. case 'SkinnedMesh':
  27398. geometry = getGeometry( data.geometry );
  27399. material = getMaterial( data.material );
  27400. object = new SkinnedMesh( geometry, material );
  27401. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  27402. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  27403. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  27404. break;
  27405. case 'Mesh':
  27406. geometry = getGeometry( data.geometry );
  27407. material = getMaterial( data.material );
  27408. object = new Mesh( geometry, material );
  27409. break;
  27410. case 'InstancedMesh':
  27411. geometry = getGeometry( data.geometry );
  27412. material = getMaterial( data.material );
  27413. const count = data.count;
  27414. const instanceMatrix = data.instanceMatrix;
  27415. const instanceColor = data.instanceColor;
  27416. object = new InstancedMesh( geometry, material, count );
  27417. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  27418. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  27419. break;
  27420. case 'BatchedMesh':
  27421. geometry = getGeometry( data.geometry );
  27422. material = getMaterial( data.material );
  27423. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  27424. object.geometry = geometry;
  27425. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  27426. object.sortObjects = data.sortObjects;
  27427. object._drawRanges = data.drawRanges;
  27428. object._reservedRanges = data.reservedRanges;
  27429. object._visibility = data.visibility;
  27430. object._active = data.active;
  27431. object._bounds = data.bounds.map( bound => {
  27432. const box = new Box3();
  27433. box.min.fromArray( bound.boxMin );
  27434. box.max.fromArray( bound.boxMax );
  27435. const sphere = new Sphere();
  27436. sphere.radius = bound.sphereRadius;
  27437. sphere.center.fromArray( bound.sphereCenter );
  27438. return {
  27439. boxInitialized: bound.boxInitialized,
  27440. box: box,
  27441. sphereInitialized: bound.sphereInitialized,
  27442. sphere: sphere
  27443. };
  27444. } );
  27445. object._maxInstanceCount = data.maxInstanceCount;
  27446. object._maxVertexCount = data.maxVertexCount;
  27447. object._maxIndexCount = data.maxIndexCount;
  27448. object._geometryInitialized = data.geometryInitialized;
  27449. object._geometryCount = data.geometryCount;
  27450. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  27451. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  27452. break;
  27453. case 'LOD':
  27454. object = new LOD();
  27455. break;
  27456. case 'Line':
  27457. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  27458. break;
  27459. case 'LineLoop':
  27460. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  27461. break;
  27462. case 'LineSegments':
  27463. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  27464. break;
  27465. case 'PointCloud':
  27466. case 'Points':
  27467. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  27468. break;
  27469. case 'Sprite':
  27470. object = new Sprite( getMaterial( data.material ) );
  27471. break;
  27472. case 'Group':
  27473. object = new Group();
  27474. break;
  27475. case 'Bone':
  27476. object = new Bone();
  27477. break;
  27478. default:
  27479. object = new Object3D();
  27480. }
  27481. object.uuid = data.uuid;
  27482. if ( data.name !== undefined ) object.name = data.name;
  27483. if ( data.matrix !== undefined ) {
  27484. object.matrix.fromArray( data.matrix );
  27485. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  27486. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  27487. } else {
  27488. if ( data.position !== undefined ) object.position.fromArray( data.position );
  27489. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  27490. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  27491. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  27492. }
  27493. if ( data.up !== undefined ) object.up.fromArray( data.up );
  27494. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  27495. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  27496. if ( data.shadow ) {
  27497. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  27498. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  27499. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  27500. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  27501. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  27502. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  27503. }
  27504. if ( data.visible !== undefined ) object.visible = data.visible;
  27505. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  27506. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  27507. if ( data.userData !== undefined ) object.userData = data.userData;
  27508. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  27509. if ( data.children !== undefined ) {
  27510. const children = data.children;
  27511. for ( let i = 0; i < children.length; i ++ ) {
  27512. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  27513. }
  27514. }
  27515. if ( data.animations !== undefined ) {
  27516. const objectAnimations = data.animations;
  27517. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  27518. const uuid = objectAnimations[ i ];
  27519. object.animations.push( animations[ uuid ] );
  27520. }
  27521. }
  27522. if ( data.type === 'LOD' ) {
  27523. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  27524. const levels = data.levels;
  27525. for ( let l = 0; l < levels.length; l ++ ) {
  27526. const level = levels[ l ];
  27527. const child = object.getObjectByProperty( 'uuid', level.object );
  27528. if ( child !== undefined ) {
  27529. object.addLevel( child, level.distance, level.hysteresis );
  27530. }
  27531. }
  27532. }
  27533. return object;
  27534. }
  27535. bindSkeletons( object, skeletons ) {
  27536. if ( Object.keys( skeletons ).length === 0 ) return;
  27537. object.traverse( function ( child ) {
  27538. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  27539. const skeleton = skeletons[ child.skeleton ];
  27540. if ( skeleton === undefined ) {
  27541. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  27542. } else {
  27543. child.bind( skeleton, child.bindMatrix );
  27544. }
  27545. }
  27546. } );
  27547. }
  27548. bindLightTargets( object ) {
  27549. object.traverse( function ( child ) {
  27550. if ( child.isDirectionalLight || child.isSpotLight ) {
  27551. const uuid = child.target;
  27552. const target = object.getObjectByProperty( 'uuid', uuid );
  27553. if ( target !== undefined ) {
  27554. child.target = target;
  27555. } else {
  27556. child.target = new Object3D();
  27557. }
  27558. }
  27559. } );
  27560. }
  27561. }
  27562. const TEXTURE_MAPPING = {
  27563. UVMapping: UVMapping,
  27564. CubeReflectionMapping: CubeReflectionMapping,
  27565. CubeRefractionMapping: CubeRefractionMapping,
  27566. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  27567. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  27568. CubeUVReflectionMapping: CubeUVReflectionMapping
  27569. };
  27570. const TEXTURE_WRAPPING = {
  27571. RepeatWrapping: RepeatWrapping,
  27572. ClampToEdgeWrapping: ClampToEdgeWrapping,
  27573. MirroredRepeatWrapping: MirroredRepeatWrapping
  27574. };
  27575. const TEXTURE_FILTER = {
  27576. NearestFilter: NearestFilter,
  27577. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  27578. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  27579. LinearFilter: LinearFilter,
  27580. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  27581. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  27582. };
  27583. class ImageBitmapLoader extends Loader {
  27584. constructor( manager ) {
  27585. super( manager );
  27586. this.isImageBitmapLoader = true;
  27587. if ( typeof createImageBitmap === 'undefined' ) {
  27588. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  27589. }
  27590. if ( typeof fetch === 'undefined' ) {
  27591. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  27592. }
  27593. this.options = { premultiplyAlpha: 'none' };
  27594. }
  27595. setOptions( options ) {
  27596. this.options = options;
  27597. return this;
  27598. }
  27599. load( url, onLoad, onProgress, onError ) {
  27600. if ( url === undefined ) url = '';
  27601. if ( this.path !== undefined ) url = this.path + url;
  27602. url = this.manager.resolveURL( url );
  27603. const scope = this;
  27604. const cached = Cache.get( url );
  27605. if ( cached !== undefined ) {
  27606. scope.manager.itemStart( url );
  27607. // If cached is a promise, wait for it to resolve
  27608. if ( cached.then ) {
  27609. cached.then( imageBitmap => {
  27610. if ( onLoad ) onLoad( imageBitmap );
  27611. scope.manager.itemEnd( url );
  27612. } ).catch( e => {
  27613. if ( onError ) onError( e );
  27614. } );
  27615. return;
  27616. }
  27617. // If cached is not a promise (i.e., it's already an imageBitmap)
  27618. setTimeout( function () {
  27619. if ( onLoad ) onLoad( cached );
  27620. scope.manager.itemEnd( url );
  27621. }, 0 );
  27622. return cached;
  27623. }
  27624. const fetchOptions = {};
  27625. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  27626. fetchOptions.headers = this.requestHeader;
  27627. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  27628. return res.blob();
  27629. } ).then( function ( blob ) {
  27630. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  27631. } ).then( function ( imageBitmap ) {
  27632. Cache.add( url, imageBitmap );
  27633. if ( onLoad ) onLoad( imageBitmap );
  27634. scope.manager.itemEnd( url );
  27635. return imageBitmap;
  27636. } ).catch( function ( e ) {
  27637. if ( onError ) onError( e );
  27638. Cache.remove( url );
  27639. scope.manager.itemError( url );
  27640. scope.manager.itemEnd( url );
  27641. } );
  27642. Cache.add( url, promise );
  27643. scope.manager.itemStart( url );
  27644. }
  27645. }
  27646. let _context;
  27647. /**
  27648. * Manages the global audio context in the engine.
  27649. *
  27650. * @hideconstructor
  27651. */
  27652. class AudioContext {
  27653. /**
  27654. * Returns the global native audio context.
  27655. *
  27656. * @return {AudioContext} The native audio context.
  27657. */
  27658. static getContext() {
  27659. if ( _context === undefined ) {
  27660. _context = new ( window.AudioContext || window.webkitAudioContext )();
  27661. }
  27662. return _context;
  27663. }
  27664. /**
  27665. * Allows to set the global native audio context from outside.
  27666. *
  27667. * @param {AudioContext} value - The native context to set.
  27668. */
  27669. static setContext( value ) {
  27670. _context = value;
  27671. }
  27672. }
  27673. class AudioLoader extends Loader {
  27674. constructor( manager ) {
  27675. super( manager );
  27676. }
  27677. load( url, onLoad, onProgress, onError ) {
  27678. const scope = this;
  27679. const loader = new FileLoader( this.manager );
  27680. loader.setResponseType( 'arraybuffer' );
  27681. loader.setPath( this.path );
  27682. loader.setRequestHeader( this.requestHeader );
  27683. loader.setWithCredentials( this.withCredentials );
  27684. loader.load( url, function ( buffer ) {
  27685. try {
  27686. // Create a copy of the buffer. The `decodeAudioData` method
  27687. // detaches the buffer when complete, preventing reuse.
  27688. const bufferCopy = buffer.slice( 0 );
  27689. const context = AudioContext.getContext();
  27690. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  27691. onLoad( audioBuffer );
  27692. } ).catch( handleError );
  27693. } catch ( e ) {
  27694. handleError( e );
  27695. }
  27696. }, onProgress, onError );
  27697. function handleError( e ) {
  27698. if ( onError ) {
  27699. onError( e );
  27700. } else {
  27701. console.error( e );
  27702. }
  27703. scope.manager.itemError( url );
  27704. }
  27705. }
  27706. }
  27707. const _eyeRight = /*@__PURE__*/ new Matrix4();
  27708. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  27709. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  27710. /**
  27711. * A special type of camera that uses two perspective cameras with
  27712. * stereoscopic projection. Can be used for rendering stereo effects
  27713. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  27714. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  27715. */
  27716. class StereoCamera {
  27717. /**
  27718. * Constructs a new stereo camera.
  27719. */
  27720. constructor() {
  27721. /**
  27722. * The type property is used for detecting the object type
  27723. * in context of serialization/deserialization.
  27724. *
  27725. * @type {string}
  27726. * @readonly
  27727. */
  27728. this.type = 'StereoCamera';
  27729. /**
  27730. * The aspect.
  27731. *
  27732. * @type {number}
  27733. * @default 1
  27734. */
  27735. this.aspect = 1;
  27736. /**
  27737. * The eye separation which represents the distance
  27738. * between the left and right camera.
  27739. *
  27740. * @type {number}
  27741. * @default 0.064
  27742. */
  27743. this.eyeSep = 0.064;
  27744. /**
  27745. * The camera representing the left eye. This is added to layer `1` so objects to be
  27746. * rendered by the left camera must also be added to this layer.
  27747. *
  27748. * @type {PerspectiveCamera}
  27749. */
  27750. this.cameraL = new PerspectiveCamera();
  27751. this.cameraL.layers.enable( 1 );
  27752. this.cameraL.matrixAutoUpdate = false;
  27753. /**
  27754. * The camera representing the right eye. This is added to layer `2` so objects to be
  27755. * rendered by the right camera must also be added to this layer.
  27756. *
  27757. * @type {PerspectiveCamera}
  27758. */
  27759. this.cameraR = new PerspectiveCamera();
  27760. this.cameraR.layers.enable( 2 );
  27761. this.cameraR.matrixAutoUpdate = false;
  27762. this._cache = {
  27763. focus: null,
  27764. fov: null,
  27765. aspect: null,
  27766. near: null,
  27767. far: null,
  27768. zoom: null,
  27769. eyeSep: null
  27770. };
  27771. }
  27772. /**
  27773. * Updates the stereo camera based on the given perspective camera.
  27774. *
  27775. * @param {PerspectiveCamera} camera - The perspective camera.
  27776. */
  27777. update( camera ) {
  27778. const cache = this._cache;
  27779. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  27780. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  27781. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  27782. if ( needsUpdate ) {
  27783. cache.focus = camera.focus;
  27784. cache.fov = camera.fov;
  27785. cache.aspect = camera.aspect * this.aspect;
  27786. cache.near = camera.near;
  27787. cache.far = camera.far;
  27788. cache.zoom = camera.zoom;
  27789. cache.eyeSep = this.eyeSep;
  27790. // Off-axis stereoscopic effect based on
  27791. // http://paulbourke.net/stereographics/stereorender/
  27792. _projectionMatrix.copy( camera.projectionMatrix );
  27793. const eyeSepHalf = cache.eyeSep / 2;
  27794. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  27795. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  27796. let xmin, xmax;
  27797. // translate xOffset
  27798. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  27799. _eyeRight.elements[ 12 ] = eyeSepHalf;
  27800. // for left eye
  27801. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  27802. xmax = ymax * cache.aspect + eyeSepOnProjection;
  27803. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  27804. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27805. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  27806. // for right eye
  27807. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  27808. xmax = ymax * cache.aspect - eyeSepOnProjection;
  27809. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  27810. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27811. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  27812. }
  27813. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  27814. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  27815. }
  27816. }
  27817. /**
  27818. * This type of camera can be used in order to efficiently render a scene with a
  27819. * predefined set of cameras. This is an important performance aspect for
  27820. * rendering VR scenes.
  27821. *
  27822. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  27823. * to define for each sub camera the `viewport` property which determines the
  27824. * part of the viewport that is rendered with this camera.
  27825. *
  27826. * @augments PerspectiveCamera
  27827. */
  27828. class ArrayCamera extends PerspectiveCamera {
  27829. /**
  27830. * Constructs a new array camera.
  27831. *
  27832. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  27833. */
  27834. constructor( array = [] ) {
  27835. super();
  27836. /**
  27837. * This flag can be used for type testing.
  27838. *
  27839. * @type {boolean}
  27840. * @readonly
  27841. * @default true
  27842. */
  27843. this.isArrayCamera = true;
  27844. /**
  27845. * An array of perspective sub cameras.
  27846. *
  27847. * @type {Array<PerspectiveCamera>}
  27848. */
  27849. this.cameras = array;
  27850. this.index = 0;
  27851. }
  27852. }
  27853. class Clock {
  27854. constructor( autoStart = true ) {
  27855. this.autoStart = autoStart;
  27856. this.startTime = 0;
  27857. this.oldTime = 0;
  27858. this.elapsedTime = 0;
  27859. this.running = false;
  27860. }
  27861. start() {
  27862. this.startTime = now();
  27863. this.oldTime = this.startTime;
  27864. this.elapsedTime = 0;
  27865. this.running = true;
  27866. }
  27867. stop() {
  27868. this.getElapsedTime();
  27869. this.running = false;
  27870. this.autoStart = false;
  27871. }
  27872. getElapsedTime() {
  27873. this.getDelta();
  27874. return this.elapsedTime;
  27875. }
  27876. getDelta() {
  27877. let diff = 0;
  27878. if ( this.autoStart && ! this.running ) {
  27879. this.start();
  27880. return 0;
  27881. }
  27882. if ( this.running ) {
  27883. const newTime = now();
  27884. diff = ( newTime - this.oldTime ) / 1000;
  27885. this.oldTime = newTime;
  27886. this.elapsedTime += diff;
  27887. }
  27888. return diff;
  27889. }
  27890. }
  27891. function now() {
  27892. return performance.now();
  27893. }
  27894. const _position$1 = /*@__PURE__*/ new Vector3();
  27895. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  27896. const _scale$1 = /*@__PURE__*/ new Vector3();
  27897. const _orientation$1 = /*@__PURE__*/ new Vector3();
  27898. /**
  27899. * The class represents a virtual listener of the all positional and non-positional audio effects
  27900. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  27901. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  27902. *
  27903. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  27904. * camera represents the 3D transformation of the listener.
  27905. *
  27906. * @augments Object3D
  27907. */
  27908. class AudioListener extends Object3D {
  27909. /**
  27910. * Constructs a new audio listener.
  27911. */
  27912. constructor() {
  27913. super();
  27914. this.type = 'AudioListener';
  27915. /**
  27916. * The native audio context.
  27917. *
  27918. * @type {AudioContext}
  27919. * @readonly
  27920. */
  27921. this.context = AudioContext.getContext();
  27922. /**
  27923. * The gain node used for volume control.
  27924. *
  27925. * @type {GainNode}
  27926. * @readonly
  27927. */
  27928. this.gain = this.context.createGain();
  27929. this.gain.connect( this.context.destination );
  27930. /**
  27931. * An optional filter.
  27932. *
  27933. * Defined via {@AudioListener#setFilter}.
  27934. *
  27935. * @type {?AudioNode}
  27936. * @default null
  27937. * @readonly
  27938. */
  27939. this.filter = null;
  27940. /**
  27941. * Time delta values required for `linearRampToValueAtTime()` usage.
  27942. *
  27943. * @type {number}
  27944. * @default 0
  27945. * @readonly
  27946. */
  27947. this.timeDelta = 0;
  27948. // private
  27949. this._clock = new Clock();
  27950. }
  27951. /**
  27952. * Returns the listener's input node.
  27953. *
  27954. * This method is used by other audio nodes to connect to this listener.
  27955. *
  27956. * @return {GainNode} The input node.
  27957. */
  27958. getInput() {
  27959. return this.gain;
  27960. }
  27961. /**
  27962. * Removes the current filter from this listener.
  27963. *
  27964. * @return {AudioListener} A reference to this listener.
  27965. */
  27966. removeFilter() {
  27967. if ( this.filter !== null ) {
  27968. this.gain.disconnect( this.filter );
  27969. this.filter.disconnect( this.context.destination );
  27970. this.gain.connect( this.context.destination );
  27971. this.filter = null;
  27972. }
  27973. return this;
  27974. }
  27975. /**
  27976. * Returns the current set filter.
  27977. *
  27978. * @return {AudioNode} The filter.
  27979. */
  27980. getFilter() {
  27981. return this.filter;
  27982. }
  27983. /**
  27984. * Sets the given filter to this listener.
  27985. *
  27986. * @param {AudioNode} value - The filter to set.
  27987. * @return {AudioListener} A reference to this listener.
  27988. */
  27989. setFilter( value ) {
  27990. if ( this.filter !== null ) {
  27991. this.gain.disconnect( this.filter );
  27992. this.filter.disconnect( this.context.destination );
  27993. } else {
  27994. this.gain.disconnect( this.context.destination );
  27995. }
  27996. this.filter = value;
  27997. this.gain.connect( this.filter );
  27998. this.filter.connect( this.context.destination );
  27999. return this;
  28000. }
  28001. /**
  28002. * Returns the applications master volume.
  28003. *
  28004. * @return {number} The master volume.
  28005. */
  28006. getMasterVolume() {
  28007. return this.gain.gain.value;
  28008. }
  28009. /**
  28010. * Sets the applications master volume. This volume setting affects
  28011. * all audio nodes in the scene.
  28012. *
  28013. * @param {number} value - The master volume to set.
  28014. * @return {AudioListener} A reference to this listener.
  28015. */
  28016. setMasterVolume( value ) {
  28017. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28018. return this;
  28019. }
  28020. updateMatrixWorld( force ) {
  28021. super.updateMatrixWorld( force );
  28022. const listener = this.context.listener;
  28023. const up = this.up;
  28024. this.timeDelta = this._clock.getDelta();
  28025. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  28026. _orientation$1.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  28027. if ( listener.positionX ) {
  28028. // code path for Chrome (see #14393)
  28029. const endTime = this.context.currentTime + this.timeDelta;
  28030. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  28031. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  28032. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  28033. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  28034. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  28035. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  28036. listener.upX.linearRampToValueAtTime( up.x, endTime );
  28037. listener.upY.linearRampToValueAtTime( up.y, endTime );
  28038. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  28039. } else {
  28040. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  28041. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  28042. }
  28043. }
  28044. }
  28045. /**
  28046. * Represents a non-positional ( global ) audio object.
  28047. *
  28048. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  28049. *
  28050. * ```js
  28051. * // create an AudioListener and add it to the camera
  28052. * const listener = new THREE.AudioListener();
  28053. * camera.add( listener );
  28054. *
  28055. * // create a global audio source
  28056. * const sound = new THREE.Audio( listener );
  28057. *
  28058. * // load a sound and set it as the Audio object's buffer
  28059. * const audioLoader = new THREE.AudioLoader();
  28060. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  28061. * sound.setBuffer( buffer );
  28062. * sound.setLoop( true );
  28063. * sound.setVolume( 0.5 );
  28064. * sound.play();
  28065. * });
  28066. * ```
  28067. *
  28068. * @augments Object3D
  28069. */
  28070. class Audio extends Object3D {
  28071. /**
  28072. * Constructs a new audio.
  28073. *
  28074. * @param {AudioListener} listener - The global audio listener.
  28075. */
  28076. constructor( listener ) {
  28077. super();
  28078. this.type = 'Audio';
  28079. /**
  28080. * The global audio listener.
  28081. *
  28082. * @type {AudioListener}
  28083. * @readonly
  28084. */
  28085. this.listener = listener;
  28086. /**
  28087. * The audio context.
  28088. *
  28089. * @type {AudioContext}
  28090. * @readonly
  28091. */
  28092. this.context = listener.context;
  28093. /**
  28094. * The gain node used for volume control.
  28095. *
  28096. * @type {GainNode}
  28097. * @readonly
  28098. */
  28099. this.gain = this.context.createGain();
  28100. this.gain.connect( listener.getInput() );
  28101. /**
  28102. * Whether to start playback automatically or not.
  28103. *
  28104. * @type {boolean}
  28105. * @default false
  28106. */
  28107. this.autoplay = false;
  28108. /**
  28109. * A reference to an audio buffer.
  28110. *
  28111. * Defined via {@link Audio#setBuffer}.
  28112. *
  28113. * @type {?AudioBuffer}
  28114. * @default null
  28115. * @readonly
  28116. */
  28117. this.buffer = null;
  28118. /**
  28119. * Modify pitch, measured in cents. +/- 100 is a semitone.
  28120. * +/- 1200 is an octave.
  28121. *
  28122. * Defined via {@link Audio#setDetune}.
  28123. *
  28124. * @type {number}
  28125. * @default 0
  28126. * @readonly
  28127. */
  28128. this.detune = 0;
  28129. /**
  28130. * Whether the audio should loop or not.
  28131. *
  28132. * Defined via {@link Audio#setLoop}.
  28133. *
  28134. * @type {boolean}
  28135. * @default false
  28136. * @readonly
  28137. */
  28138. this.loop = false;
  28139. /**
  28140. * Defines where in the audio buffer the replay should
  28141. * start, in seconds.
  28142. *
  28143. * @type {number}
  28144. * @default 0
  28145. */
  28146. this.loopStart = 0;
  28147. /**
  28148. * Defines where in the audio buffer the replay should
  28149. * stop, in seconds.
  28150. *
  28151. * @type {number}
  28152. * @default 0
  28153. */
  28154. this.loopEnd = 0;
  28155. /**
  28156. * An offset to the time within the audio buffer the playback
  28157. * should begin, in seconds.
  28158. *
  28159. * @type {number}
  28160. * @default 0
  28161. */
  28162. this.offset = 0;
  28163. /**
  28164. * Overrides the default duration of the audio.
  28165. *
  28166. * @type {undefined|number}
  28167. * @default undefined
  28168. */
  28169. this.duration = undefined;
  28170. /**
  28171. * The playback speed.
  28172. *
  28173. * Defined via {@link Audio#setPlaybackRate}.
  28174. *
  28175. * @type {number}
  28176. * @readonly
  28177. * @default 1
  28178. */
  28179. this.playbackRate = 1;
  28180. /**
  28181. * Indicates whether the audio is playing or not.
  28182. *
  28183. * This flag will be automatically set when using {@link Audio#play},
  28184. * {@link Audio#pause}, {@link Audio#stop}.
  28185. *
  28186. * @type {boolean}
  28187. * @readonly
  28188. * @default false
  28189. */
  28190. this.isPlaying = false;
  28191. /**
  28192. * Indicates whether the audio playback can be controlled
  28193. * with method like {@link Audio#play} or {@link Audio#pause}.
  28194. *
  28195. * This flag will be automatically set when audio sources are
  28196. * defined.
  28197. *
  28198. * @type {boolean}
  28199. * @readonly
  28200. * @default true
  28201. */
  28202. this.hasPlaybackControl = true;
  28203. /**
  28204. * Holds a reference to the current audio source.
  28205. *
  28206. * The property is automatically by one of the `set*()` methods.
  28207. *
  28208. * @type {?AudioNode}
  28209. * @readonly
  28210. * @default null
  28211. */
  28212. this.source = null;
  28213. /**
  28214. * Defines the source type.
  28215. *
  28216. * The property is automatically by one of the `set*()` methods.
  28217. *
  28218. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  28219. * @readonly
  28220. * @default 'empty'
  28221. */
  28222. this.sourceType = 'empty';
  28223. this._startedAt = 0;
  28224. this._progress = 0;
  28225. this._connected = false;
  28226. /**
  28227. * Can be used to apply a variety of low-order filters to create
  28228. * more complex sound effects e.g. via `BiquadFilterNode`.
  28229. *
  28230. * The property is automatically set by {@link Audio#setFilters}.
  28231. *
  28232. * @type {Array<AudioNode>}
  28233. * @readonly
  28234. */
  28235. this.filters = [];
  28236. }
  28237. /**
  28238. * Returns the output audio node.
  28239. *
  28240. * @return {GainNode} The output node.
  28241. */
  28242. getOutput() {
  28243. return this.gain;
  28244. }
  28245. /**
  28246. * Sets the given audio node as the source of this instance.
  28247. *
  28248. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  28249. *
  28250. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  28251. * @return {Audio} A reference to this instance.
  28252. */
  28253. setNodeSource( audioNode ) {
  28254. this.hasPlaybackControl = false;
  28255. this.sourceType = 'audioNode';
  28256. this.source = audioNode;
  28257. this.connect();
  28258. return this;
  28259. }
  28260. /**
  28261. * Sets the given media element as the source of this instance.
  28262. *
  28263. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  28264. *
  28265. * @param {HTMLMediaElement} mediaElement - The media element.
  28266. * @return {Audio} A reference to this instance.
  28267. */
  28268. setMediaElementSource( mediaElement ) {
  28269. this.hasPlaybackControl = false;
  28270. this.sourceType = 'mediaNode';
  28271. this.source = this.context.createMediaElementSource( mediaElement );
  28272. this.connect();
  28273. return this;
  28274. }
  28275. /**
  28276. * Sets the given media stream as the source of this instance.
  28277. *
  28278. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  28279. *
  28280. * @param {MediaStream} mediaStream - The media stream.
  28281. * @return {Audio} A reference to this instance.
  28282. */
  28283. setMediaStreamSource( mediaStream ) {
  28284. this.hasPlaybackControl = false;
  28285. this.sourceType = 'mediaStreamNode';
  28286. this.source = this.context.createMediaStreamSource( mediaStream );
  28287. this.connect();
  28288. return this;
  28289. }
  28290. /**
  28291. * Sets the given audio buffer as the source of this instance.
  28292. *
  28293. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  28294. *
  28295. * @param {AudioBuffer} audioBuffer - The audio buffer.
  28296. * @return {Audio} A reference to this instance.
  28297. */
  28298. setBuffer( audioBuffer ) {
  28299. this.buffer = audioBuffer;
  28300. this.sourceType = 'buffer';
  28301. if ( this.autoplay ) this.play();
  28302. return this;
  28303. }
  28304. /**
  28305. * Starts the playback of the audio.
  28306. *
  28307. * Can only be used with compatible audio sources that allow playback control.
  28308. *
  28309. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  28310. * @return {Audio|undefined} A reference to this instance.
  28311. */
  28312. play( delay = 0 ) {
  28313. if ( this.isPlaying === true ) {
  28314. console.warn( 'THREE.Audio: Audio is already playing.' );
  28315. return;
  28316. }
  28317. if ( this.hasPlaybackControl === false ) {
  28318. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28319. return;
  28320. }
  28321. this._startedAt = this.context.currentTime + delay;
  28322. const source = this.context.createBufferSource();
  28323. source.buffer = this.buffer;
  28324. source.loop = this.loop;
  28325. source.loopStart = this.loopStart;
  28326. source.loopEnd = this.loopEnd;
  28327. source.onended = this.onEnded.bind( this );
  28328. source.start( this._startedAt, this._progress + this.offset, this.duration );
  28329. this.isPlaying = true;
  28330. this.source = source;
  28331. this.setDetune( this.detune );
  28332. this.setPlaybackRate( this.playbackRate );
  28333. return this.connect();
  28334. }
  28335. /**
  28336. * Pauses the playback of the audio.
  28337. *
  28338. * Can only be used with compatible audio sources that allow playback control.
  28339. *
  28340. * @return {Audio|undefined} A reference to this instance.
  28341. */
  28342. pause() {
  28343. if ( this.hasPlaybackControl === false ) {
  28344. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28345. return;
  28346. }
  28347. if ( this.isPlaying === true ) {
  28348. // update current progress
  28349. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  28350. if ( this.loop === true ) {
  28351. // ensure _progress does not exceed duration with looped audios
  28352. this._progress = this._progress % ( this.duration || this.buffer.duration );
  28353. }
  28354. this.source.stop();
  28355. this.source.onended = null;
  28356. this.isPlaying = false;
  28357. }
  28358. return this;
  28359. }
  28360. /**
  28361. * Stops the playback of the audio.
  28362. *
  28363. * Can only be used with compatible audio sources that allow playback control.
  28364. *
  28365. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  28366. * @return {Audio|undefined} A reference to this instance.
  28367. */
  28368. stop( delay = 0 ) {
  28369. if ( this.hasPlaybackControl === false ) {
  28370. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28371. return;
  28372. }
  28373. this._progress = 0;
  28374. if ( this.source !== null ) {
  28375. this.source.stop( this.context.currentTime + delay );
  28376. this.source.onended = null;
  28377. }
  28378. this.isPlaying = false;
  28379. return this;
  28380. }
  28381. /**
  28382. * Connects to the audio source. This is used internally on
  28383. * initialisation and when setting / removing filters.
  28384. *
  28385. * @return {Audio} A reference to this instance.
  28386. */
  28387. connect() {
  28388. if ( this.filters.length > 0 ) {
  28389. this.source.connect( this.filters[ 0 ] );
  28390. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28391. this.filters[ i - 1 ].connect( this.filters[ i ] );
  28392. }
  28393. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  28394. } else {
  28395. this.source.connect( this.getOutput() );
  28396. }
  28397. this._connected = true;
  28398. return this;
  28399. }
  28400. /**
  28401. * Disconnects to the audio source. This is used internally on
  28402. * initialisation and when setting / removing filters.
  28403. *
  28404. * @return {Audio|undefined} A reference to this instance.
  28405. */
  28406. disconnect() {
  28407. if ( this._connected === false ) {
  28408. return;
  28409. }
  28410. if ( this.filters.length > 0 ) {
  28411. this.source.disconnect( this.filters[ 0 ] );
  28412. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28413. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  28414. }
  28415. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  28416. } else {
  28417. this.source.disconnect( this.getOutput() );
  28418. }
  28419. this._connected = false;
  28420. return this;
  28421. }
  28422. /**
  28423. * Returns the current set filters.
  28424. *
  28425. * @return {Array<AudioNode>} The list of filters.
  28426. */
  28427. getFilters() {
  28428. return this.filters;
  28429. }
  28430. /**
  28431. * Sets an array of filters and connects them with the audio source.
  28432. *
  28433. * @param {Array<AudioNode>} [value] - A list of filters.
  28434. * @return {Audio} A reference to this instance.
  28435. */
  28436. setFilters( value ) {
  28437. if ( ! value ) value = [];
  28438. if ( this._connected === true ) {
  28439. this.disconnect();
  28440. this.filters = value.slice();
  28441. this.connect();
  28442. } else {
  28443. this.filters = value.slice();
  28444. }
  28445. return this;
  28446. }
  28447. /**
  28448. * Defines the detuning of oscillation in cents.
  28449. *
  28450. * @param {number} value - The detuning of oscillation in cents.
  28451. * @return {Audio} A reference to this instance.
  28452. */
  28453. setDetune( value ) {
  28454. this.detune = value;
  28455. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  28456. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  28457. }
  28458. return this;
  28459. }
  28460. /**
  28461. * Returns the detuning of oscillation in cents.
  28462. *
  28463. * @return {number} The detuning of oscillation in cents.
  28464. */
  28465. getDetune() {
  28466. return this.detune;
  28467. }
  28468. /**
  28469. * Returns the first filter in the list of filters.
  28470. *
  28471. * @return {AudioNode|undefined} The first filter in the list of filters.
  28472. */
  28473. getFilter() {
  28474. return this.getFilters()[ 0 ];
  28475. }
  28476. /**
  28477. * Applies a single filter node to the audio.
  28478. *
  28479. * @param {AudioNode} [filter] - The filter to set.
  28480. * @return {Audio} A reference to this instance.
  28481. */
  28482. setFilter( filter ) {
  28483. return this.setFilters( filter ? [ filter ] : [] );
  28484. }
  28485. /**
  28486. * Sets the playback rate.
  28487. *
  28488. * Can only be used with compatible audio sources that allow playback control.
  28489. *
  28490. * @param {number} [value] - The playback rate to set.
  28491. * @return {Audio|undefined} A reference to this instance.
  28492. */
  28493. setPlaybackRate( value ) {
  28494. if ( this.hasPlaybackControl === false ) {
  28495. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28496. return;
  28497. }
  28498. this.playbackRate = value;
  28499. if ( this.isPlaying === true ) {
  28500. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  28501. }
  28502. return this;
  28503. }
  28504. /**
  28505. * Returns the current playback rate.
  28506. * @return {number} The playback rate.
  28507. */
  28508. getPlaybackRate() {
  28509. return this.playbackRate;
  28510. }
  28511. /**
  28512. * Automatically called when playback finished.
  28513. */
  28514. onEnded() {
  28515. this.isPlaying = false;
  28516. this._progress = 0;
  28517. }
  28518. /**
  28519. * Returns the loop flag.
  28520. *
  28521. * Can only be used with compatible audio sources that allow playback control.
  28522. *
  28523. * @return {boolean} Whether the audio should loop or not.
  28524. */
  28525. getLoop() {
  28526. if ( this.hasPlaybackControl === false ) {
  28527. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28528. return false;
  28529. }
  28530. return this.loop;
  28531. }
  28532. /**
  28533. * Sets the loop flag.
  28534. *
  28535. * Can only be used with compatible audio sources that allow playback control.
  28536. *
  28537. * @param {boolean} value - Whether the audio should loop or not.
  28538. * @return {Audio|undefined} A reference to this instance.
  28539. */
  28540. setLoop( value ) {
  28541. if ( this.hasPlaybackControl === false ) {
  28542. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28543. return;
  28544. }
  28545. this.loop = value;
  28546. if ( this.isPlaying === true ) {
  28547. this.source.loop = this.loop;
  28548. }
  28549. return this;
  28550. }
  28551. /**
  28552. * Sets the loop start value which defines where in the audio buffer the replay should
  28553. * start, in seconds.
  28554. *
  28555. * @param {number} value - The loop start value.
  28556. * @return {Audio} A reference to this instance.
  28557. */
  28558. setLoopStart( value ) {
  28559. this.loopStart = value;
  28560. return this;
  28561. }
  28562. /**
  28563. * Sets the loop end value which defines where in the audio buffer the replay should
  28564. * stop, in seconds.
  28565. *
  28566. * @param {number} value - The loop end value.
  28567. * @return {Audio} A reference to this instance.
  28568. */
  28569. setLoopEnd( value ) {
  28570. this.loopEnd = value;
  28571. return this;
  28572. }
  28573. /**
  28574. * Returns the volume.
  28575. *
  28576. * @return {number} The volume.
  28577. */
  28578. getVolume() {
  28579. return this.gain.gain.value;
  28580. }
  28581. /**
  28582. * Sets the volume.
  28583. *
  28584. * @param {number} value - The volume to set.
  28585. * @return {Audio} A reference to this instance.
  28586. */
  28587. setVolume( value ) {
  28588. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28589. return this;
  28590. }
  28591. copy( source, recursive ) {
  28592. super.copy( source, recursive );
  28593. if ( source.sourceType !== 'buffer' ) {
  28594. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  28595. return this;
  28596. }
  28597. this.autoplay = source.autoplay;
  28598. this.buffer = source.buffer;
  28599. this.detune = source.detune;
  28600. this.loop = source.loop;
  28601. this.loopStart = source.loopStart;
  28602. this.loopEnd = source.loopEnd;
  28603. this.offset = source.offset;
  28604. this.duration = source.duration;
  28605. this.playbackRate = source.playbackRate;
  28606. this.hasPlaybackControl = source.hasPlaybackControl;
  28607. this.sourceType = source.sourceType;
  28608. this.filters = source.filters.slice();
  28609. return this;
  28610. }
  28611. clone( recursive ) {
  28612. return new this.constructor( this.listener ).copy( this, recursive );
  28613. }
  28614. }
  28615. const _position = /*@__PURE__*/ new Vector3();
  28616. const _quaternion = /*@__PURE__*/ new Quaternion();
  28617. const _scale = /*@__PURE__*/ new Vector3();
  28618. const _orientation = /*@__PURE__*/ new Vector3();
  28619. /**
  28620. * Represents a positional audio object.
  28621. *
  28622. * ```js
  28623. * // create an AudioListener and add it to the camera
  28624. * const listener = new THREE.AudioListener();
  28625. * camera.add( listener );
  28626. *
  28627. * // create the PositionalAudio object (passing in the listener)
  28628. * const sound = new THREE.PositionalAudio( listener );
  28629. *
  28630. * // load a sound and set it as the PositionalAudio object's buffer
  28631. * const audioLoader = new THREE.AudioLoader();
  28632. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  28633. * sound.setBuffer( buffer );
  28634. * sound.setRefDistance( 20 );
  28635. * sound.play();
  28636. * });
  28637. *
  28638. * // create an object for the sound to play from
  28639. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  28640. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  28641. * const mesh = new THREE.Mesh( sphere, material );
  28642. * scene.add( mesh );
  28643. *
  28644. * // finally add the sound to the mesh
  28645. * mesh.add( sound );
  28646. *
  28647. * @augments Audio
  28648. */
  28649. class PositionalAudio extends Audio {
  28650. /**
  28651. * Constructs a positional audio.
  28652. *
  28653. * @param {AudioListener} listener - The global audio listener.
  28654. */
  28655. constructor( listener ) {
  28656. super( listener );
  28657. /**
  28658. * The panner node represents the location, direction, and behavior of an audio
  28659. * source in 3D space.
  28660. *
  28661. * @type {PannerNode}
  28662. * @readonly
  28663. */
  28664. this.panner = this.context.createPanner();
  28665. this.panner.panningModel = 'HRTF';
  28666. this.panner.connect( this.gain );
  28667. }
  28668. connect() {
  28669. super.connect();
  28670. this.panner.connect( this.gain );
  28671. return this;
  28672. }
  28673. disconnect() {
  28674. super.disconnect();
  28675. this.panner.disconnect( this.gain );
  28676. return this;
  28677. }
  28678. getOutput() {
  28679. return this.panner;
  28680. }
  28681. /**
  28682. * Returns the current reference distance.
  28683. *
  28684. * @return {number} The reference distance.
  28685. */
  28686. getRefDistance() {
  28687. return this.panner.refDistance;
  28688. }
  28689. /**
  28690. * Defines the reference distance for reducing volume as the audio source moves
  28691. * further from the listener – i.e. the distance at which the volume reduction
  28692. * starts taking effect.
  28693. *
  28694. * @param {number} value - The reference distance to set.
  28695. * @return {Audio} A reference to this instance.
  28696. */
  28697. setRefDistance( value ) {
  28698. this.panner.refDistance = value;
  28699. return this;
  28700. }
  28701. /**
  28702. * Returns the current rolloff factor.
  28703. *
  28704. * @return {number} The rolloff factor.
  28705. */
  28706. getRolloffFactor() {
  28707. return this.panner.rolloffFactor;
  28708. }
  28709. /**
  28710. * Defines how quickly the volume is reduced as the source moves away from the listener.
  28711. *
  28712. * @param {number} value - The rolloff factor.
  28713. * @return {Audio} A reference to this instance.
  28714. */
  28715. setRolloffFactor( value ) {
  28716. this.panner.rolloffFactor = value;
  28717. return this;
  28718. }
  28719. /**
  28720. * Returns the current distance model.
  28721. *
  28722. * @return {('linear'|'inverse'|'exponential')} The distance model.
  28723. */
  28724. getDistanceModel() {
  28725. return this.panner.distanceModel;
  28726. }
  28727. /**
  28728. * Defines which algorithm to use to reduce the volume of the audio source
  28729. * as it moves away from the listener.
  28730. *
  28731. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  28732. * for more details.
  28733. *
  28734. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  28735. * @return {Audio} A reference to this instance.
  28736. */
  28737. setDistanceModel( value ) {
  28738. this.panner.distanceModel = value;
  28739. return this;
  28740. }
  28741. /**
  28742. * Returns the current max distance.
  28743. *
  28744. * @return {number} The max distance.
  28745. */
  28746. getMaxDistance() {
  28747. return this.panner.maxDistance;
  28748. }
  28749. /**
  28750. * Defines the maximum distance between the audio source and the listener,
  28751. * after which the volume is not reduced any further.
  28752. *
  28753. * This value is used only by the `linear` distance model.
  28754. *
  28755. * @param {number} value - The max distance.
  28756. * @return {Audio} A reference to this instance.
  28757. */
  28758. setMaxDistance( value ) {
  28759. this.panner.maxDistance = value;
  28760. return this;
  28761. }
  28762. /**
  28763. * Sets the directional cone in which the audio can be listened.
  28764. *
  28765. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  28766. * @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.
  28767. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  28768. * @return {Audio} A reference to this instance.
  28769. */
  28770. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  28771. this.panner.coneInnerAngle = coneInnerAngle;
  28772. this.panner.coneOuterAngle = coneOuterAngle;
  28773. this.panner.coneOuterGain = coneOuterGain;
  28774. return this;
  28775. }
  28776. updateMatrixWorld( force ) {
  28777. super.updateMatrixWorld( force );
  28778. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  28779. this.matrixWorld.decompose( _position, _quaternion, _scale );
  28780. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  28781. const panner = this.panner;
  28782. if ( panner.positionX ) {
  28783. // code path for Chrome and Firefox (see #14393)
  28784. const endTime = this.context.currentTime + this.listener.timeDelta;
  28785. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  28786. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  28787. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  28788. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  28789. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  28790. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  28791. } else {
  28792. panner.setPosition( _position.x, _position.y, _position.z );
  28793. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  28794. }
  28795. }
  28796. }
  28797. /**
  28798. * This class can be used to analyse audio data.
  28799. *
  28800. * ```js
  28801. * // create an AudioListener and add it to the camera
  28802. * const listener = new THREE.AudioListener();
  28803. * camera.add( listener );
  28804. *
  28805. * // create an Audio source
  28806. * const sound = new THREE.Audio( listener );
  28807. *
  28808. * // load a sound and set it as the Audio object's buffer
  28809. * const audioLoader = new THREE.AudioLoader();
  28810. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  28811. * sound.setBuffer( buffer );
  28812. * sound.setLoop(true);
  28813. * sound.setVolume(0.5);
  28814. * sound.play();
  28815. * });
  28816. *
  28817. * // create an AudioAnalyser, passing in the sound and desired fftSize
  28818. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  28819. *
  28820. * // get the average frequency of the sound
  28821. * const data = analyser.getAverageFrequency();
  28822. * ```
  28823. */
  28824. class AudioAnalyser {
  28825. /**
  28826. * Constructs a new audio analyzer.
  28827. *
  28828. * @param {Audio} audio - The audio to analyze.
  28829. * @param {Audio} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  28830. */
  28831. constructor( audio, fftSize = 2048 ) {
  28832. /**
  28833. * The global audio listener.
  28834. *
  28835. * @type {AnalyserNode}
  28836. */
  28837. this.analyser = audio.context.createAnalyser();
  28838. this.analyser.fftSize = fftSize;
  28839. /**
  28840. * Holds the analyzed data.
  28841. *
  28842. * @type {Uint8Array}
  28843. */
  28844. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  28845. audio.getOutput().connect( this.analyser );
  28846. }
  28847. /**
  28848. * Returns an array with frequency data of the audio.
  28849. *
  28850. * Each item in the array represents the decibel value for a specific frequency.
  28851. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  28852. * For example, for 48000 sample rate, the last item of the array will represent
  28853. * the decibel value for 24000 Hz.
  28854. *
  28855. * @return {Uint8Array} The frequency data.
  28856. */
  28857. getFrequencyData() {
  28858. this.analyser.getByteFrequencyData( this.data );
  28859. return this.data;
  28860. }
  28861. /**
  28862. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  28863. *
  28864. * @return {number} The average frequency.
  28865. */
  28866. getAverageFrequency() {
  28867. let value = 0;
  28868. const data = this.getFrequencyData();
  28869. for ( let i = 0; i < data.length; i ++ ) {
  28870. value += data[ i ];
  28871. }
  28872. return value / data.length;
  28873. }
  28874. }
  28875. class PropertyMixer {
  28876. constructor( binding, typeName, valueSize ) {
  28877. this.binding = binding;
  28878. this.valueSize = valueSize;
  28879. let mixFunction,
  28880. mixFunctionAdditive,
  28881. setIdentity;
  28882. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  28883. //
  28884. // interpolators can use .buffer as their .result
  28885. // the data then goes to 'incoming'
  28886. //
  28887. // 'accu0' and 'accu1' are used frame-interleaved for
  28888. // the cumulative result and are compared to detect
  28889. // changes
  28890. //
  28891. // 'orig' stores the original state of the property
  28892. //
  28893. // 'add' is used for additive cumulative results
  28894. //
  28895. // 'work' is optional and is only present for quaternion types. It is used
  28896. // to store intermediate quaternion multiplication results
  28897. switch ( typeName ) {
  28898. case 'quaternion':
  28899. mixFunction = this._slerp;
  28900. mixFunctionAdditive = this._slerpAdditive;
  28901. setIdentity = this._setAdditiveIdentityQuaternion;
  28902. this.buffer = new Float64Array( valueSize * 6 );
  28903. this._workIndex = 5;
  28904. break;
  28905. case 'string':
  28906. case 'bool':
  28907. mixFunction = this._select;
  28908. // Use the regular mix function and for additive on these types,
  28909. // additive is not relevant for non-numeric types
  28910. mixFunctionAdditive = this._select;
  28911. setIdentity = this._setAdditiveIdentityOther;
  28912. this.buffer = new Array( valueSize * 5 );
  28913. break;
  28914. default:
  28915. mixFunction = this._lerp;
  28916. mixFunctionAdditive = this._lerpAdditive;
  28917. setIdentity = this._setAdditiveIdentityNumeric;
  28918. this.buffer = new Float64Array( valueSize * 5 );
  28919. }
  28920. this._mixBufferRegion = mixFunction;
  28921. this._mixBufferRegionAdditive = mixFunctionAdditive;
  28922. this._setIdentity = setIdentity;
  28923. this._origIndex = 3;
  28924. this._addIndex = 4;
  28925. this.cumulativeWeight = 0;
  28926. this.cumulativeWeightAdditive = 0;
  28927. this.useCount = 0;
  28928. this.referenceCount = 0;
  28929. }
  28930. // accumulate data in the 'incoming' region into 'accu<i>'
  28931. accumulate( accuIndex, weight ) {
  28932. // note: happily accumulating nothing when weight = 0, the caller knows
  28933. // the weight and shouldn't have made the call in the first place
  28934. const buffer = this.buffer,
  28935. stride = this.valueSize,
  28936. offset = accuIndex * stride + stride;
  28937. let currentWeight = this.cumulativeWeight;
  28938. if ( currentWeight === 0 ) {
  28939. // accuN := incoming * weight
  28940. for ( let i = 0; i !== stride; ++ i ) {
  28941. buffer[ offset + i ] = buffer[ i ];
  28942. }
  28943. currentWeight = weight;
  28944. } else {
  28945. // accuN := accuN + incoming * weight
  28946. currentWeight += weight;
  28947. const mix = weight / currentWeight;
  28948. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  28949. }
  28950. this.cumulativeWeight = currentWeight;
  28951. }
  28952. // accumulate data in the 'incoming' region into 'add'
  28953. accumulateAdditive( weight ) {
  28954. const buffer = this.buffer,
  28955. stride = this.valueSize,
  28956. offset = stride * this._addIndex;
  28957. if ( this.cumulativeWeightAdditive === 0 ) {
  28958. // add = identity
  28959. this._setIdentity();
  28960. }
  28961. // add := add + incoming * weight
  28962. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  28963. this.cumulativeWeightAdditive += weight;
  28964. }
  28965. // apply the state of 'accu<i>' to the binding when accus differ
  28966. apply( accuIndex ) {
  28967. const stride = this.valueSize,
  28968. buffer = this.buffer,
  28969. offset = accuIndex * stride + stride,
  28970. weight = this.cumulativeWeight,
  28971. weightAdditive = this.cumulativeWeightAdditive,
  28972. binding = this.binding;
  28973. this.cumulativeWeight = 0;
  28974. this.cumulativeWeightAdditive = 0;
  28975. if ( weight < 1 ) {
  28976. // accuN := accuN + original * ( 1 - cumulativeWeight )
  28977. const originalValueOffset = stride * this._origIndex;
  28978. this._mixBufferRegion(
  28979. buffer, offset, originalValueOffset, 1 - weight, stride );
  28980. }
  28981. if ( weightAdditive > 0 ) {
  28982. // accuN := accuN + additive accuN
  28983. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  28984. }
  28985. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  28986. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  28987. // value has changed -> update scene graph
  28988. binding.setValue( buffer, offset );
  28989. break;
  28990. }
  28991. }
  28992. }
  28993. // remember the state of the bound property and copy it to both accus
  28994. saveOriginalState() {
  28995. const binding = this.binding;
  28996. const buffer = this.buffer,
  28997. stride = this.valueSize,
  28998. originalValueOffset = stride * this._origIndex;
  28999. binding.getValue( buffer, originalValueOffset );
  29000. // accu[0..1] := orig -- initially detect changes against the original
  29001. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  29002. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  29003. }
  29004. // Add to identity for additive
  29005. this._setIdentity();
  29006. this.cumulativeWeight = 0;
  29007. this.cumulativeWeightAdditive = 0;
  29008. }
  29009. // apply the state previously taken via 'saveOriginalState' to the binding
  29010. restoreOriginalState() {
  29011. const originalValueOffset = this.valueSize * 3;
  29012. this.binding.setValue( this.buffer, originalValueOffset );
  29013. }
  29014. _setAdditiveIdentityNumeric() {
  29015. const startIndex = this._addIndex * this.valueSize;
  29016. const endIndex = startIndex + this.valueSize;
  29017. for ( let i = startIndex; i < endIndex; i ++ ) {
  29018. this.buffer[ i ] = 0;
  29019. }
  29020. }
  29021. _setAdditiveIdentityQuaternion() {
  29022. this._setAdditiveIdentityNumeric();
  29023. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  29024. }
  29025. _setAdditiveIdentityOther() {
  29026. const startIndex = this._origIndex * this.valueSize;
  29027. const targetIndex = this._addIndex * this.valueSize;
  29028. for ( let i = 0; i < this.valueSize; i ++ ) {
  29029. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  29030. }
  29031. }
  29032. // mix functions
  29033. _select( buffer, dstOffset, srcOffset, t, stride ) {
  29034. if ( t >= 0.5 ) {
  29035. for ( let i = 0; i !== stride; ++ i ) {
  29036. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  29037. }
  29038. }
  29039. }
  29040. _slerp( buffer, dstOffset, srcOffset, t ) {
  29041. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  29042. }
  29043. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  29044. const workOffset = this._workIndex * stride;
  29045. // Store result in intermediate buffer offset
  29046. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  29047. // Slerp to the intermediate result
  29048. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  29049. }
  29050. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  29051. const s = 1 - t;
  29052. for ( let i = 0; i !== stride; ++ i ) {
  29053. const j = dstOffset + i;
  29054. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  29055. }
  29056. }
  29057. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  29058. for ( let i = 0; i !== stride; ++ i ) {
  29059. const j = dstOffset + i;
  29060. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  29061. }
  29062. }
  29063. }
  29064. // Characters [].:/ are reserved for track binding syntax.
  29065. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  29066. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  29067. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  29068. // only latin characters, and the unicode \p{L} is not yet supported. So
  29069. // instead, we exclude reserved characters and match everything else.
  29070. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  29071. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  29072. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  29073. // be matched to parse the rest of the track name.
  29074. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  29075. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  29076. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  29077. // Object on target node, and accessor. May not contain reserved
  29078. // characters. Accessor may contain any character except closing bracket.
  29079. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  29080. // Property and accessor. May not contain reserved characters. Accessor may
  29081. // contain any non-bracket characters.
  29082. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  29083. const _trackRe = new RegExp( ''
  29084. + '^'
  29085. + _directoryRe
  29086. + _nodeRe
  29087. + _objectRe
  29088. + _propertyRe
  29089. + '$'
  29090. );
  29091. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  29092. class Composite {
  29093. constructor( targetGroup, path, optionalParsedPath ) {
  29094. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  29095. this._targetGroup = targetGroup;
  29096. this._bindings = targetGroup.subscribe_( path, parsedPath );
  29097. }
  29098. getValue( array, offset ) {
  29099. this.bind(); // bind all binding
  29100. const firstValidIndex = this._targetGroup.nCachedObjects_,
  29101. binding = this._bindings[ firstValidIndex ];
  29102. // and only call .getValue on the first
  29103. if ( binding !== undefined ) binding.getValue( array, offset );
  29104. }
  29105. setValue( array, offset ) {
  29106. const bindings = this._bindings;
  29107. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29108. bindings[ i ].setValue( array, offset );
  29109. }
  29110. }
  29111. bind() {
  29112. const bindings = this._bindings;
  29113. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29114. bindings[ i ].bind();
  29115. }
  29116. }
  29117. unbind() {
  29118. const bindings = this._bindings;
  29119. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29120. bindings[ i ].unbind();
  29121. }
  29122. }
  29123. }
  29124. // Note: This class uses a State pattern on a per-method basis:
  29125. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  29126. // prototype version of these methods with one that represents
  29127. // the bound state. When the property is not found, the methods
  29128. // become no-ops.
  29129. class PropertyBinding {
  29130. constructor( rootNode, path, parsedPath ) {
  29131. this.path = path;
  29132. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  29133. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  29134. this.rootNode = rootNode;
  29135. // initial state of these methods that calls 'bind'
  29136. this.getValue = this._getValue_unbound;
  29137. this.setValue = this._setValue_unbound;
  29138. }
  29139. static create( root, path, parsedPath ) {
  29140. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  29141. return new PropertyBinding( root, path, parsedPath );
  29142. } else {
  29143. return new PropertyBinding.Composite( root, path, parsedPath );
  29144. }
  29145. }
  29146. /**
  29147. * Replaces spaces with underscores and removes unsupported characters from
  29148. * node names, to ensure compatibility with parseTrackName().
  29149. *
  29150. * @param {string} name Node name to be sanitized.
  29151. * @return {string}
  29152. */
  29153. static sanitizeNodeName( name ) {
  29154. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  29155. }
  29156. static parseTrackName( trackName ) {
  29157. const matches = _trackRe.exec( trackName );
  29158. if ( matches === null ) {
  29159. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  29160. }
  29161. const results = {
  29162. // directoryName: matches[ 1 ], // (tschw) currently unused
  29163. nodeName: matches[ 2 ],
  29164. objectName: matches[ 3 ],
  29165. objectIndex: matches[ 4 ],
  29166. propertyName: matches[ 5 ], // required
  29167. propertyIndex: matches[ 6 ]
  29168. };
  29169. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  29170. if ( lastDot !== undefined && lastDot !== -1 ) {
  29171. const objectName = results.nodeName.substring( lastDot + 1 );
  29172. // Object names must be checked against an allowlist. Otherwise, there
  29173. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  29174. // 'bar' could be the objectName, or part of a nodeName (which can
  29175. // include '.' characters).
  29176. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  29177. results.nodeName = results.nodeName.substring( 0, lastDot );
  29178. results.objectName = objectName;
  29179. }
  29180. }
  29181. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  29182. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  29183. }
  29184. return results;
  29185. }
  29186. static findNode( root, nodeName ) {
  29187. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  29188. return root;
  29189. }
  29190. // search into skeleton bones.
  29191. if ( root.skeleton ) {
  29192. const bone = root.skeleton.getBoneByName( nodeName );
  29193. if ( bone !== undefined ) {
  29194. return bone;
  29195. }
  29196. }
  29197. // search into node subtree.
  29198. if ( root.children ) {
  29199. const searchNodeSubtree = function ( children ) {
  29200. for ( let i = 0; i < children.length; i ++ ) {
  29201. const childNode = children[ i ];
  29202. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  29203. return childNode;
  29204. }
  29205. const result = searchNodeSubtree( childNode.children );
  29206. if ( result ) return result;
  29207. }
  29208. return null;
  29209. };
  29210. const subTreeNode = searchNodeSubtree( root.children );
  29211. if ( subTreeNode ) {
  29212. return subTreeNode;
  29213. }
  29214. }
  29215. return null;
  29216. }
  29217. // these are used to "bind" a nonexistent property
  29218. _getValue_unavailable() {}
  29219. _setValue_unavailable() {}
  29220. // Getters
  29221. _getValue_direct( buffer, offset ) {
  29222. buffer[ offset ] = this.targetObject[ this.propertyName ];
  29223. }
  29224. _getValue_array( buffer, offset ) {
  29225. const source = this.resolvedProperty;
  29226. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  29227. buffer[ offset ++ ] = source[ i ];
  29228. }
  29229. }
  29230. _getValue_arrayElement( buffer, offset ) {
  29231. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  29232. }
  29233. _getValue_toArray( buffer, offset ) {
  29234. this.resolvedProperty.toArray( buffer, offset );
  29235. }
  29236. // Direct
  29237. _setValue_direct( buffer, offset ) {
  29238. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29239. }
  29240. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  29241. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29242. this.targetObject.needsUpdate = true;
  29243. }
  29244. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29245. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29246. this.targetObject.matrixWorldNeedsUpdate = true;
  29247. }
  29248. // EntireArray
  29249. _setValue_array( buffer, offset ) {
  29250. const dest = this.resolvedProperty;
  29251. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  29252. dest[ i ] = buffer[ offset ++ ];
  29253. }
  29254. }
  29255. _setValue_array_setNeedsUpdate( buffer, offset ) {
  29256. const dest = this.resolvedProperty;
  29257. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  29258. dest[ i ] = buffer[ offset ++ ];
  29259. }
  29260. this.targetObject.needsUpdate = true;
  29261. }
  29262. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29263. const dest = this.resolvedProperty;
  29264. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  29265. dest[ i ] = buffer[ offset ++ ];
  29266. }
  29267. this.targetObject.matrixWorldNeedsUpdate = true;
  29268. }
  29269. // ArrayElement
  29270. _setValue_arrayElement( buffer, offset ) {
  29271. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29272. }
  29273. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  29274. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29275. this.targetObject.needsUpdate = true;
  29276. }
  29277. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29278. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29279. this.targetObject.matrixWorldNeedsUpdate = true;
  29280. }
  29281. // HasToFromArray
  29282. _setValue_fromArray( buffer, offset ) {
  29283. this.resolvedProperty.fromArray( buffer, offset );
  29284. }
  29285. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  29286. this.resolvedProperty.fromArray( buffer, offset );
  29287. this.targetObject.needsUpdate = true;
  29288. }
  29289. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29290. this.resolvedProperty.fromArray( buffer, offset );
  29291. this.targetObject.matrixWorldNeedsUpdate = true;
  29292. }
  29293. _getValue_unbound( targetArray, offset ) {
  29294. this.bind();
  29295. this.getValue( targetArray, offset );
  29296. }
  29297. _setValue_unbound( sourceArray, offset ) {
  29298. this.bind();
  29299. this.setValue( sourceArray, offset );
  29300. }
  29301. // create getter / setter pair for a property in the scene graph
  29302. bind() {
  29303. let targetObject = this.node;
  29304. const parsedPath = this.parsedPath;
  29305. const objectName = parsedPath.objectName;
  29306. const propertyName = parsedPath.propertyName;
  29307. let propertyIndex = parsedPath.propertyIndex;
  29308. if ( ! targetObject ) {
  29309. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  29310. this.node = targetObject;
  29311. }
  29312. // set fail state so we can just 'return' on error
  29313. this.getValue = this._getValue_unavailable;
  29314. this.setValue = this._setValue_unavailable;
  29315. // ensure there is a value node
  29316. if ( ! targetObject ) {
  29317. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  29318. return;
  29319. }
  29320. if ( objectName ) {
  29321. let objectIndex = parsedPath.objectIndex;
  29322. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  29323. switch ( objectName ) {
  29324. case 'materials':
  29325. if ( ! targetObject.material ) {
  29326. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  29327. return;
  29328. }
  29329. if ( ! targetObject.material.materials ) {
  29330. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  29331. return;
  29332. }
  29333. targetObject = targetObject.material.materials;
  29334. break;
  29335. case 'bones':
  29336. if ( ! targetObject.skeleton ) {
  29337. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  29338. return;
  29339. }
  29340. // potential future optimization: skip this if propertyIndex is already an integer
  29341. // and convert the integer string to a true integer.
  29342. targetObject = targetObject.skeleton.bones;
  29343. // support resolving morphTarget names into indices.
  29344. for ( let i = 0; i < targetObject.length; i ++ ) {
  29345. if ( targetObject[ i ].name === objectIndex ) {
  29346. objectIndex = i;
  29347. break;
  29348. }
  29349. }
  29350. break;
  29351. case 'map':
  29352. if ( 'map' in targetObject ) {
  29353. targetObject = targetObject.map;
  29354. break;
  29355. }
  29356. if ( ! targetObject.material ) {
  29357. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  29358. return;
  29359. }
  29360. if ( ! targetObject.material.map ) {
  29361. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  29362. return;
  29363. }
  29364. targetObject = targetObject.material.map;
  29365. break;
  29366. default:
  29367. if ( targetObject[ objectName ] === undefined ) {
  29368. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  29369. return;
  29370. }
  29371. targetObject = targetObject[ objectName ];
  29372. }
  29373. if ( objectIndex !== undefined ) {
  29374. if ( targetObject[ objectIndex ] === undefined ) {
  29375. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  29376. return;
  29377. }
  29378. targetObject = targetObject[ objectIndex ];
  29379. }
  29380. }
  29381. // resolve property
  29382. const nodeProperty = targetObject[ propertyName ];
  29383. if ( nodeProperty === undefined ) {
  29384. const nodeName = parsedPath.nodeName;
  29385. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  29386. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  29387. return;
  29388. }
  29389. // determine versioning scheme
  29390. let versioning = this.Versioning.None;
  29391. this.targetObject = targetObject;
  29392. if ( targetObject.isMaterial === true ) {
  29393. versioning = this.Versioning.NeedsUpdate;
  29394. } else if ( targetObject.isObject3D === true ) {
  29395. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  29396. }
  29397. // determine how the property gets bound
  29398. let bindingType = this.BindingType.Direct;
  29399. if ( propertyIndex !== undefined ) {
  29400. // access a sub element of the property array (only primitives are supported right now)
  29401. if ( propertyName === 'morphTargetInfluences' ) {
  29402. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  29403. // support resolving morphTarget names into indices.
  29404. if ( ! targetObject.geometry ) {
  29405. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  29406. return;
  29407. }
  29408. if ( ! targetObject.geometry.morphAttributes ) {
  29409. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  29410. return;
  29411. }
  29412. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  29413. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  29414. }
  29415. }
  29416. bindingType = this.BindingType.ArrayElement;
  29417. this.resolvedProperty = nodeProperty;
  29418. this.propertyIndex = propertyIndex;
  29419. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  29420. // must use copy for Object3D.Euler/Quaternion
  29421. bindingType = this.BindingType.HasFromToArray;
  29422. this.resolvedProperty = nodeProperty;
  29423. } else if ( Array.isArray( nodeProperty ) ) {
  29424. bindingType = this.BindingType.EntireArray;
  29425. this.resolvedProperty = nodeProperty;
  29426. } else {
  29427. this.propertyName = propertyName;
  29428. }
  29429. // select getter / setter
  29430. this.getValue = this.GetterByBindingType[ bindingType ];
  29431. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  29432. }
  29433. unbind() {
  29434. this.node = null;
  29435. // back to the prototype version of getValue / setValue
  29436. // note: avoiding to mutate the shape of 'this' via 'delete'
  29437. this.getValue = this._getValue_unbound;
  29438. this.setValue = this._setValue_unbound;
  29439. }
  29440. }
  29441. PropertyBinding.Composite = Composite;
  29442. PropertyBinding.prototype.BindingType = {
  29443. Direct: 0,
  29444. EntireArray: 1,
  29445. ArrayElement: 2,
  29446. HasFromToArray: 3
  29447. };
  29448. PropertyBinding.prototype.Versioning = {
  29449. None: 0,
  29450. NeedsUpdate: 1,
  29451. MatrixWorldNeedsUpdate: 2
  29452. };
  29453. PropertyBinding.prototype.GetterByBindingType = [
  29454. PropertyBinding.prototype._getValue_direct,
  29455. PropertyBinding.prototype._getValue_array,
  29456. PropertyBinding.prototype._getValue_arrayElement,
  29457. PropertyBinding.prototype._getValue_toArray,
  29458. ];
  29459. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  29460. [
  29461. // Direct
  29462. PropertyBinding.prototype._setValue_direct,
  29463. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  29464. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  29465. ], [
  29466. // EntireArray
  29467. PropertyBinding.prototype._setValue_array,
  29468. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  29469. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  29470. ], [
  29471. // ArrayElement
  29472. PropertyBinding.prototype._setValue_arrayElement,
  29473. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  29474. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  29475. ], [
  29476. // HasToFromArray
  29477. PropertyBinding.prototype._setValue_fromArray,
  29478. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  29479. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  29480. ]
  29481. ];
  29482. /**
  29483. *
  29484. * A group of objects that receives a shared animation state.
  29485. *
  29486. * Usage:
  29487. *
  29488. * - Add objects you would otherwise pass as 'root' to the
  29489. * constructor or the .clipAction method of AnimationMixer.
  29490. *
  29491. * - Instead pass this object as 'root'.
  29492. *
  29493. * - You can also add and remove objects later when the mixer
  29494. * is running.
  29495. *
  29496. * Note:
  29497. *
  29498. * Objects of this class appear as one object to the mixer,
  29499. * so cache control of the individual objects must be done
  29500. * on the group.
  29501. *
  29502. * Limitation:
  29503. *
  29504. * - The animated properties must be compatible among the
  29505. * all objects in the group.
  29506. *
  29507. * - A single property can either be controlled through a
  29508. * target group or directly, but not both.
  29509. */
  29510. class AnimationObjectGroup {
  29511. constructor() {
  29512. this.isAnimationObjectGroup = true;
  29513. this.uuid = generateUUID();
  29514. // cached objects followed by the active ones
  29515. this._objects = Array.prototype.slice.call( arguments );
  29516. this.nCachedObjects_ = 0; // threshold
  29517. // note: read by PropertyBinding.Composite
  29518. const indices = {};
  29519. this._indicesByUUID = indices; // for bookkeeping
  29520. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29521. indices[ arguments[ i ].uuid ] = i;
  29522. }
  29523. this._paths = []; // inside: string
  29524. this._parsedPaths = []; // inside: { we don't care, here }
  29525. this._bindings = []; // inside: Array< PropertyBinding >
  29526. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  29527. const scope = this;
  29528. this.stats = {
  29529. objects: {
  29530. get total() {
  29531. return scope._objects.length;
  29532. },
  29533. get inUse() {
  29534. return this.total - scope.nCachedObjects_;
  29535. }
  29536. },
  29537. get bindingsPerObject() {
  29538. return scope._bindings.length;
  29539. }
  29540. };
  29541. }
  29542. add() {
  29543. const objects = this._objects,
  29544. indicesByUUID = this._indicesByUUID,
  29545. paths = this._paths,
  29546. parsedPaths = this._parsedPaths,
  29547. bindings = this._bindings,
  29548. nBindings = bindings.length;
  29549. let knownObject = undefined,
  29550. nObjects = objects.length,
  29551. nCachedObjects = this.nCachedObjects_;
  29552. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29553. const object = arguments[ i ],
  29554. uuid = object.uuid;
  29555. let index = indicesByUUID[ uuid ];
  29556. if ( index === undefined ) {
  29557. // unknown object -> add it to the ACTIVE region
  29558. index = nObjects ++;
  29559. indicesByUUID[ uuid ] = index;
  29560. objects.push( object );
  29561. // accounting is done, now do the same for all bindings
  29562. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29563. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  29564. }
  29565. } else if ( index < nCachedObjects ) {
  29566. knownObject = objects[ index ];
  29567. // move existing object to the ACTIVE region
  29568. const firstActiveIndex = -- nCachedObjects,
  29569. lastCachedObject = objects[ firstActiveIndex ];
  29570. indicesByUUID[ lastCachedObject.uuid ] = index;
  29571. objects[ index ] = lastCachedObject;
  29572. indicesByUUID[ uuid ] = firstActiveIndex;
  29573. objects[ firstActiveIndex ] = object;
  29574. // accounting is done, now do the same for all bindings
  29575. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29576. const bindingsForPath = bindings[ j ],
  29577. lastCached = bindingsForPath[ firstActiveIndex ];
  29578. let binding = bindingsForPath[ index ];
  29579. bindingsForPath[ index ] = lastCached;
  29580. if ( binding === undefined ) {
  29581. // since we do not bother to create new bindings
  29582. // for objects that are cached, the binding may
  29583. // or may not exist
  29584. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  29585. }
  29586. bindingsForPath[ firstActiveIndex ] = binding;
  29587. }
  29588. } else if ( objects[ index ] !== knownObject ) {
  29589. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  29590. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  29591. } // else the object is already where we want it to be
  29592. } // for arguments
  29593. this.nCachedObjects_ = nCachedObjects;
  29594. }
  29595. remove() {
  29596. const objects = this._objects,
  29597. indicesByUUID = this._indicesByUUID,
  29598. bindings = this._bindings,
  29599. nBindings = bindings.length;
  29600. let nCachedObjects = this.nCachedObjects_;
  29601. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29602. const object = arguments[ i ],
  29603. uuid = object.uuid,
  29604. index = indicesByUUID[ uuid ];
  29605. if ( index !== undefined && index >= nCachedObjects ) {
  29606. // move existing object into the CACHED region
  29607. const lastCachedIndex = nCachedObjects ++,
  29608. firstActiveObject = objects[ lastCachedIndex ];
  29609. indicesByUUID[ firstActiveObject.uuid ] = index;
  29610. objects[ index ] = firstActiveObject;
  29611. indicesByUUID[ uuid ] = lastCachedIndex;
  29612. objects[ lastCachedIndex ] = object;
  29613. // accounting is done, now do the same for all bindings
  29614. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29615. const bindingsForPath = bindings[ j ],
  29616. firstActive = bindingsForPath[ lastCachedIndex ],
  29617. binding = bindingsForPath[ index ];
  29618. bindingsForPath[ index ] = firstActive;
  29619. bindingsForPath[ lastCachedIndex ] = binding;
  29620. }
  29621. }
  29622. } // for arguments
  29623. this.nCachedObjects_ = nCachedObjects;
  29624. }
  29625. // remove & forget
  29626. uncache() {
  29627. const objects = this._objects,
  29628. indicesByUUID = this._indicesByUUID,
  29629. bindings = this._bindings,
  29630. nBindings = bindings.length;
  29631. let nCachedObjects = this.nCachedObjects_,
  29632. nObjects = objects.length;
  29633. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29634. const object = arguments[ i ],
  29635. uuid = object.uuid,
  29636. index = indicesByUUID[ uuid ];
  29637. if ( index !== undefined ) {
  29638. delete indicesByUUID[ uuid ];
  29639. if ( index < nCachedObjects ) {
  29640. // object is cached, shrink the CACHED region
  29641. const firstActiveIndex = -- nCachedObjects,
  29642. lastCachedObject = objects[ firstActiveIndex ],
  29643. lastIndex = -- nObjects,
  29644. lastObject = objects[ lastIndex ];
  29645. // last cached object takes this object's place
  29646. indicesByUUID[ lastCachedObject.uuid ] = index;
  29647. objects[ index ] = lastCachedObject;
  29648. // last object goes to the activated slot and pop
  29649. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  29650. objects[ firstActiveIndex ] = lastObject;
  29651. objects.pop();
  29652. // accounting is done, now do the same for all bindings
  29653. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29654. const bindingsForPath = bindings[ j ],
  29655. lastCached = bindingsForPath[ firstActiveIndex ],
  29656. last = bindingsForPath[ lastIndex ];
  29657. bindingsForPath[ index ] = lastCached;
  29658. bindingsForPath[ firstActiveIndex ] = last;
  29659. bindingsForPath.pop();
  29660. }
  29661. } else {
  29662. // object is active, just swap with the last and pop
  29663. const lastIndex = -- nObjects,
  29664. lastObject = objects[ lastIndex ];
  29665. if ( lastIndex > 0 ) {
  29666. indicesByUUID[ lastObject.uuid ] = index;
  29667. }
  29668. objects[ index ] = lastObject;
  29669. objects.pop();
  29670. // accounting is done, now do the same for all bindings
  29671. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29672. const bindingsForPath = bindings[ j ];
  29673. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  29674. bindingsForPath.pop();
  29675. }
  29676. } // cached or active
  29677. } // if object is known
  29678. } // for arguments
  29679. this.nCachedObjects_ = nCachedObjects;
  29680. }
  29681. // Internal interface used by befriended PropertyBinding.Composite:
  29682. subscribe_( path, parsedPath ) {
  29683. // returns an array of bindings for the given path that is changed
  29684. // according to the contained objects in the group
  29685. const indicesByPath = this._bindingsIndicesByPath;
  29686. let index = indicesByPath[ path ];
  29687. const bindings = this._bindings;
  29688. if ( index !== undefined ) return bindings[ index ];
  29689. const paths = this._paths,
  29690. parsedPaths = this._parsedPaths,
  29691. objects = this._objects,
  29692. nObjects = objects.length,
  29693. nCachedObjects = this.nCachedObjects_,
  29694. bindingsForPath = new Array( nObjects );
  29695. index = bindings.length;
  29696. indicesByPath[ path ] = index;
  29697. paths.push( path );
  29698. parsedPaths.push( parsedPath );
  29699. bindings.push( bindingsForPath );
  29700. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  29701. const object = objects[ i ];
  29702. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  29703. }
  29704. return bindingsForPath;
  29705. }
  29706. unsubscribe_( path ) {
  29707. // tells the group to forget about a property path and no longer
  29708. // update the array previously obtained with 'subscribe_'
  29709. const indicesByPath = this._bindingsIndicesByPath,
  29710. index = indicesByPath[ path ];
  29711. if ( index !== undefined ) {
  29712. const paths = this._paths,
  29713. parsedPaths = this._parsedPaths,
  29714. bindings = this._bindings,
  29715. lastBindingsIndex = bindings.length - 1,
  29716. lastBindings = bindings[ lastBindingsIndex ],
  29717. lastBindingsPath = path[ lastBindingsIndex ];
  29718. indicesByPath[ lastBindingsPath ] = index;
  29719. bindings[ index ] = lastBindings;
  29720. bindings.pop();
  29721. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  29722. parsedPaths.pop();
  29723. paths[ index ] = paths[ lastBindingsIndex ];
  29724. paths.pop();
  29725. }
  29726. }
  29727. }
  29728. class AnimationAction {
  29729. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  29730. this._mixer = mixer;
  29731. this._clip = clip;
  29732. this._localRoot = localRoot;
  29733. this.blendMode = blendMode;
  29734. const tracks = clip.tracks,
  29735. nTracks = tracks.length,
  29736. interpolants = new Array( nTracks );
  29737. const interpolantSettings = {
  29738. endingStart: ZeroCurvatureEnding,
  29739. endingEnd: ZeroCurvatureEnding
  29740. };
  29741. for ( let i = 0; i !== nTracks; ++ i ) {
  29742. const interpolant = tracks[ i ].createInterpolant( null );
  29743. interpolants[ i ] = interpolant;
  29744. interpolant.settings = interpolantSettings;
  29745. }
  29746. this._interpolantSettings = interpolantSettings;
  29747. this._interpolants = interpolants; // bound by the mixer
  29748. // inside: PropertyMixer (managed by the mixer)
  29749. this._propertyBindings = new Array( nTracks );
  29750. this._cacheIndex = null; // for the memory manager
  29751. this._byClipCacheIndex = null; // for the memory manager
  29752. this._timeScaleInterpolant = null;
  29753. this._weightInterpolant = null;
  29754. this.loop = LoopRepeat;
  29755. this._loopCount = -1;
  29756. // global mixer time when the action is to be started
  29757. // it's set back to 'null' upon start of the action
  29758. this._startTime = null;
  29759. // scaled local time of the action
  29760. // gets clamped or wrapped to 0..clip.duration according to loop
  29761. this.time = 0;
  29762. this.timeScale = 1;
  29763. this._effectiveTimeScale = 1;
  29764. this.weight = 1;
  29765. this._effectiveWeight = 1;
  29766. this.repetitions = Infinity; // no. of repetitions when looping
  29767. this.paused = false; // true -> zero effective time scale
  29768. this.enabled = true; // false -> zero effective weight
  29769. this.clampWhenFinished = false;// keep feeding the last frame?
  29770. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  29771. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  29772. }
  29773. // State & Scheduling
  29774. play() {
  29775. this._mixer._activateAction( this );
  29776. return this;
  29777. }
  29778. stop() {
  29779. this._mixer._deactivateAction( this );
  29780. return this.reset();
  29781. }
  29782. reset() {
  29783. this.paused = false;
  29784. this.enabled = true;
  29785. this.time = 0; // restart clip
  29786. this._loopCount = -1;// forget previous loops
  29787. this._startTime = null;// forget scheduling
  29788. return this.stopFading().stopWarping();
  29789. }
  29790. isRunning() {
  29791. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  29792. this._startTime === null && this._mixer._isActiveAction( this );
  29793. }
  29794. // return true when play has been called
  29795. isScheduled() {
  29796. return this._mixer._isActiveAction( this );
  29797. }
  29798. startAt( time ) {
  29799. this._startTime = time;
  29800. return this;
  29801. }
  29802. setLoop( mode, repetitions ) {
  29803. this.loop = mode;
  29804. this.repetitions = repetitions;
  29805. return this;
  29806. }
  29807. // Weight
  29808. // set the weight stopping any scheduled fading
  29809. // although .enabled = false yields an effective weight of zero, this
  29810. // method does *not* change .enabled, because it would be confusing
  29811. setEffectiveWeight( weight ) {
  29812. this.weight = weight;
  29813. // note: same logic as when updated at runtime
  29814. this._effectiveWeight = this.enabled ? weight : 0;
  29815. return this.stopFading();
  29816. }
  29817. // return the weight considering fading and .enabled
  29818. getEffectiveWeight() {
  29819. return this._effectiveWeight;
  29820. }
  29821. fadeIn( duration ) {
  29822. return this._scheduleFading( duration, 0, 1 );
  29823. }
  29824. fadeOut( duration ) {
  29825. return this._scheduleFading( duration, 1, 0 );
  29826. }
  29827. crossFadeFrom( fadeOutAction, duration, warp ) {
  29828. fadeOutAction.fadeOut( duration );
  29829. this.fadeIn( duration );
  29830. if ( warp ) {
  29831. const fadeInDuration = this._clip.duration,
  29832. fadeOutDuration = fadeOutAction._clip.duration,
  29833. startEndRatio = fadeOutDuration / fadeInDuration,
  29834. endStartRatio = fadeInDuration / fadeOutDuration;
  29835. fadeOutAction.warp( 1.0, startEndRatio, duration );
  29836. this.warp( endStartRatio, 1.0, duration );
  29837. }
  29838. return this;
  29839. }
  29840. crossFadeTo( fadeInAction, duration, warp ) {
  29841. return fadeInAction.crossFadeFrom( this, duration, warp );
  29842. }
  29843. stopFading() {
  29844. const weightInterpolant = this._weightInterpolant;
  29845. if ( weightInterpolant !== null ) {
  29846. this._weightInterpolant = null;
  29847. this._mixer._takeBackControlInterpolant( weightInterpolant );
  29848. }
  29849. return this;
  29850. }
  29851. // Time Scale Control
  29852. // set the time scale stopping any scheduled warping
  29853. // although .paused = true yields an effective time scale of zero, this
  29854. // method does *not* change .paused, because it would be confusing
  29855. setEffectiveTimeScale( timeScale ) {
  29856. this.timeScale = timeScale;
  29857. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  29858. return this.stopWarping();
  29859. }
  29860. // return the time scale considering warping and .paused
  29861. getEffectiveTimeScale() {
  29862. return this._effectiveTimeScale;
  29863. }
  29864. setDuration( duration ) {
  29865. this.timeScale = this._clip.duration / duration;
  29866. return this.stopWarping();
  29867. }
  29868. syncWith( action ) {
  29869. this.time = action.time;
  29870. this.timeScale = action.timeScale;
  29871. return this.stopWarping();
  29872. }
  29873. halt( duration ) {
  29874. return this.warp( this._effectiveTimeScale, 0, duration );
  29875. }
  29876. warp( startTimeScale, endTimeScale, duration ) {
  29877. const mixer = this._mixer,
  29878. now = mixer.time,
  29879. timeScale = this.timeScale;
  29880. let interpolant = this._timeScaleInterpolant;
  29881. if ( interpolant === null ) {
  29882. interpolant = mixer._lendControlInterpolant();
  29883. this._timeScaleInterpolant = interpolant;
  29884. }
  29885. const times = interpolant.parameterPositions,
  29886. values = interpolant.sampleValues;
  29887. times[ 0 ] = now;
  29888. times[ 1 ] = now + duration;
  29889. values[ 0 ] = startTimeScale / timeScale;
  29890. values[ 1 ] = endTimeScale / timeScale;
  29891. return this;
  29892. }
  29893. stopWarping() {
  29894. const timeScaleInterpolant = this._timeScaleInterpolant;
  29895. if ( timeScaleInterpolant !== null ) {
  29896. this._timeScaleInterpolant = null;
  29897. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  29898. }
  29899. return this;
  29900. }
  29901. // Object Accessors
  29902. getMixer() {
  29903. return this._mixer;
  29904. }
  29905. getClip() {
  29906. return this._clip;
  29907. }
  29908. getRoot() {
  29909. return this._localRoot || this._mixer._root;
  29910. }
  29911. // Interna
  29912. _update( time, deltaTime, timeDirection, accuIndex ) {
  29913. // called by the mixer
  29914. if ( ! this.enabled ) {
  29915. // call ._updateWeight() to update ._effectiveWeight
  29916. this._updateWeight( time );
  29917. return;
  29918. }
  29919. const startTime = this._startTime;
  29920. if ( startTime !== null ) {
  29921. // check for scheduled start of action
  29922. const timeRunning = ( time - startTime ) * timeDirection;
  29923. if ( timeRunning < 0 || timeDirection === 0 ) {
  29924. deltaTime = 0;
  29925. } else {
  29926. this._startTime = null; // unschedule
  29927. deltaTime = timeDirection * timeRunning;
  29928. }
  29929. }
  29930. // apply time scale and advance time
  29931. deltaTime *= this._updateTimeScale( time );
  29932. const clipTime = this._updateTime( deltaTime );
  29933. // note: _updateTime may disable the action resulting in
  29934. // an effective weight of 0
  29935. const weight = this._updateWeight( time );
  29936. if ( weight > 0 ) {
  29937. const interpolants = this._interpolants;
  29938. const propertyMixers = this._propertyBindings;
  29939. switch ( this.blendMode ) {
  29940. case AdditiveAnimationBlendMode:
  29941. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29942. interpolants[ j ].evaluate( clipTime );
  29943. propertyMixers[ j ].accumulateAdditive( weight );
  29944. }
  29945. break;
  29946. case NormalAnimationBlendMode:
  29947. default:
  29948. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29949. interpolants[ j ].evaluate( clipTime );
  29950. propertyMixers[ j ].accumulate( accuIndex, weight );
  29951. }
  29952. }
  29953. }
  29954. }
  29955. _updateWeight( time ) {
  29956. let weight = 0;
  29957. if ( this.enabled ) {
  29958. weight = this.weight;
  29959. const interpolant = this._weightInterpolant;
  29960. if ( interpolant !== null ) {
  29961. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29962. weight *= interpolantValue;
  29963. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29964. this.stopFading();
  29965. if ( interpolantValue === 0 ) {
  29966. // faded out, disable
  29967. this.enabled = false;
  29968. }
  29969. }
  29970. }
  29971. }
  29972. this._effectiveWeight = weight;
  29973. return weight;
  29974. }
  29975. _updateTimeScale( time ) {
  29976. let timeScale = 0;
  29977. if ( ! this.paused ) {
  29978. timeScale = this.timeScale;
  29979. const interpolant = this._timeScaleInterpolant;
  29980. if ( interpolant !== null ) {
  29981. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29982. timeScale *= interpolantValue;
  29983. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29984. this.stopWarping();
  29985. if ( timeScale === 0 ) {
  29986. // motion has halted, pause
  29987. this.paused = true;
  29988. } else {
  29989. // warp done - apply final time scale
  29990. this.timeScale = timeScale;
  29991. }
  29992. }
  29993. }
  29994. }
  29995. this._effectiveTimeScale = timeScale;
  29996. return timeScale;
  29997. }
  29998. _updateTime( deltaTime ) {
  29999. const duration = this._clip.duration;
  30000. const loop = this.loop;
  30001. let time = this.time + deltaTime;
  30002. let loopCount = this._loopCount;
  30003. const pingPong = ( loop === LoopPingPong );
  30004. if ( deltaTime === 0 ) {
  30005. if ( loopCount === -1 ) return time;
  30006. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  30007. }
  30008. if ( loop === LoopOnce ) {
  30009. if ( loopCount === -1 ) {
  30010. // just started
  30011. this._loopCount = 0;
  30012. this._setEndings( true, true, false );
  30013. }
  30014. handle_stop: {
  30015. if ( time >= duration ) {
  30016. time = duration;
  30017. } else if ( time < 0 ) {
  30018. time = 0;
  30019. } else {
  30020. this.time = time;
  30021. break handle_stop;
  30022. }
  30023. if ( this.clampWhenFinished ) this.paused = true;
  30024. else this.enabled = false;
  30025. this.time = time;
  30026. this._mixer.dispatchEvent( {
  30027. type: 'finished', action: this,
  30028. direction: deltaTime < 0 ? -1 : 1
  30029. } );
  30030. }
  30031. } else { // repetitive Repeat or PingPong
  30032. if ( loopCount === -1 ) {
  30033. // just started
  30034. if ( deltaTime >= 0 ) {
  30035. loopCount = 0;
  30036. this._setEndings( true, this.repetitions === 0, pingPong );
  30037. } else {
  30038. // when looping in reverse direction, the initial
  30039. // transition through zero counts as a repetition,
  30040. // so leave loopCount at -1
  30041. this._setEndings( this.repetitions === 0, true, pingPong );
  30042. }
  30043. }
  30044. if ( time >= duration || time < 0 ) {
  30045. // wrap around
  30046. const loopDelta = Math.floor( time / duration ); // signed
  30047. time -= duration * loopDelta;
  30048. loopCount += Math.abs( loopDelta );
  30049. const pending = this.repetitions - loopCount;
  30050. if ( pending <= 0 ) {
  30051. // have to stop (switch state, clamp time, fire event)
  30052. if ( this.clampWhenFinished ) this.paused = true;
  30053. else this.enabled = false;
  30054. time = deltaTime > 0 ? duration : 0;
  30055. this.time = time;
  30056. this._mixer.dispatchEvent( {
  30057. type: 'finished', action: this,
  30058. direction: deltaTime > 0 ? 1 : -1
  30059. } );
  30060. } else {
  30061. // keep running
  30062. if ( pending === 1 ) {
  30063. // entering the last round
  30064. const atStart = deltaTime < 0;
  30065. this._setEndings( atStart, ! atStart, pingPong );
  30066. } else {
  30067. this._setEndings( false, false, pingPong );
  30068. }
  30069. this._loopCount = loopCount;
  30070. this.time = time;
  30071. this._mixer.dispatchEvent( {
  30072. type: 'loop', action: this, loopDelta: loopDelta
  30073. } );
  30074. }
  30075. } else {
  30076. this.time = time;
  30077. }
  30078. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  30079. // invert time for the "pong round"
  30080. return duration - time;
  30081. }
  30082. }
  30083. return time;
  30084. }
  30085. _setEndings( atStart, atEnd, pingPong ) {
  30086. const settings = this._interpolantSettings;
  30087. if ( pingPong ) {
  30088. settings.endingStart = ZeroSlopeEnding;
  30089. settings.endingEnd = ZeroSlopeEnding;
  30090. } else {
  30091. // assuming for LoopOnce atStart == atEnd == true
  30092. if ( atStart ) {
  30093. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  30094. } else {
  30095. settings.endingStart = WrapAroundEnding;
  30096. }
  30097. if ( atEnd ) {
  30098. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  30099. } else {
  30100. settings.endingEnd = WrapAroundEnding;
  30101. }
  30102. }
  30103. }
  30104. _scheduleFading( duration, weightNow, weightThen ) {
  30105. const mixer = this._mixer, now = mixer.time;
  30106. let interpolant = this._weightInterpolant;
  30107. if ( interpolant === null ) {
  30108. interpolant = mixer._lendControlInterpolant();
  30109. this._weightInterpolant = interpolant;
  30110. }
  30111. const times = interpolant.parameterPositions,
  30112. values = interpolant.sampleValues;
  30113. times[ 0 ] = now;
  30114. values[ 0 ] = weightNow;
  30115. times[ 1 ] = now + duration;
  30116. values[ 1 ] = weightThen;
  30117. return this;
  30118. }
  30119. }
  30120. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  30121. class AnimationMixer extends EventDispatcher {
  30122. constructor( root ) {
  30123. super();
  30124. this._root = root;
  30125. this._initMemoryManager();
  30126. this._accuIndex = 0;
  30127. this.time = 0;
  30128. this.timeScale = 1.0;
  30129. }
  30130. _bindAction( action, prototypeAction ) {
  30131. const root = action._localRoot || this._root,
  30132. tracks = action._clip.tracks,
  30133. nTracks = tracks.length,
  30134. bindings = action._propertyBindings,
  30135. interpolants = action._interpolants,
  30136. rootUuid = root.uuid,
  30137. bindingsByRoot = this._bindingsByRootAndName;
  30138. let bindingsByName = bindingsByRoot[ rootUuid ];
  30139. if ( bindingsByName === undefined ) {
  30140. bindingsByName = {};
  30141. bindingsByRoot[ rootUuid ] = bindingsByName;
  30142. }
  30143. for ( let i = 0; i !== nTracks; ++ i ) {
  30144. const track = tracks[ i ],
  30145. trackName = track.name;
  30146. let binding = bindingsByName[ trackName ];
  30147. if ( binding !== undefined ) {
  30148. ++ binding.referenceCount;
  30149. bindings[ i ] = binding;
  30150. } else {
  30151. binding = bindings[ i ];
  30152. if ( binding !== undefined ) {
  30153. // existing binding, make sure the cache knows
  30154. if ( binding._cacheIndex === null ) {
  30155. ++ binding.referenceCount;
  30156. this._addInactiveBinding( binding, rootUuid, trackName );
  30157. }
  30158. continue;
  30159. }
  30160. const path = prototypeAction && prototypeAction.
  30161. _propertyBindings[ i ].binding.parsedPath;
  30162. binding = new PropertyMixer(
  30163. PropertyBinding.create( root, trackName, path ),
  30164. track.ValueTypeName, track.getValueSize() );
  30165. ++ binding.referenceCount;
  30166. this._addInactiveBinding( binding, rootUuid, trackName );
  30167. bindings[ i ] = binding;
  30168. }
  30169. interpolants[ i ].resultBuffer = binding.buffer;
  30170. }
  30171. }
  30172. _activateAction( action ) {
  30173. if ( ! this._isActiveAction( action ) ) {
  30174. if ( action._cacheIndex === null ) {
  30175. // this action has been forgotten by the cache, but the user
  30176. // appears to be still using it -> rebind
  30177. const rootUuid = ( action._localRoot || this._root ).uuid,
  30178. clipUuid = action._clip.uuid,
  30179. actionsForClip = this._actionsByClip[ clipUuid ];
  30180. this._bindAction( action,
  30181. actionsForClip && actionsForClip.knownActions[ 0 ] );
  30182. this._addInactiveAction( action, clipUuid, rootUuid );
  30183. }
  30184. const bindings = action._propertyBindings;
  30185. // increment reference counts / sort out state
  30186. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30187. const binding = bindings[ i ];
  30188. if ( binding.useCount ++ === 0 ) {
  30189. this._lendBinding( binding );
  30190. binding.saveOriginalState();
  30191. }
  30192. }
  30193. this._lendAction( action );
  30194. }
  30195. }
  30196. _deactivateAction( action ) {
  30197. if ( this._isActiveAction( action ) ) {
  30198. const bindings = action._propertyBindings;
  30199. // decrement reference counts / sort out state
  30200. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30201. const binding = bindings[ i ];
  30202. if ( -- binding.useCount === 0 ) {
  30203. binding.restoreOriginalState();
  30204. this._takeBackBinding( binding );
  30205. }
  30206. }
  30207. this._takeBackAction( action );
  30208. }
  30209. }
  30210. // Memory manager
  30211. _initMemoryManager() {
  30212. this._actions = []; // 'nActiveActions' followed by inactive ones
  30213. this._nActiveActions = 0;
  30214. this._actionsByClip = {};
  30215. // inside:
  30216. // {
  30217. // knownActions: Array< AnimationAction > - used as prototypes
  30218. // actionByRoot: AnimationAction - lookup
  30219. // }
  30220. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  30221. this._nActiveBindings = 0;
  30222. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  30223. this._controlInterpolants = []; // same game as above
  30224. this._nActiveControlInterpolants = 0;
  30225. const scope = this;
  30226. this.stats = {
  30227. actions: {
  30228. get total() {
  30229. return scope._actions.length;
  30230. },
  30231. get inUse() {
  30232. return scope._nActiveActions;
  30233. }
  30234. },
  30235. bindings: {
  30236. get total() {
  30237. return scope._bindings.length;
  30238. },
  30239. get inUse() {
  30240. return scope._nActiveBindings;
  30241. }
  30242. },
  30243. controlInterpolants: {
  30244. get total() {
  30245. return scope._controlInterpolants.length;
  30246. },
  30247. get inUse() {
  30248. return scope._nActiveControlInterpolants;
  30249. }
  30250. }
  30251. };
  30252. }
  30253. // Memory management for AnimationAction objects
  30254. _isActiveAction( action ) {
  30255. const index = action._cacheIndex;
  30256. return index !== null && index < this._nActiveActions;
  30257. }
  30258. _addInactiveAction( action, clipUuid, rootUuid ) {
  30259. const actions = this._actions,
  30260. actionsByClip = this._actionsByClip;
  30261. let actionsForClip = actionsByClip[ clipUuid ];
  30262. if ( actionsForClip === undefined ) {
  30263. actionsForClip = {
  30264. knownActions: [ action ],
  30265. actionByRoot: {}
  30266. };
  30267. action._byClipCacheIndex = 0;
  30268. actionsByClip[ clipUuid ] = actionsForClip;
  30269. } else {
  30270. const knownActions = actionsForClip.knownActions;
  30271. action._byClipCacheIndex = knownActions.length;
  30272. knownActions.push( action );
  30273. }
  30274. action._cacheIndex = actions.length;
  30275. actions.push( action );
  30276. actionsForClip.actionByRoot[ rootUuid ] = action;
  30277. }
  30278. _removeInactiveAction( action ) {
  30279. const actions = this._actions,
  30280. lastInactiveAction = actions[ actions.length - 1 ],
  30281. cacheIndex = action._cacheIndex;
  30282. lastInactiveAction._cacheIndex = cacheIndex;
  30283. actions[ cacheIndex ] = lastInactiveAction;
  30284. actions.pop();
  30285. action._cacheIndex = null;
  30286. const clipUuid = action._clip.uuid,
  30287. actionsByClip = this._actionsByClip,
  30288. actionsForClip = actionsByClip[ clipUuid ],
  30289. knownActionsForClip = actionsForClip.knownActions,
  30290. lastKnownAction =
  30291. knownActionsForClip[ knownActionsForClip.length - 1 ],
  30292. byClipCacheIndex = action._byClipCacheIndex;
  30293. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  30294. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  30295. knownActionsForClip.pop();
  30296. action._byClipCacheIndex = null;
  30297. const actionByRoot = actionsForClip.actionByRoot,
  30298. rootUuid = ( action._localRoot || this._root ).uuid;
  30299. delete actionByRoot[ rootUuid ];
  30300. if ( knownActionsForClip.length === 0 ) {
  30301. delete actionsByClip[ clipUuid ];
  30302. }
  30303. this._removeInactiveBindingsForAction( action );
  30304. }
  30305. _removeInactiveBindingsForAction( action ) {
  30306. const bindings = action._propertyBindings;
  30307. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30308. const binding = bindings[ i ];
  30309. if ( -- binding.referenceCount === 0 ) {
  30310. this._removeInactiveBinding( binding );
  30311. }
  30312. }
  30313. }
  30314. _lendAction( action ) {
  30315. // [ active actions | inactive actions ]
  30316. // [ active actions >| inactive actions ]
  30317. // s a
  30318. // <-swap->
  30319. // a s
  30320. const actions = this._actions,
  30321. prevIndex = action._cacheIndex,
  30322. lastActiveIndex = this._nActiveActions ++,
  30323. firstInactiveAction = actions[ lastActiveIndex ];
  30324. action._cacheIndex = lastActiveIndex;
  30325. actions[ lastActiveIndex ] = action;
  30326. firstInactiveAction._cacheIndex = prevIndex;
  30327. actions[ prevIndex ] = firstInactiveAction;
  30328. }
  30329. _takeBackAction( action ) {
  30330. // [ active actions | inactive actions ]
  30331. // [ active actions |< inactive actions ]
  30332. // a s
  30333. // <-swap->
  30334. // s a
  30335. const actions = this._actions,
  30336. prevIndex = action._cacheIndex,
  30337. firstInactiveIndex = -- this._nActiveActions,
  30338. lastActiveAction = actions[ firstInactiveIndex ];
  30339. action._cacheIndex = firstInactiveIndex;
  30340. actions[ firstInactiveIndex ] = action;
  30341. lastActiveAction._cacheIndex = prevIndex;
  30342. actions[ prevIndex ] = lastActiveAction;
  30343. }
  30344. // Memory management for PropertyMixer objects
  30345. _addInactiveBinding( binding, rootUuid, trackName ) {
  30346. const bindingsByRoot = this._bindingsByRootAndName,
  30347. bindings = this._bindings;
  30348. let bindingByName = bindingsByRoot[ rootUuid ];
  30349. if ( bindingByName === undefined ) {
  30350. bindingByName = {};
  30351. bindingsByRoot[ rootUuid ] = bindingByName;
  30352. }
  30353. bindingByName[ trackName ] = binding;
  30354. binding._cacheIndex = bindings.length;
  30355. bindings.push( binding );
  30356. }
  30357. _removeInactiveBinding( binding ) {
  30358. const bindings = this._bindings,
  30359. propBinding = binding.binding,
  30360. rootUuid = propBinding.rootNode.uuid,
  30361. trackName = propBinding.path,
  30362. bindingsByRoot = this._bindingsByRootAndName,
  30363. bindingByName = bindingsByRoot[ rootUuid ],
  30364. lastInactiveBinding = bindings[ bindings.length - 1 ],
  30365. cacheIndex = binding._cacheIndex;
  30366. lastInactiveBinding._cacheIndex = cacheIndex;
  30367. bindings[ cacheIndex ] = lastInactiveBinding;
  30368. bindings.pop();
  30369. delete bindingByName[ trackName ];
  30370. if ( Object.keys( bindingByName ).length === 0 ) {
  30371. delete bindingsByRoot[ rootUuid ];
  30372. }
  30373. }
  30374. _lendBinding( binding ) {
  30375. const bindings = this._bindings,
  30376. prevIndex = binding._cacheIndex,
  30377. lastActiveIndex = this._nActiveBindings ++,
  30378. firstInactiveBinding = bindings[ lastActiveIndex ];
  30379. binding._cacheIndex = lastActiveIndex;
  30380. bindings[ lastActiveIndex ] = binding;
  30381. firstInactiveBinding._cacheIndex = prevIndex;
  30382. bindings[ prevIndex ] = firstInactiveBinding;
  30383. }
  30384. _takeBackBinding( binding ) {
  30385. const bindings = this._bindings,
  30386. prevIndex = binding._cacheIndex,
  30387. firstInactiveIndex = -- this._nActiveBindings,
  30388. lastActiveBinding = bindings[ firstInactiveIndex ];
  30389. binding._cacheIndex = firstInactiveIndex;
  30390. bindings[ firstInactiveIndex ] = binding;
  30391. lastActiveBinding._cacheIndex = prevIndex;
  30392. bindings[ prevIndex ] = lastActiveBinding;
  30393. }
  30394. // Memory management of Interpolants for weight and time scale
  30395. _lendControlInterpolant() {
  30396. const interpolants = this._controlInterpolants,
  30397. lastActiveIndex = this._nActiveControlInterpolants ++;
  30398. let interpolant = interpolants[ lastActiveIndex ];
  30399. if ( interpolant === undefined ) {
  30400. interpolant = new LinearInterpolant(
  30401. new Float32Array( 2 ), new Float32Array( 2 ),
  30402. 1, _controlInterpolantsResultBuffer );
  30403. interpolant.__cacheIndex = lastActiveIndex;
  30404. interpolants[ lastActiveIndex ] = interpolant;
  30405. }
  30406. return interpolant;
  30407. }
  30408. _takeBackControlInterpolant( interpolant ) {
  30409. const interpolants = this._controlInterpolants,
  30410. prevIndex = interpolant.__cacheIndex,
  30411. firstInactiveIndex = -- this._nActiveControlInterpolants,
  30412. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  30413. interpolant.__cacheIndex = firstInactiveIndex;
  30414. interpolants[ firstInactiveIndex ] = interpolant;
  30415. lastActiveInterpolant.__cacheIndex = prevIndex;
  30416. interpolants[ prevIndex ] = lastActiveInterpolant;
  30417. }
  30418. // return an action for a clip optionally using a custom root target
  30419. // object (this method allocates a lot of dynamic memory in case a
  30420. // previously unknown clip/root combination is specified)
  30421. clipAction( clip, optionalRoot, blendMode ) {
  30422. const root = optionalRoot || this._root,
  30423. rootUuid = root.uuid;
  30424. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  30425. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  30426. const actionsForClip = this._actionsByClip[ clipUuid ];
  30427. let prototypeAction = null;
  30428. if ( blendMode === undefined ) {
  30429. if ( clipObject !== null ) {
  30430. blendMode = clipObject.blendMode;
  30431. } else {
  30432. blendMode = NormalAnimationBlendMode;
  30433. }
  30434. }
  30435. if ( actionsForClip !== undefined ) {
  30436. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  30437. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  30438. return existingAction;
  30439. }
  30440. // we know the clip, so we don't have to parse all
  30441. // the bindings again but can just copy
  30442. prototypeAction = actionsForClip.knownActions[ 0 ];
  30443. // also, take the clip from the prototype action
  30444. if ( clipObject === null )
  30445. clipObject = prototypeAction._clip;
  30446. }
  30447. // clip must be known when specified via string
  30448. if ( clipObject === null ) return null;
  30449. // allocate all resources required to run it
  30450. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  30451. this._bindAction( newAction, prototypeAction );
  30452. // and make the action known to the memory manager
  30453. this._addInactiveAction( newAction, clipUuid, rootUuid );
  30454. return newAction;
  30455. }
  30456. // get an existing action
  30457. existingAction( clip, optionalRoot ) {
  30458. const root = optionalRoot || this._root,
  30459. rootUuid = root.uuid,
  30460. clipObject = typeof clip === 'string' ?
  30461. AnimationClip.findByName( root, clip ) : clip,
  30462. clipUuid = clipObject ? clipObject.uuid : clip,
  30463. actionsForClip = this._actionsByClip[ clipUuid ];
  30464. if ( actionsForClip !== undefined ) {
  30465. return actionsForClip.actionByRoot[ rootUuid ] || null;
  30466. }
  30467. return null;
  30468. }
  30469. // deactivates all previously scheduled actions
  30470. stopAllAction() {
  30471. const actions = this._actions,
  30472. nActions = this._nActiveActions;
  30473. for ( let i = nActions - 1; i >= 0; -- i ) {
  30474. actions[ i ].stop();
  30475. }
  30476. return this;
  30477. }
  30478. // advance the time and update apply the animation
  30479. update( deltaTime ) {
  30480. deltaTime *= this.timeScale;
  30481. const actions = this._actions,
  30482. nActions = this._nActiveActions,
  30483. time = this.time += deltaTime,
  30484. timeDirection = Math.sign( deltaTime ),
  30485. accuIndex = this._accuIndex ^= 1;
  30486. // run active actions
  30487. for ( let i = 0; i !== nActions; ++ i ) {
  30488. const action = actions[ i ];
  30489. action._update( time, deltaTime, timeDirection, accuIndex );
  30490. }
  30491. // update scene graph
  30492. const bindings = this._bindings,
  30493. nBindings = this._nActiveBindings;
  30494. for ( let i = 0; i !== nBindings; ++ i ) {
  30495. bindings[ i ].apply( accuIndex );
  30496. }
  30497. return this;
  30498. }
  30499. // Allows you to seek to a specific time in an animation.
  30500. setTime( timeInSeconds ) {
  30501. this.time = 0; // Zero out time attribute for AnimationMixer object;
  30502. for ( let i = 0; i < this._actions.length; i ++ ) {
  30503. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  30504. }
  30505. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  30506. }
  30507. // return this mixer's root target object
  30508. getRoot() {
  30509. return this._root;
  30510. }
  30511. // free all resources specific to a particular clip
  30512. uncacheClip( clip ) {
  30513. const actions = this._actions,
  30514. clipUuid = clip.uuid,
  30515. actionsByClip = this._actionsByClip,
  30516. actionsForClip = actionsByClip[ clipUuid ];
  30517. if ( actionsForClip !== undefined ) {
  30518. // note: just calling _removeInactiveAction would mess up the
  30519. // iteration state and also require updating the state we can
  30520. // just throw away
  30521. const actionsToRemove = actionsForClip.knownActions;
  30522. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  30523. const action = actionsToRemove[ i ];
  30524. this._deactivateAction( action );
  30525. const cacheIndex = action._cacheIndex,
  30526. lastInactiveAction = actions[ actions.length - 1 ];
  30527. action._cacheIndex = null;
  30528. action._byClipCacheIndex = null;
  30529. lastInactiveAction._cacheIndex = cacheIndex;
  30530. actions[ cacheIndex ] = lastInactiveAction;
  30531. actions.pop();
  30532. this._removeInactiveBindingsForAction( action );
  30533. }
  30534. delete actionsByClip[ clipUuid ];
  30535. }
  30536. }
  30537. // free all resources specific to a particular root target object
  30538. uncacheRoot( root ) {
  30539. const rootUuid = root.uuid,
  30540. actionsByClip = this._actionsByClip;
  30541. for ( const clipUuid in actionsByClip ) {
  30542. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  30543. action = actionByRoot[ rootUuid ];
  30544. if ( action !== undefined ) {
  30545. this._deactivateAction( action );
  30546. this._removeInactiveAction( action );
  30547. }
  30548. }
  30549. const bindingsByRoot = this._bindingsByRootAndName,
  30550. bindingByName = bindingsByRoot[ rootUuid ];
  30551. if ( bindingByName !== undefined ) {
  30552. for ( const trackName in bindingByName ) {
  30553. const binding = bindingByName[ trackName ];
  30554. binding.restoreOriginalState();
  30555. this._removeInactiveBinding( binding );
  30556. }
  30557. }
  30558. }
  30559. // remove a targeted clip from the cache
  30560. uncacheAction( clip, optionalRoot ) {
  30561. const action = this.existingAction( clip, optionalRoot );
  30562. if ( action !== null ) {
  30563. this._deactivateAction( action );
  30564. this._removeInactiveAction( action );
  30565. }
  30566. }
  30567. }
  30568. class RenderTarget3D extends RenderTarget {
  30569. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  30570. super( width, height, options );
  30571. this.isRenderTarget3D = true;
  30572. this.depth = depth;
  30573. this.texture = new Data3DTexture( null, width, height, depth );
  30574. this.texture.isRenderTargetTexture = true;
  30575. }
  30576. }
  30577. class RenderTargetArray extends RenderTarget {
  30578. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  30579. super( width, height, options );
  30580. this.isRenderTargetArray = true;
  30581. this.depth = depth;
  30582. this.texture = new DataArrayTexture( null, width, height, depth );
  30583. this.texture.isRenderTargetTexture = true;
  30584. }
  30585. }
  30586. class Uniform {
  30587. constructor( value ) {
  30588. this.value = value;
  30589. }
  30590. clone() {
  30591. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  30592. }
  30593. }
  30594. let _id$1 = 0;
  30595. class UniformsGroup extends EventDispatcher {
  30596. constructor() {
  30597. super();
  30598. this.isUniformsGroup = true;
  30599. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  30600. this.name = '';
  30601. this.usage = StaticDrawUsage;
  30602. this.uniforms = [];
  30603. }
  30604. add( uniform ) {
  30605. this.uniforms.push( uniform );
  30606. return this;
  30607. }
  30608. remove( uniform ) {
  30609. const index = this.uniforms.indexOf( uniform );
  30610. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  30611. return this;
  30612. }
  30613. setName( name ) {
  30614. this.name = name;
  30615. return this;
  30616. }
  30617. setUsage( value ) {
  30618. this.usage = value;
  30619. return this;
  30620. }
  30621. dispose() {
  30622. this.dispatchEvent( { type: 'dispose' } );
  30623. return this;
  30624. }
  30625. copy( source ) {
  30626. this.name = source.name;
  30627. this.usage = source.usage;
  30628. const uniformsSource = source.uniforms;
  30629. this.uniforms.length = 0;
  30630. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  30631. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  30632. for ( let j = 0; j < uniforms.length; j ++ ) {
  30633. this.uniforms.push( uniforms[ j ].clone() );
  30634. }
  30635. }
  30636. return this;
  30637. }
  30638. clone() {
  30639. return new this.constructor().copy( this );
  30640. }
  30641. }
  30642. class InstancedInterleavedBuffer extends InterleavedBuffer {
  30643. constructor( array, stride, meshPerAttribute = 1 ) {
  30644. super( array, stride );
  30645. this.isInstancedInterleavedBuffer = true;
  30646. this.meshPerAttribute = meshPerAttribute;
  30647. }
  30648. copy( source ) {
  30649. super.copy( source );
  30650. this.meshPerAttribute = source.meshPerAttribute;
  30651. return this;
  30652. }
  30653. clone( data ) {
  30654. const ib = super.clone( data );
  30655. ib.meshPerAttribute = this.meshPerAttribute;
  30656. return ib;
  30657. }
  30658. toJSON( data ) {
  30659. const json = super.toJSON( data );
  30660. json.isInstancedInterleavedBuffer = true;
  30661. json.meshPerAttribute = this.meshPerAttribute;
  30662. return json;
  30663. }
  30664. }
  30665. class GLBufferAttribute {
  30666. constructor( buffer, type, itemSize, elementSize, count ) {
  30667. this.isGLBufferAttribute = true;
  30668. this.name = '';
  30669. this.buffer = buffer;
  30670. this.type = type;
  30671. this.itemSize = itemSize;
  30672. this.elementSize = elementSize;
  30673. this.count = count;
  30674. this.version = 0;
  30675. }
  30676. set needsUpdate( value ) {
  30677. if ( value === true ) this.version ++;
  30678. }
  30679. setBuffer( buffer ) {
  30680. this.buffer = buffer;
  30681. return this;
  30682. }
  30683. setType( type, elementSize ) {
  30684. this.type = type;
  30685. this.elementSize = elementSize;
  30686. return this;
  30687. }
  30688. setItemSize( itemSize ) {
  30689. this.itemSize = itemSize;
  30690. return this;
  30691. }
  30692. setCount( count ) {
  30693. this.count = count;
  30694. return this;
  30695. }
  30696. }
  30697. const _matrix = /*@__PURE__*/ new Matrix4();
  30698. class Raycaster {
  30699. constructor( origin, direction, near = 0, far = Infinity ) {
  30700. this.ray = new Ray( origin, direction );
  30701. // direction is assumed to be normalized (for accurate distance calculations)
  30702. this.near = near;
  30703. this.far = far;
  30704. this.camera = null;
  30705. this.layers = new Layers();
  30706. this.params = {
  30707. Mesh: {},
  30708. Line: { threshold: 1 },
  30709. LOD: {},
  30710. Points: { threshold: 1 },
  30711. Sprite: {}
  30712. };
  30713. }
  30714. set( origin, direction ) {
  30715. // direction is assumed to be normalized (for accurate distance calculations)
  30716. this.ray.set( origin, direction );
  30717. }
  30718. setFromCamera( coords, camera ) {
  30719. if ( camera.isPerspectiveCamera ) {
  30720. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  30721. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  30722. this.camera = camera;
  30723. } else if ( camera.isOrthographicCamera ) {
  30724. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  30725. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  30726. this.camera = camera;
  30727. } else {
  30728. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  30729. }
  30730. }
  30731. setFromXRController( controller ) {
  30732. _matrix.identity().extractRotation( controller.matrixWorld );
  30733. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  30734. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  30735. return this;
  30736. }
  30737. intersectObject( object, recursive = true, intersects = [] ) {
  30738. intersect( object, this, intersects, recursive );
  30739. intersects.sort( ascSort );
  30740. return intersects;
  30741. }
  30742. intersectObjects( objects, recursive = true, intersects = [] ) {
  30743. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  30744. intersect( objects[ i ], this, intersects, recursive );
  30745. }
  30746. intersects.sort( ascSort );
  30747. return intersects;
  30748. }
  30749. }
  30750. function ascSort( a, b ) {
  30751. return a.distance - b.distance;
  30752. }
  30753. function intersect( object, raycaster, intersects, recursive ) {
  30754. let propagate = true;
  30755. if ( object.layers.test( raycaster.layers ) ) {
  30756. const result = object.raycast( raycaster, intersects );
  30757. if ( result === false ) propagate = false;
  30758. }
  30759. if ( propagate === true && recursive === true ) {
  30760. const children = object.children;
  30761. for ( let i = 0, l = children.length; i < l; i ++ ) {
  30762. intersect( children[ i ], raycaster, intersects, true );
  30763. }
  30764. }
  30765. }
  30766. /**
  30767. * This class can be used to represent points in 3D space as
  30768. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  30769. */
  30770. class Spherical {
  30771. /**
  30772. * Constructs a new spherical.
  30773. *
  30774. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  30775. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  30776. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  30777. */
  30778. constructor( radius = 1, phi = 0, theta = 0 ) {
  30779. /**
  30780. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  30781. *
  30782. * @type {number}
  30783. * @default 1
  30784. */
  30785. this.radius = radius;
  30786. /**
  30787. * The polar angle in radians from the y (up) axis.
  30788. *
  30789. * @type {number}
  30790. * @default 0
  30791. */
  30792. this.phi = phi;
  30793. /**
  30794. * The equator/azimuthal angle in radians around the y (up) axis.
  30795. *
  30796. * @type {number}
  30797. * @default 0
  30798. */
  30799. this.theta = theta;
  30800. }
  30801. /**
  30802. * Sets the spherical components by copying the given values.
  30803. *
  30804. * @param {number} radius - The radius.
  30805. * @param {number} phi - The polar angle.
  30806. * @param {number} theta - The azimuthal angle.
  30807. * @return {Spherical} A reference to this spherical.
  30808. */
  30809. set( radius, phi, theta ) {
  30810. this.radius = radius;
  30811. this.phi = phi;
  30812. this.theta = theta;
  30813. return this;
  30814. }
  30815. /**
  30816. * Copies the values of the given spherical to this instance.
  30817. *
  30818. * @param {Spherical} other - The spherical to copy.
  30819. * @return {Spherical} A reference to this spherical.
  30820. */
  30821. copy( other ) {
  30822. this.radius = other.radius;
  30823. this.phi = other.phi;
  30824. this.theta = other.theta;
  30825. return this;
  30826. }
  30827. /**
  30828. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  30829. * `0.000001`.
  30830. *
  30831. * @return {Spherical} A reference to this spherical.
  30832. */
  30833. makeSafe() {
  30834. const EPS = 0.000001;
  30835. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  30836. return this;
  30837. }
  30838. /**
  30839. * Sets the spherical components from the given vector which is assumed to hold
  30840. * Cartesian coordinates.
  30841. *
  30842. * @param {Vector3} v - The vector to set.
  30843. * @return {Spherical} A reference to this spherical.
  30844. */
  30845. setFromVector3( v ) {
  30846. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30847. }
  30848. /**
  30849. * Sets the spherical components from the given Cartesian coordinates.
  30850. *
  30851. * @param {number} x - The x value.
  30852. * @param {number} y - The x value.
  30853. * @param {number} z - The x value.
  30854. * @return {Spherical} A reference to this spherical.
  30855. */
  30856. setFromCartesianCoords( x, y, z ) {
  30857. this.radius = Math.sqrt( x * x + y * y + z * z );
  30858. if ( this.radius === 0 ) {
  30859. this.theta = 0;
  30860. this.phi = 0;
  30861. } else {
  30862. this.theta = Math.atan2( x, z );
  30863. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  30864. }
  30865. return this;
  30866. }
  30867. /**
  30868. * Returns a new spherical with copied values from this instance.
  30869. *
  30870. * @return {Spherical} A clone of this instance.
  30871. */
  30872. clone() {
  30873. return new this.constructor().copy( this );
  30874. }
  30875. }
  30876. /**
  30877. * This class can be used to represent points in 3D space as
  30878. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  30879. */
  30880. class Cylindrical {
  30881. /**
  30882. * Constructs a new cylindrical.
  30883. *
  30884. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  30885. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  30886. * @param {number} [y=0] - The height above the x-z plane.
  30887. */
  30888. constructor( radius = 1, theta = 0, y = 0 ) {
  30889. /**
  30890. * The distance from the origin to a point in the x-z plane.
  30891. *
  30892. * @type {number}
  30893. * @default 1
  30894. */
  30895. this.radius = radius;
  30896. /**
  30897. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  30898. *
  30899. * @type {number}
  30900. * @default 0
  30901. */
  30902. this.theta = theta;
  30903. /**
  30904. * The height above the x-z plane.
  30905. *
  30906. * @type {number}
  30907. * @default 0
  30908. */
  30909. this.y = y;
  30910. }
  30911. /**
  30912. * Sets the cylindrical components by copying the given values.
  30913. *
  30914. * @param {number} radius - The radius.
  30915. * @param {number} theta - The theta angle.
  30916. * @param {number} y - The height value.
  30917. * @return {Cylindrical} A reference to this cylindrical.
  30918. */
  30919. set( radius, theta, y ) {
  30920. this.radius = radius;
  30921. this.theta = theta;
  30922. this.y = y;
  30923. return this;
  30924. }
  30925. /**
  30926. * Copies the values of the given cylindrical to this instance.
  30927. *
  30928. * @param {Cylindrical} other - The cylindrical to copy.
  30929. * @return {Cylindrical} A reference to this cylindrical.
  30930. */
  30931. copy( other ) {
  30932. this.radius = other.radius;
  30933. this.theta = other.theta;
  30934. this.y = other.y;
  30935. return this;
  30936. }
  30937. /**
  30938. * Sets the cylindrical components from the given vector which is assumed to hold
  30939. * Cartesian coordinates.
  30940. *
  30941. * @param {Vector3} v - The vector to set.
  30942. * @return {Cylindrical} A reference to this cylindrical.
  30943. */
  30944. setFromVector3( v ) {
  30945. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30946. }
  30947. /**
  30948. * Sets the cylindrical components from the given Cartesian coordinates.
  30949. *
  30950. * @param {number} x - The x value.
  30951. * @param {number} y - The x value.
  30952. * @param {number} z - The x value.
  30953. * @return {Cylindrical} A reference to this cylindrical.
  30954. */
  30955. setFromCartesianCoords( x, y, z ) {
  30956. this.radius = Math.sqrt( x * x + z * z );
  30957. this.theta = Math.atan2( x, z );
  30958. this.y = y;
  30959. return this;
  30960. }
  30961. /**
  30962. * Returns a new cylindrical with copied values from this instance.
  30963. *
  30964. * @return {Cylindrical} A clone of this instance.
  30965. */
  30966. clone() {
  30967. return new this.constructor().copy( this );
  30968. }
  30969. }
  30970. /**
  30971. * Represents a 2x2 matrix.
  30972. *
  30973. * A Note on Row-Major and Column-Major Ordering:
  30974. *
  30975. * The constructor and {@link Matrix2#set} method take arguments in
  30976. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  30977. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  30978. * This means that calling:
  30979. * ```js
  30980. * const m = new THREE.Matrix2();
  30981. * m.set( 11, 12,
  30982. * 21, 22 );
  30983. * ```
  30984. * will result in the elements array containing:
  30985. * ```js
  30986. * m.elements = [ 11, 21,
  30987. * 12, 22 ];
  30988. * ```
  30989. * and internally all calculations are performed using column-major ordering.
  30990. * However, as the actual ordering makes no difference mathematically and
  30991. * most people are used to thinking about matrices in row-major order, the
  30992. * three.js documentation shows matrices in row-major order. Just bear in
  30993. * mind that if you are reading the source code, you'll have to take the
  30994. * transpose of any matrices outlined here to make sense of the calculations.
  30995. */
  30996. class Matrix2 {
  30997. /**
  30998. * Constructs a new 2x2 matrix. The arguments are supposed to be
  30999. * in row-major order. If no arguments are provided, the constructor
  31000. * initializes the matrix as an identity matrix.
  31001. *
  31002. * @param {number} [n11] - 1-1 matrix element.
  31003. * @param {number} [n12] - 1-2 matrix element.
  31004. * @param {number} [n21] - 2-1 matrix element.
  31005. * @param {number} [n22] - 2-2 matrix element.
  31006. */
  31007. constructor( n11, n12, n21, n22 ) {
  31008. /**
  31009. * This flag can be used for type testing.
  31010. *
  31011. * @type {boolean}
  31012. * @readonly
  31013. * @default true
  31014. */
  31015. Matrix2.prototype.isMatrix2 = true;
  31016. /**
  31017. * A column-major list of matrix values.
  31018. *
  31019. * @type {Array<number>}
  31020. */
  31021. this.elements = [
  31022. 1, 0,
  31023. 0, 1,
  31024. ];
  31025. if ( n11 !== undefined ) {
  31026. this.set( n11, n12, n21, n22 );
  31027. }
  31028. }
  31029. /**
  31030. * Sets this matrix to the 2x2 identity matrix.
  31031. *
  31032. * @return {Matrix2} A reference to this matrix.
  31033. */
  31034. identity() {
  31035. this.set(
  31036. 1, 0,
  31037. 0, 1,
  31038. );
  31039. return this;
  31040. }
  31041. /**
  31042. * Sets the elements of the matrix from the given array.
  31043. *
  31044. * @param {Array<number>} array - The matrix elements in column-major order.
  31045. * @param {number} [offset=0] - Index of the first element in the array.
  31046. * @return {Matrix2} A reference to this matrix.
  31047. */
  31048. fromArray( array, offset = 0 ) {
  31049. for ( let i = 0; i < 4; i ++ ) {
  31050. this.elements[ i ] = array[ i + offset ];
  31051. }
  31052. return this;
  31053. }
  31054. /**
  31055. * Sets the elements of the matrix.The arguments are supposed to be
  31056. * in row-major order.
  31057. *
  31058. * @param {number} n11 - 1-1 matrix element.
  31059. * @param {number} n12 - 1-2 matrix element.
  31060. * @param {number} n21 - 2-1 matrix element.
  31061. * @param {number} n22 - 2-2 matrix element.
  31062. * @return {Matrix2} A reference to this matrix.
  31063. */
  31064. set( n11, n12, n21, n22 ) {
  31065. const te = this.elements;
  31066. te[ 0 ] = n11; te[ 2 ] = n12;
  31067. te[ 1 ] = n21; te[ 3 ] = n22;
  31068. return this;
  31069. }
  31070. }
  31071. const _vector$4 = /*@__PURE__*/ new Vector2();
  31072. /**
  31073. * Represents an axis-aligned bounding box (AABB) in 2D space.
  31074. */
  31075. class Box2 {
  31076. /**
  31077. * Constructs a new bounding box.
  31078. *
  31079. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  31080. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  31081. */
  31082. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  31083. /**
  31084. * This flag can be used for type testing.
  31085. *
  31086. * @type {boolean}
  31087. * @readonly
  31088. * @default true
  31089. */
  31090. this.isBox2 = true;
  31091. /**
  31092. * The lower boundary of the box.
  31093. *
  31094. * @type {Vector2}
  31095. */
  31096. this.min = min;
  31097. /**
  31098. * The upper boundary of the box.
  31099. *
  31100. * @type {Vector2}
  31101. */
  31102. this.max = max;
  31103. }
  31104. /**
  31105. * Sets the lower and upper boundaries of this box.
  31106. * Please note that this method only copies the values from the given objects.
  31107. *
  31108. * @param {Vector2} min - The lower boundary of the box.
  31109. * @param {Vector2} max - The upper boundary of the box.
  31110. * @return {Box2} A reference to this bounding box.
  31111. */
  31112. set( min, max ) {
  31113. this.min.copy( min );
  31114. this.max.copy( max );
  31115. return this;
  31116. }
  31117. /**
  31118. * Sets the upper and lower bounds of this box so it encloses the position data
  31119. * in the given array.
  31120. *
  31121. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  31122. * @return {Box2} A reference to this bounding box.
  31123. */
  31124. setFromPoints( points ) {
  31125. this.makeEmpty();
  31126. for ( let i = 0, il = points.length; i < il; i ++ ) {
  31127. this.expandByPoint( points[ i ] );
  31128. }
  31129. return this;
  31130. }
  31131. /**
  31132. * Centers this box on the given center vector and sets this box's width, height and
  31133. * depth to the given size values.
  31134. *
  31135. * @param {Vector2} center - The center of the box.
  31136. * @param {Vector2} size - The x and y dimensions of the box.
  31137. * @return {Box2} A reference to this bounding box.
  31138. */
  31139. setFromCenterAndSize( center, size ) {
  31140. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  31141. this.min.copy( center ).sub( halfSize );
  31142. this.max.copy( center ).add( halfSize );
  31143. return this;
  31144. }
  31145. /**
  31146. * Returns a new box with copied values from this instance.
  31147. *
  31148. * @return {Box2} A clone of this instance.
  31149. */
  31150. clone() {
  31151. return new this.constructor().copy( this );
  31152. }
  31153. /**
  31154. * Copies the values of the given box to this instance.
  31155. *
  31156. * @param {Box2} box - The box to copy.
  31157. * @return {Box2} A reference to this bounding box.
  31158. */
  31159. copy( box ) {
  31160. this.min.copy( box.min );
  31161. this.max.copy( box.max );
  31162. return this;
  31163. }
  31164. /**
  31165. * Makes this box empty which means in encloses a zero space in 2D.
  31166. *
  31167. * @return {Box2} A reference to this bounding box.
  31168. */
  31169. makeEmpty() {
  31170. this.min.x = this.min.y = + Infinity;
  31171. this.max.x = this.max.y = - Infinity;
  31172. return this;
  31173. }
  31174. /**
  31175. * Returns true if this box includes zero points within its bounds.
  31176. * Note that a box with equal lower and upper bounds still includes one
  31177. * point, the one both bounds share.
  31178. *
  31179. * @return {boolean} Whether this box is empty or not.
  31180. */
  31181. isEmpty() {
  31182. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  31183. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  31184. }
  31185. /**
  31186. * Returns the center point of this box.
  31187. *
  31188. * @param {Vector2} target - The target vector that is used to store the method's result.
  31189. * @return {Vector2} The center point.
  31190. */
  31191. getCenter( target ) {
  31192. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  31193. }
  31194. /**
  31195. * Returns the dimensions of this box.
  31196. *
  31197. * @param {Vector2} target - The target vector that is used to store the method's result.
  31198. * @return {Vector2} The size.
  31199. */
  31200. getSize( target ) {
  31201. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  31202. }
  31203. /**
  31204. * Expands the boundaries of this box to include the given point.
  31205. *
  31206. * @param {Vector2} point - The point that should be included by the bounding box.
  31207. * @return {Box2} A reference to this bounding box.
  31208. */
  31209. expandByPoint( point ) {
  31210. this.min.min( point );
  31211. this.max.max( point );
  31212. return this;
  31213. }
  31214. /**
  31215. * Expands this box equilaterally by the given vector. The width of this
  31216. * box will be expanded by the x component of the vector in both
  31217. * directions. The height of this box will be expanded by the y component of
  31218. * the vector in both directions.
  31219. *
  31220. * @param {Vector2} vector - The vector that should expand the bounding box.
  31221. * @return {Box2} A reference to this bounding box.
  31222. */
  31223. expandByVector( vector ) {
  31224. this.min.sub( vector );
  31225. this.max.add( vector );
  31226. return this;
  31227. }
  31228. /**
  31229. * Expands each dimension of the box by the given scalar. If negative, the
  31230. * dimensions of the box will be contracted.
  31231. *
  31232. * @param {number} scalar - The scalar value that should expand the bounding box.
  31233. * @return {Box2} A reference to this bounding box.
  31234. */
  31235. expandByScalar( scalar ) {
  31236. this.min.addScalar( - scalar );
  31237. this.max.addScalar( scalar );
  31238. return this;
  31239. }
  31240. /**
  31241. * Returns `true` if the given point lies within or on the boundaries of this box.
  31242. *
  31243. * @param {Vector2} point - The point to test.
  31244. * @return {boolean} Whether the bounding box contains the given point or not.
  31245. */
  31246. containsPoint( point ) {
  31247. return point.x >= this.min.x && point.x <= this.max.x &&
  31248. point.y >= this.min.y && point.y <= this.max.y;
  31249. }
  31250. /**
  31251. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  31252. * If this box and the given one are identical, this function also returns `true`.
  31253. *
  31254. * @param {Box2} box - The bounding box to test.
  31255. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  31256. */
  31257. containsBox( box ) {
  31258. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  31259. this.min.y <= box.min.y && box.max.y <= this.max.y;
  31260. }
  31261. /**
  31262. * Returns a point as a proportion of this box's width and height.
  31263. *
  31264. * @param {Vector2} point - A point in 2D space.
  31265. * @param {Vector2} target - The target vector that is used to store the method's result.
  31266. * @return {Vector2} A point as a proportion of this box's width and height.
  31267. */
  31268. getParameter( point, target ) {
  31269. // This can potentially have a divide by zero if the box
  31270. // has a size dimension of 0.
  31271. return target.set(
  31272. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  31273. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  31274. );
  31275. }
  31276. /**
  31277. * Returns `true` if the given bounding box intersects with this bounding box.
  31278. *
  31279. * @param {Box2} box - The bounding box to test.
  31280. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  31281. */
  31282. intersectsBox( box ) {
  31283. // using 4 splitting planes to rule out intersections
  31284. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  31285. box.max.y >= this.min.y && box.min.y <= this.max.y;
  31286. }
  31287. /**
  31288. * Clamps the given point within the bounds of this box.
  31289. *
  31290. * @param {Vector2} point - The point to clamp.
  31291. * @param {Vector2} target - The target vector that is used to store the method's result.
  31292. * @return {Vector2} The clamped point.
  31293. */
  31294. clampPoint( point, target ) {
  31295. return target.copy( point ).clamp( this.min, this.max );
  31296. }
  31297. /**
  31298. * Returns the euclidean distance from any edge of this box to the specified point. If
  31299. * the given point lies inside of this box, the distance will be `0`.
  31300. *
  31301. * @param {Vector2} point - The point to compute the distance to.
  31302. * @return {number} The euclidean distance.
  31303. */
  31304. distanceToPoint( point ) {
  31305. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  31306. }
  31307. /**
  31308. * Computes the intersection of this bounding box and the given one, setting the upper
  31309. * bound of this box to the lesser of the two boxes' upper bounds and the
  31310. * lower bound of this box to the greater of the two boxes' lower bounds. If
  31311. * there's no overlap, makes this box empty.
  31312. *
  31313. * @param {Box2} box - The bounding box to intersect with.
  31314. * @return {Box2} A reference to this bounding box.
  31315. */
  31316. intersect( box ) {
  31317. this.min.max( box.min );
  31318. this.max.min( box.max );
  31319. if ( this.isEmpty() ) this.makeEmpty();
  31320. return this;
  31321. }
  31322. /**
  31323. * Computes the union of this box and another and the given one, setting the upper
  31324. * bound of this box to the greater of the two boxes' upper bounds and the
  31325. * lower bound of this box to the lesser of the two boxes' lower bounds.
  31326. *
  31327. * @param {Box2} box - The bounding box that will be unioned with this instance.
  31328. * @return {Box2} A reference to this bounding box.
  31329. */
  31330. union( box ) {
  31331. this.min.min( box.min );
  31332. this.max.max( box.max );
  31333. return this;
  31334. }
  31335. /**
  31336. * Adds the given offset to both the upper and lower bounds of this bounding box,
  31337. * effectively moving it in 2D space.
  31338. *
  31339. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  31340. * @return {Box2} A reference to this bounding box.
  31341. */
  31342. translate( offset ) {
  31343. this.min.add( offset );
  31344. this.max.add( offset );
  31345. return this;
  31346. }
  31347. /**
  31348. * Returns `true` if this bounding box is equal with the given one.
  31349. *
  31350. * @param {Box2} box - The box to test for equality.
  31351. * @return {boolean} Whether this bounding box is equal with the given one.
  31352. */
  31353. equals( box ) {
  31354. return box.min.equals( this.min ) && box.max.equals( this.max );
  31355. }
  31356. }
  31357. const _startP = /*@__PURE__*/ new Vector3();
  31358. const _startEnd = /*@__PURE__*/ new Vector3();
  31359. /**
  31360. * An analytical line segment in 3D space represented by a start and end point.
  31361. */
  31362. class Line3 {
  31363. /**
  31364. * Constructs a new line segment.
  31365. *
  31366. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  31367. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  31368. */
  31369. constructor( start = new Vector3(), end = new Vector3() ) {
  31370. /**
  31371. * Start of the line segment.
  31372. *
  31373. * @type {Vector3}
  31374. */
  31375. this.start = start;
  31376. /**
  31377. * End of the line segment.
  31378. *
  31379. * @type {Vector3}
  31380. */
  31381. this.end = end;
  31382. }
  31383. /**
  31384. * Sets the start and end values by copying the given vectors.
  31385. *
  31386. * @param {Vector3} start - The start point.
  31387. * @param {Vector3} end - The end point.
  31388. * @return {Line3} A reference to this line segment.
  31389. */
  31390. set( start, end ) {
  31391. this.start.copy( start );
  31392. this.end.copy( end );
  31393. return this;
  31394. }
  31395. /**
  31396. * Copies the values of the given line segment to this instance.
  31397. *
  31398. * @param {Line3} line - The line segment to copy.
  31399. * @return {Line3} A reference to this line segment.
  31400. */
  31401. copy( line ) {
  31402. this.start.copy( line.start );
  31403. this.end.copy( line.end );
  31404. return this;
  31405. }
  31406. /**
  31407. * Returns the center of the line segment.
  31408. *
  31409. * @param {Vector3} target - The target vector that is used to store the method's result.
  31410. * @return {Vector3} The center point.
  31411. */
  31412. getCenter( target ) {
  31413. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  31414. }
  31415. /**
  31416. * Returns the delta vector of the line segment's start and end point.
  31417. *
  31418. * @param {Vector3} target - The target vector that is used to store the method's result.
  31419. * @return {Vector3} The delta vector.
  31420. */
  31421. delta( target ) {
  31422. return target.subVectors( this.end, this.start );
  31423. }
  31424. /**
  31425. * Returns the squared Euclidean distance between the line' start and end point.
  31426. *
  31427. * @return {number} The squared Euclidean distance.
  31428. */
  31429. distanceSq() {
  31430. return this.start.distanceToSquared( this.end );
  31431. }
  31432. /**
  31433. * Returns the Euclidean distance between the line' start and end point.
  31434. *
  31435. * @return {number} The Euclidean distance.
  31436. */
  31437. distance() {
  31438. return this.start.distanceTo( this.end );
  31439. }
  31440. /**
  31441. * Returns a vector at a certain position along the line segment.
  31442. *
  31443. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  31444. * @param {Vector3} target - The target vector that is used to store the method's result.
  31445. * @return {Vector3} The delta vector.
  31446. */
  31447. at( t, target ) {
  31448. return this.delta( target ).multiplyScalar( t ).add( this.start );
  31449. }
  31450. /**
  31451. * Returns a point parameter based on the closest point as projected on the line segment.
  31452. *
  31453. * @param {Vector3} point - The point for which to return a point parameter.
  31454. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  31455. * @return {number} The point parameter.
  31456. */
  31457. closestPointToPointParameter( point, clampToLine ) {
  31458. _startP.subVectors( point, this.start );
  31459. _startEnd.subVectors( this.end, this.start );
  31460. const startEnd2 = _startEnd.dot( _startEnd );
  31461. const startEnd_startP = _startEnd.dot( _startP );
  31462. let t = startEnd_startP / startEnd2;
  31463. if ( clampToLine ) {
  31464. t = clamp( t, 0, 1 );
  31465. }
  31466. return t;
  31467. }
  31468. /**
  31469. * Returns the closets point on the line for a given point.
  31470. *
  31471. * @param {Vector3} point - The point to compute the closest point on the line for.
  31472. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  31473. * @param {Vector3} target - The target vector that is used to store the method's result.
  31474. * @return {Vector3} The closest point on the line.
  31475. */
  31476. closestPointToPoint( point, clampToLine, target ) {
  31477. const t = this.closestPointToPointParameter( point, clampToLine );
  31478. return this.delta( target ).multiplyScalar( t ).add( this.start );
  31479. }
  31480. /**
  31481. * Applies a 4x4 transformation matrix to this line segment.
  31482. *
  31483. * @param {Matrix4} matrix - The transformation matrix.
  31484. * @return {Line3} A reference to this line segment.
  31485. */
  31486. applyMatrix4( matrix ) {
  31487. this.start.applyMatrix4( matrix );
  31488. this.end.applyMatrix4( matrix );
  31489. return this;
  31490. }
  31491. /**
  31492. * Returns `true` if this line segment is equal with the given one.
  31493. *
  31494. * @param {Line3} line - The line segment to test for equality.
  31495. * @return {boolean} Whether this line segment is equal with the given one.
  31496. */
  31497. equals( line ) {
  31498. return line.start.equals( this.start ) && line.end.equals( this.end );
  31499. }
  31500. /**
  31501. * Returns a new line segment with copied values from this instance.
  31502. *
  31503. * @return {Line3} A clone of this instance.
  31504. */
  31505. clone() {
  31506. return new this.constructor().copy( this );
  31507. }
  31508. }
  31509. const _vector$3 = /*@__PURE__*/ new Vector3();
  31510. /**
  31511. * This displays a cone shaped helper object for a {@link SpotLight}.
  31512. *
  31513. * ```js
  31514. * const spotLight = new THREE.SpotLight( 0xffffff );
  31515. * spotLight.position.set( 10, 10, 10 );
  31516. * scene.add( spotLight );
  31517. *
  31518. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  31519. * scene.add( spotLightHelper );
  31520. * ```
  31521. *
  31522. * @augments Object3D
  31523. */
  31524. class SpotLightHelper extends Object3D {
  31525. /**
  31526. * Constructs a new spot light helper.
  31527. *
  31528. * @param {HemisphereLight} light - The light to be visualized.
  31529. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  31530. * the color of the light.
  31531. */
  31532. constructor( light, color ) {
  31533. super();
  31534. /**
  31535. * The light being visualized.
  31536. *
  31537. * @type {SpotLight}
  31538. */
  31539. this.light = light;
  31540. this.matrixAutoUpdate = false;
  31541. /**
  31542. * The color parameter passed in the constructor.
  31543. * If not set, the helper will take the color of the light.
  31544. *
  31545. * @type {number|Color|string}
  31546. */
  31547. this.color = color;
  31548. this.type = 'SpotLightHelper';
  31549. const geometry = new BufferGeometry();
  31550. const positions = [
  31551. 0, 0, 0, 0, 0, 1,
  31552. 0, 0, 0, 1, 0, 1,
  31553. 0, 0, 0, -1, 0, 1,
  31554. 0, 0, 0, 0, 1, 1,
  31555. 0, 0, 0, 0, -1, 1
  31556. ];
  31557. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  31558. const p1 = ( i / l ) * Math.PI * 2;
  31559. const p2 = ( j / l ) * Math.PI * 2;
  31560. positions.push(
  31561. Math.cos( p1 ), Math.sin( p1 ), 1,
  31562. Math.cos( p2 ), Math.sin( p2 ), 1
  31563. );
  31564. }
  31565. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31566. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  31567. this.cone = new LineSegments( geometry, material );
  31568. this.add( this.cone );
  31569. this.update();
  31570. }
  31571. /**
  31572. * Frees the GPU-related resources allocated by this instance. Call this
  31573. * method whenever this instance is no longer used in your app.
  31574. */
  31575. dispose() {
  31576. this.cone.geometry.dispose();
  31577. this.cone.material.dispose();
  31578. }
  31579. /**
  31580. * Updates the helper to match the position and direction of the
  31581. * light being visualized.
  31582. */
  31583. update() {
  31584. this.light.updateWorldMatrix( true, false );
  31585. this.light.target.updateWorldMatrix( true, false );
  31586. // update the local matrix based on the parent and light target transforms
  31587. if ( this.parent ) {
  31588. this.parent.updateWorldMatrix( true );
  31589. this.matrix
  31590. .copy( this.parent.matrixWorld )
  31591. .invert()
  31592. .multiply( this.light.matrixWorld );
  31593. } else {
  31594. this.matrix.copy( this.light.matrixWorld );
  31595. }
  31596. this.matrixWorld.copy( this.light.matrixWorld );
  31597. const coneLength = this.light.distance ? this.light.distance : 1000;
  31598. const coneWidth = coneLength * Math.tan( this.light.angle );
  31599. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  31600. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  31601. this.cone.lookAt( _vector$3 );
  31602. if ( this.color !== undefined ) {
  31603. this.cone.material.color.set( this.color );
  31604. } else {
  31605. this.cone.material.color.copy( this.light.color );
  31606. }
  31607. }
  31608. }
  31609. const _vector$2 = /*@__PURE__*/ new Vector3();
  31610. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  31611. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  31612. /**
  31613. * A helper object to assist with visualizing a {@link Skeleton}.
  31614. *
  31615. * ```js
  31616. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  31617. * scene.add( helper );
  31618. * ```
  31619. *
  31620. * @augments LineSegments
  31621. */
  31622. class SkeletonHelper extends LineSegments {
  31623. /**
  31624. * Constructs a new hemisphere light helper.
  31625. *
  31626. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  31627. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  31628. */
  31629. constructor( object ) {
  31630. const bones = getBoneList( object );
  31631. const geometry = new BufferGeometry();
  31632. const vertices = [];
  31633. const colors = [];
  31634. const color1 = new Color( 0, 0, 1 );
  31635. const color2 = new Color( 0, 1, 0 );
  31636. for ( let i = 0; i < bones.length; i ++ ) {
  31637. const bone = bones[ i ];
  31638. if ( bone.parent && bone.parent.isBone ) {
  31639. vertices.push( 0, 0, 0 );
  31640. vertices.push( 0, 0, 0 );
  31641. colors.push( color1.r, color1.g, color1.b );
  31642. colors.push( color2.r, color2.g, color2.b );
  31643. }
  31644. }
  31645. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31646. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31647. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  31648. super( geometry, material );
  31649. /**
  31650. * This flag can be used for type testing.
  31651. *
  31652. * @type {boolean}
  31653. * @readonly
  31654. * @default true
  31655. */
  31656. this.isSkeletonHelper = true;
  31657. this.type = 'SkeletonHelper';
  31658. /**
  31659. * The object being visualized.
  31660. *
  31661. * @type {Object3D}
  31662. */
  31663. this.root = object;
  31664. /**
  31665. * he list of bones that the helper visualizes.
  31666. *
  31667. * @type {Array<Bone>}
  31668. */
  31669. this.bones = bones;
  31670. this.matrix = object.matrixWorld;
  31671. this.matrixAutoUpdate = false;
  31672. }
  31673. updateMatrixWorld( force ) {
  31674. const bones = this.bones;
  31675. const geometry = this.geometry;
  31676. const position = geometry.getAttribute( 'position' );
  31677. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  31678. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  31679. const bone = bones[ i ];
  31680. if ( bone.parent && bone.parent.isBone ) {
  31681. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  31682. _vector$2.setFromMatrixPosition( _boneMatrix );
  31683. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  31684. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  31685. _vector$2.setFromMatrixPosition( _boneMatrix );
  31686. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  31687. j += 2;
  31688. }
  31689. }
  31690. geometry.getAttribute( 'position' ).needsUpdate = true;
  31691. super.updateMatrixWorld( force );
  31692. }
  31693. /**
  31694. * Frees the GPU-related resources allocated by this instance. Call this
  31695. * method whenever this instance is no longer used in your app.
  31696. */
  31697. dispose() {
  31698. this.geometry.dispose();
  31699. this.material.dispose();
  31700. }
  31701. }
  31702. function getBoneList( object ) {
  31703. const boneList = [];
  31704. if ( object.isBone === true ) {
  31705. boneList.push( object );
  31706. }
  31707. for ( let i = 0; i < object.children.length; i ++ ) {
  31708. boneList.push( ...getBoneList( object.children[ i ] ) );
  31709. }
  31710. return boneList;
  31711. }
  31712. /**
  31713. * This displays a helper object consisting of a spherical mesh for
  31714. * visualizing an instance of {@link PointLight}.
  31715. *
  31716. * ```js
  31717. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  31718. * pointLight.position.set( 10, 10, 10 );
  31719. * scene.add( pointLight );
  31720. *
  31721. * const sphereSize = 1;
  31722. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  31723. * scene.add( pointLightHelper );
  31724. * ```
  31725. *
  31726. * @augments Mesh
  31727. */
  31728. class PointLightHelper extends Mesh {
  31729. /**
  31730. * Constructs a new point light helper.
  31731. *
  31732. * @param {PointLight} light - The light to be visualized.
  31733. * @param {number} [sphereSize=1] - The size of the sphere helper.
  31734. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  31735. * the color of the light.
  31736. */
  31737. constructor( light, sphereSize, color ) {
  31738. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  31739. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  31740. super( geometry, material );
  31741. /**
  31742. * The light being visualized.
  31743. *
  31744. * @type {HemisphereLight}
  31745. */
  31746. this.light = light;
  31747. /**
  31748. * The color parameter passed in the constructor.
  31749. * If not set, the helper will take the color of the light.
  31750. *
  31751. * @type {number|Color|string}
  31752. */
  31753. this.color = color;
  31754. this.type = 'PointLightHelper';
  31755. this.matrix = this.light.matrixWorld;
  31756. this.matrixAutoUpdate = false;
  31757. this.update();
  31758. /*
  31759. // TODO: delete this comment?
  31760. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  31761. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  31762. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  31763. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  31764. const d = light.distance;
  31765. if ( d === 0.0 ) {
  31766. this.lightDistance.visible = false;
  31767. } else {
  31768. this.lightDistance.scale.set( d, d, d );
  31769. }
  31770. this.add( this.lightDistance );
  31771. */
  31772. }
  31773. /**
  31774. * Frees the GPU-related resources allocated by this instance. Call this
  31775. * method whenever this instance is no longer used in your app.
  31776. */
  31777. dispose() {
  31778. this.geometry.dispose();
  31779. this.material.dispose();
  31780. }
  31781. /**
  31782. * Updates the helper to match the position of the
  31783. * light being visualized.
  31784. */
  31785. update() {
  31786. this.light.updateWorldMatrix( true, false );
  31787. if ( this.color !== undefined ) {
  31788. this.material.color.set( this.color );
  31789. } else {
  31790. this.material.color.copy( this.light.color );
  31791. }
  31792. /*
  31793. const d = this.light.distance;
  31794. if ( d === 0.0 ) {
  31795. this.lightDistance.visible = false;
  31796. } else {
  31797. this.lightDistance.visible = true;
  31798. this.lightDistance.scale.set( d, d, d );
  31799. }
  31800. */
  31801. }
  31802. }
  31803. const _vector$1 = /*@__PURE__*/ new Vector3();
  31804. const _color1 = /*@__PURE__*/ new Color();
  31805. const _color2 = /*@__PURE__*/ new Color();
  31806. /**
  31807. * Creates a visual aid consisting of a spherical mesh for a
  31808. * given {@link HemisphereLight}.
  31809. *
  31810. * ```js
  31811. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  31812. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  31813. * scene.add( helper );
  31814. * ```
  31815. *
  31816. * @augments Object3D
  31817. */
  31818. class HemisphereLightHelper extends Object3D {
  31819. /**
  31820. * Constructs a new hemisphere light helper.
  31821. *
  31822. * @param {HemisphereLight} light - The light to be visualized.
  31823. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  31824. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  31825. * the color of the light.
  31826. */
  31827. constructor( light, size, color ) {
  31828. super();
  31829. /**
  31830. * The light being visualized.
  31831. *
  31832. * @type {HemisphereLight}
  31833. */
  31834. this.light = light;
  31835. this.matrix = light.matrixWorld;
  31836. this.matrixAutoUpdate = false;
  31837. /**
  31838. * The color parameter passed in the constructor.
  31839. * If not set, the helper will take the color of the light.
  31840. *
  31841. * @type {number|Color|string}
  31842. */
  31843. this.color = color;
  31844. this.type = 'HemisphereLightHelper';
  31845. const geometry = new OctahedronGeometry( size );
  31846. geometry.rotateY( Math.PI * 0.5 );
  31847. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  31848. if ( this.color === undefined ) this.material.vertexColors = true;
  31849. const position = geometry.getAttribute( 'position' );
  31850. const colors = new Float32Array( position.count * 3 );
  31851. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  31852. this.add( new Mesh( geometry, this.material ) );
  31853. this.update();
  31854. }
  31855. /**
  31856. * Frees the GPU-related resources allocated by this instance. Call this
  31857. * method whenever this instance is no longer used in your app.
  31858. */
  31859. dispose() {
  31860. this.children[ 0 ].geometry.dispose();
  31861. this.children[ 0 ].material.dispose();
  31862. }
  31863. /**
  31864. * Updates the helper to match the position and direction of the
  31865. * light being visualized.
  31866. */
  31867. update() {
  31868. const mesh = this.children[ 0 ];
  31869. if ( this.color !== undefined ) {
  31870. this.material.color.set( this.color );
  31871. } else {
  31872. const colors = mesh.geometry.getAttribute( 'color' );
  31873. _color1.copy( this.light.color );
  31874. _color2.copy( this.light.groundColor );
  31875. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  31876. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  31877. colors.setXYZ( i, color.r, color.g, color.b );
  31878. }
  31879. colors.needsUpdate = true;
  31880. }
  31881. this.light.updateWorldMatrix( true, false );
  31882. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  31883. }
  31884. }
  31885. /**
  31886. * The helper is an object to define grids. Grids are two-dimensional
  31887. * arrays of lines.
  31888. *
  31889. * ```js
  31890. * const size = 10;
  31891. * const divisions = 10;
  31892. *
  31893. * const gridHelper = new THREE.GridHelper( size, divisions );
  31894. * scene.add( gridHelper );
  31895. * ```
  31896. *
  31897. * @augments LineSegments
  31898. */
  31899. class GridHelper extends LineSegments {
  31900. /**
  31901. * Constructs a new grid helper.
  31902. *
  31903. * @param {number} [size=10] - The size of the grid.
  31904. * @param {number} [divisions=10] - The number of divisions across the grid.
  31905. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  31906. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  31907. */
  31908. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  31909. color1 = new Color( color1 );
  31910. color2 = new Color( color2 );
  31911. const center = divisions / 2;
  31912. const step = size / divisions;
  31913. const halfSize = size / 2;
  31914. const vertices = [], colors = [];
  31915. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  31916. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  31917. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  31918. const color = i === center ? color1 : color2;
  31919. color.toArray( colors, j ); j += 3;
  31920. color.toArray( colors, j ); j += 3;
  31921. color.toArray( colors, j ); j += 3;
  31922. color.toArray( colors, j ); j += 3;
  31923. }
  31924. const geometry = new BufferGeometry();
  31925. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31926. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31927. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  31928. super( geometry, material );
  31929. this.type = 'GridHelper';
  31930. }
  31931. /**
  31932. * Frees the GPU-related resources allocated by this instance. Call this
  31933. * method whenever this instance is no longer used in your app.
  31934. */
  31935. dispose() {
  31936. this.geometry.dispose();
  31937. this.material.dispose();
  31938. }
  31939. }
  31940. /**
  31941. * This helper is an object to define polar grids. Grids are
  31942. * two-dimensional arrays of lines.
  31943. *
  31944. * ```js
  31945. * const radius = 10;
  31946. * const sectors = 16;
  31947. * const rings = 8;
  31948. * const divisions = 64;
  31949. *
  31950. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  31951. * scene.add( helper );
  31952. * ```
  31953. *
  31954. * @augments LineSegments
  31955. */
  31956. class PolarGridHelper extends LineSegments {
  31957. /**
  31958. * Constructs a new polar grid helper.
  31959. *
  31960. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  31961. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  31962. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  31963. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  31964. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  31965. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  31966. */
  31967. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  31968. color1 = new Color( color1 );
  31969. color2 = new Color( color2 );
  31970. const vertices = [];
  31971. const colors = [];
  31972. // create the sectors
  31973. if ( sectors > 1 ) {
  31974. for ( let i = 0; i < sectors; i ++ ) {
  31975. const v = ( i / sectors ) * ( Math.PI * 2 );
  31976. const x = Math.sin( v ) * radius;
  31977. const z = Math.cos( v ) * radius;
  31978. vertices.push( 0, 0, 0 );
  31979. vertices.push( x, 0, z );
  31980. const color = ( i & 1 ) ? color1 : color2;
  31981. colors.push( color.r, color.g, color.b );
  31982. colors.push( color.r, color.g, color.b );
  31983. }
  31984. }
  31985. // create the rings
  31986. for ( let i = 0; i < rings; i ++ ) {
  31987. const color = ( i & 1 ) ? color1 : color2;
  31988. const r = radius - ( radius / rings * i );
  31989. for ( let j = 0; j < divisions; j ++ ) {
  31990. // first vertex
  31991. let v = ( j / divisions ) * ( Math.PI * 2 );
  31992. let x = Math.sin( v ) * r;
  31993. let z = Math.cos( v ) * r;
  31994. vertices.push( x, 0, z );
  31995. colors.push( color.r, color.g, color.b );
  31996. // second vertex
  31997. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  31998. x = Math.sin( v ) * r;
  31999. z = Math.cos( v ) * r;
  32000. vertices.push( x, 0, z );
  32001. colors.push( color.r, color.g, color.b );
  32002. }
  32003. }
  32004. const geometry = new BufferGeometry();
  32005. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  32006. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  32007. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  32008. super( geometry, material );
  32009. this.type = 'PolarGridHelper';
  32010. }
  32011. /**
  32012. * Frees the GPU-related resources allocated by this instance. Call this
  32013. * method whenever this instance is no longer used in your app.
  32014. */
  32015. dispose() {
  32016. this.geometry.dispose();
  32017. this.material.dispose();
  32018. }
  32019. }
  32020. const _v1 = /*@__PURE__*/ new Vector3();
  32021. const _v2 = /*@__PURE__*/ new Vector3();
  32022. const _v3 = /*@__PURE__*/ new Vector3();
  32023. /**
  32024. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  32025. * effect on the scene. This consists of plane and a line representing the
  32026. * light's position and direction.
  32027. *
  32028. * ```js
  32029. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  32030. * scene.add( light );
  32031. *
  32032. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  32033. * scene.add( helper );
  32034. * ```
  32035. *
  32036. * @augments Object3D
  32037. */
  32038. class DirectionalLightHelper extends Object3D {
  32039. /**
  32040. * Constructs a new directional light helper.
  32041. *
  32042. * @param {DirectionalLight} light - The light to be visualized.
  32043. * @param {number} [size=1] - The dimensions of the plane.
  32044. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  32045. * the color of the light.
  32046. */
  32047. constructor( light, size, color ) {
  32048. super();
  32049. /**
  32050. * The light being visualized.
  32051. *
  32052. * @type {DirectionalLight}
  32053. */
  32054. this.light = light;
  32055. this.matrix = light.matrixWorld;
  32056. this.matrixAutoUpdate = false;
  32057. /**
  32058. * The color parameter passed in the constructor.
  32059. * If not set, the helper will take the color of the light.
  32060. *
  32061. * @type {number|Color|string}
  32062. */
  32063. this.color = color;
  32064. this.type = 'DirectionalLightHelper';
  32065. if ( size === undefined ) size = 1;
  32066. let geometry = new BufferGeometry();
  32067. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  32068. - size, size, 0,
  32069. size, size, 0,
  32070. size, - size, 0,
  32071. - size, - size, 0,
  32072. - size, size, 0
  32073. ], 3 ) );
  32074. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  32075. /**
  32076. * Contains the line showing the location of the directional light.
  32077. *
  32078. * @type {Line}
  32079. */
  32080. this.lightPlane = new Line( geometry, material );
  32081. this.add( this.lightPlane );
  32082. geometry = new BufferGeometry();
  32083. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  32084. /**
  32085. * Represents the target line of the directional light.
  32086. *
  32087. * @type {Line}
  32088. */
  32089. this.targetLine = new Line( geometry, material );
  32090. this.add( this.targetLine );
  32091. this.update();
  32092. }
  32093. /**
  32094. * Frees the GPU-related resources allocated by this instance. Call this
  32095. * method whenever this instance is no longer used in your app.
  32096. */
  32097. dispose() {
  32098. this.lightPlane.geometry.dispose();
  32099. this.lightPlane.material.dispose();
  32100. this.targetLine.geometry.dispose();
  32101. this.targetLine.material.dispose();
  32102. }
  32103. /**
  32104. * Updates the helper to match the position and direction of the
  32105. * light being visualized.
  32106. */
  32107. update() {
  32108. this.light.updateWorldMatrix( true, false );
  32109. this.light.target.updateWorldMatrix( true, false );
  32110. _v1.setFromMatrixPosition( this.light.matrixWorld );
  32111. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  32112. _v3.subVectors( _v2, _v1 );
  32113. this.lightPlane.lookAt( _v2 );
  32114. if ( this.color !== undefined ) {
  32115. this.lightPlane.material.color.set( this.color );
  32116. this.targetLine.material.color.set( this.color );
  32117. } else {
  32118. this.lightPlane.material.color.copy( this.light.color );
  32119. this.targetLine.material.color.copy( this.light.color );
  32120. }
  32121. this.targetLine.lookAt( _v2 );
  32122. this.targetLine.scale.z = _v3.length();
  32123. }
  32124. }
  32125. const _vector = /*@__PURE__*/ new Vector3();
  32126. const _camera = /*@__PURE__*/ new Camera();
  32127. /**
  32128. * This helps with visualizing what a camera contains in its frustum. It
  32129. * visualizes the frustum of a camera using a line segments.
  32130. *
  32131. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  32132. *
  32133. * `CameraHelper` must be a child of the scene.
  32134. *
  32135. * ```js
  32136. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  32137. * const helper = new THREE.CameraHelper( camera );
  32138. * scene.add( helper );
  32139. * ```
  32140. *
  32141. * @augments LineSegments
  32142. */
  32143. class CameraHelper extends LineSegments {
  32144. /**
  32145. * Constructs a new arrow helper.
  32146. *
  32147. * @param {Camera} camera - The camera to visualize.
  32148. */
  32149. constructor( camera ) {
  32150. const geometry = new BufferGeometry();
  32151. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  32152. const vertices = [];
  32153. const colors = [];
  32154. const pointMap = {};
  32155. // near
  32156. addLine( 'n1', 'n2' );
  32157. addLine( 'n2', 'n4' );
  32158. addLine( 'n4', 'n3' );
  32159. addLine( 'n3', 'n1' );
  32160. // far
  32161. addLine( 'f1', 'f2' );
  32162. addLine( 'f2', 'f4' );
  32163. addLine( 'f4', 'f3' );
  32164. addLine( 'f3', 'f1' );
  32165. // sides
  32166. addLine( 'n1', 'f1' );
  32167. addLine( 'n2', 'f2' );
  32168. addLine( 'n3', 'f3' );
  32169. addLine( 'n4', 'f4' );
  32170. // cone
  32171. addLine( 'p', 'n1' );
  32172. addLine( 'p', 'n2' );
  32173. addLine( 'p', 'n3' );
  32174. addLine( 'p', 'n4' );
  32175. // up
  32176. addLine( 'u1', 'u2' );
  32177. addLine( 'u2', 'u3' );
  32178. addLine( 'u3', 'u1' );
  32179. // target
  32180. addLine( 'c', 't' );
  32181. addLine( 'p', 'c' );
  32182. // cross
  32183. addLine( 'cn1', 'cn2' );
  32184. addLine( 'cn3', 'cn4' );
  32185. addLine( 'cf1', 'cf2' );
  32186. addLine( 'cf3', 'cf4' );
  32187. function addLine( a, b ) {
  32188. addPoint( a );
  32189. addPoint( b );
  32190. }
  32191. function addPoint( id ) {
  32192. vertices.push( 0, 0, 0 );
  32193. colors.push( 0, 0, 0 );
  32194. if ( pointMap[ id ] === undefined ) {
  32195. pointMap[ id ] = [];
  32196. }
  32197. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  32198. }
  32199. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  32200. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  32201. super( geometry, material );
  32202. this.type = 'CameraHelper';
  32203. /**
  32204. * The camera being visualized.
  32205. *
  32206. * @type {Camera}
  32207. */
  32208. this.camera = camera;
  32209. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  32210. this.matrix = camera.matrixWorld;
  32211. this.matrixAutoUpdate = false;
  32212. /**
  32213. * This contains the points used to visualize the camera.
  32214. *
  32215. * @type {Object<string,Array<number>>}
  32216. */
  32217. this.pointMap = pointMap;
  32218. this.update();
  32219. // colors
  32220. const colorFrustum = new Color( 0xffaa00 );
  32221. const colorCone = new Color( 0xff0000 );
  32222. const colorUp = new Color( 0x00aaff );
  32223. const colorTarget = new Color( 0xffffff );
  32224. const colorCross = new Color( 0x333333 );
  32225. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  32226. }
  32227. /**
  32228. * Defines the colors of the helper.
  32229. *
  32230. * @param {Color} frustum - The frustum line color.
  32231. * @param {Color} cone - The cone line color.
  32232. * @param {Color} up - The up line color.
  32233. * @param {Color} target - The target line color.
  32234. * @param {Color} cross - The cross line color.
  32235. */
  32236. setColors( frustum, cone, up, target, cross ) {
  32237. const geometry = this.geometry;
  32238. const colorAttribute = geometry.getAttribute( 'color' );
  32239. // near
  32240. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  32241. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  32242. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  32243. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  32244. // far
  32245. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  32246. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  32247. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  32248. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  32249. // sides
  32250. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  32251. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  32252. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  32253. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  32254. // cone
  32255. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  32256. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  32257. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  32258. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  32259. // up
  32260. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  32261. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  32262. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  32263. // target
  32264. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  32265. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  32266. // cross
  32267. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  32268. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  32269. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  32270. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  32271. colorAttribute.needsUpdate = true;
  32272. }
  32273. /**
  32274. * Updates the helper based on the projection matrix of the camera.
  32275. */
  32276. update() {
  32277. const geometry = this.geometry;
  32278. const pointMap = this.pointMap;
  32279. const w = 1, h = 1;
  32280. // we need just camera projection matrix inverse
  32281. // world matrix must be identity
  32282. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  32283. // Adjust z values based on coordinate system
  32284. const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? -1 : 0;
  32285. // center / target
  32286. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  32287. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  32288. // near
  32289. setPoint( 'n1', pointMap, geometry, _camera, -1, -1, nearZ );
  32290. setPoint( 'n2', pointMap, geometry, _camera, w, -1, nearZ );
  32291. setPoint( 'n3', pointMap, geometry, _camera, -1, h, nearZ );
  32292. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  32293. // far
  32294. setPoint( 'f1', pointMap, geometry, _camera, -1, -1, 1 );
  32295. setPoint( 'f2', pointMap, geometry, _camera, w, -1, 1 );
  32296. setPoint( 'f3', pointMap, geometry, _camera, -1, h, 1 );
  32297. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  32298. // up
  32299. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  32300. setPoint( 'u2', pointMap, geometry, _camera, -1 * 0.7, h * 1.1, nearZ );
  32301. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  32302. // cross
  32303. setPoint( 'cf1', pointMap, geometry, _camera, -1, 0, 1 );
  32304. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  32305. setPoint( 'cf3', pointMap, geometry, _camera, 0, -1, 1 );
  32306. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  32307. setPoint( 'cn1', pointMap, geometry, _camera, -1, 0, nearZ );
  32308. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  32309. setPoint( 'cn3', pointMap, geometry, _camera, 0, -1, nearZ );
  32310. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  32311. geometry.getAttribute( 'position' ).needsUpdate = true;
  32312. }
  32313. /**
  32314. * Frees the GPU-related resources allocated by this instance. Call this
  32315. * method whenever this instance is no longer used in your app.
  32316. */
  32317. dispose() {
  32318. this.geometry.dispose();
  32319. this.material.dispose();
  32320. }
  32321. }
  32322. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  32323. _vector.set( x, y, z ).unproject( camera );
  32324. const points = pointMap[ point ];
  32325. if ( points !== undefined ) {
  32326. const position = geometry.getAttribute( 'position' );
  32327. for ( let i = 0, l = points.length; i < l; i ++ ) {
  32328. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  32329. }
  32330. }
  32331. }
  32332. const _box = /*@__PURE__*/ new Box3();
  32333. /**
  32334. * Helper object to graphically show the world-axis-aligned bounding box
  32335. * around an object. The actual bounding box is handled with {@link Box3},
  32336. * this is just a visual helper for debugging. It can be automatically
  32337. * resized with {@link BoxHelper#update} when the object it's created from
  32338. * is transformed. Note that the object must have a geometry for this to work,
  32339. * so it won't work with sprites.
  32340. *
  32341. * ```js
  32342. * const sphere = new THREE.SphereGeometry();
  32343. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  32344. * const box = new THREE.BoxHelper( object, 0xffff00 );
  32345. * scene.add( box );
  32346. * ```
  32347. *
  32348. * @augments LineSegments
  32349. */
  32350. class BoxHelper extends LineSegments {
  32351. /**
  32352. * Constructs a new box helper.
  32353. *
  32354. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  32355. * @param {number|Color|string} [color=0xffff00] - The box's color.
  32356. */
  32357. constructor( object, color = 0xffff00 ) {
  32358. 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 ] );
  32359. const positions = new Float32Array( 8 * 3 );
  32360. const geometry = new BufferGeometry();
  32361. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  32362. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  32363. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  32364. /**
  32365. * The 3D object being visualized.
  32366. *
  32367. * @type {Object3D}
  32368. */
  32369. this.object = object;
  32370. this.type = 'BoxHelper';
  32371. this.matrixAutoUpdate = false;
  32372. this.update();
  32373. }
  32374. /**
  32375. * Updates the helper's geometry to match the dimensions of the object,
  32376. * including any children.
  32377. */
  32378. update() {
  32379. if ( this.object !== undefined ) {
  32380. _box.setFromObject( this.object );
  32381. }
  32382. if ( _box.isEmpty() ) return;
  32383. const min = _box.min;
  32384. const max = _box.max;
  32385. /*
  32386. 5____4
  32387. 1/___0/|
  32388. | 6__|_7
  32389. 2/___3/
  32390. 0: max.x, max.y, max.z
  32391. 1: min.x, max.y, max.z
  32392. 2: min.x, min.y, max.z
  32393. 3: max.x, min.y, max.z
  32394. 4: max.x, max.y, min.z
  32395. 5: min.x, max.y, min.z
  32396. 6: min.x, min.y, min.z
  32397. 7: max.x, min.y, min.z
  32398. */
  32399. const position = this.geometry.attributes.position;
  32400. const array = position.array;
  32401. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  32402. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  32403. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  32404. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  32405. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  32406. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  32407. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  32408. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  32409. position.needsUpdate = true;
  32410. this.geometry.computeBoundingSphere();
  32411. }
  32412. /**
  32413. * Updates the wireframe box for the passed object.
  32414. *
  32415. * @param {Object3D} object - The 3D object to create the helper for.
  32416. * @return {BoxHelper} A reference to this instance.
  32417. */
  32418. setFromObject( object ) {
  32419. this.object = object;
  32420. this.update();
  32421. return this;
  32422. }
  32423. copy( source, recursive ) {
  32424. super.copy( source, recursive );
  32425. this.object = source.object;
  32426. return this;
  32427. }
  32428. /**
  32429. * Frees the GPU-related resources allocated by this instance. Call this
  32430. * method whenever this instance is no longer used in your app.
  32431. */
  32432. dispose() {
  32433. this.geometry.dispose();
  32434. this.material.dispose();
  32435. }
  32436. }
  32437. /**
  32438. * A helper object to visualize an instance of {@link Box3}.
  32439. *
  32440. * ```js
  32441. * const box = new THREE.Box3();
  32442. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  32443. *
  32444. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  32445. * scene.add( helper )
  32446. * ```
  32447. *
  32448. * @augments LineSegments
  32449. */
  32450. class Box3Helper extends LineSegments {
  32451. /**
  32452. * Constructs a new box3 helper.
  32453. *
  32454. * @param {Box3} box - The box to visualize.
  32455. * @param {number|Color|string} [color=0xffff00] - The box's color.
  32456. */
  32457. constructor( box, color = 0xffff00 ) {
  32458. 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 ] );
  32459. 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 ];
  32460. const geometry = new BufferGeometry();
  32461. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  32462. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  32463. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  32464. /**
  32465. * The box being visualized.
  32466. *
  32467. * @type {Box3}
  32468. */
  32469. this.box = box;
  32470. this.type = 'Box3Helper';
  32471. this.geometry.computeBoundingSphere();
  32472. }
  32473. updateMatrixWorld( force ) {
  32474. const box = this.box;
  32475. if ( box.isEmpty() ) return;
  32476. box.getCenter( this.position );
  32477. box.getSize( this.scale );
  32478. this.scale.multiplyScalar( 0.5 );
  32479. super.updateMatrixWorld( force );
  32480. }
  32481. /**
  32482. * Frees the GPU-related resources allocated by this instance. Call this
  32483. * method whenever this instance is no longer used in your app.
  32484. */
  32485. dispose() {
  32486. this.geometry.dispose();
  32487. this.material.dispose();
  32488. }
  32489. }
  32490. /**
  32491. * A helper object to visualize an instance of {@link Plane}.
  32492. *
  32493. * ```js
  32494. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  32495. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  32496. * scene.add( helper );
  32497. * ```
  32498. *
  32499. * @augments Line
  32500. */
  32501. class PlaneHelper extends Line {
  32502. /**
  32503. * Constructs a new plane helper.
  32504. *
  32505. * @param {Plane} plane - The plane to be visualized.
  32506. * @param {number} [size=1] - The side length of plane helper.
  32507. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  32508. */
  32509. constructor( plane, size = 1, hex = 0xffff00 ) {
  32510. const color = hex;
  32511. 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 ];
  32512. const geometry = new BufferGeometry();
  32513. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  32514. geometry.computeBoundingSphere();
  32515. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  32516. this.type = 'PlaneHelper';
  32517. /**
  32518. * The plane being visualized.
  32519. *
  32520. * @type {Plane}
  32521. */
  32522. this.plane = plane;
  32523. /**
  32524. * The side length of plane helper.
  32525. *
  32526. * @type {number}
  32527. * @default 1
  32528. */
  32529. this.size = size;
  32530. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  32531. const geometry2 = new BufferGeometry();
  32532. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  32533. geometry2.computeBoundingSphere();
  32534. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  32535. }
  32536. updateMatrixWorld( force ) {
  32537. this.position.set( 0, 0, 0 );
  32538. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  32539. this.lookAt( this.plane.normal );
  32540. this.translateZ( - this.plane.constant );
  32541. super.updateMatrixWorld( force );
  32542. }
  32543. /**
  32544. * Updates the helper to match the position and direction of the
  32545. * light being visualized.
  32546. */
  32547. dispose() {
  32548. this.geometry.dispose();
  32549. this.material.dispose();
  32550. this.children[ 0 ].geometry.dispose();
  32551. this.children[ 0 ].material.dispose();
  32552. }
  32553. }
  32554. const _axis = /*@__PURE__*/ new Vector3();
  32555. let _lineGeometry, _coneGeometry;
  32556. /**
  32557. * An 3D arrow object for visualizing directions.
  32558. *
  32559. * ```js
  32560. * const dir = new THREE.Vector3( 1, 2, 0 );
  32561. *
  32562. * //normalize the direction vector (convert to vector of length 1)
  32563. * dir.normalize();
  32564. *
  32565. * const origin = new THREE.Vector3( 0, 0, 0 );
  32566. * const length = 1;
  32567. * const hex = 0xffff00;
  32568. *
  32569. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  32570. * scene.add( arrowHelper );
  32571. * ```
  32572. *
  32573. * @augments Object3D
  32574. */
  32575. class ArrowHelper extends Object3D {
  32576. /**
  32577. * Constructs a new arrow helper.
  32578. *
  32579. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  32580. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  32581. * @param {number} [length=1] - Length of the arrow in world units.
  32582. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  32583. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  32584. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  32585. */
  32586. 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 ) {
  32587. super();
  32588. this.type = 'ArrowHelper';
  32589. if ( _lineGeometry === undefined ) {
  32590. _lineGeometry = new BufferGeometry();
  32591. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  32592. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  32593. _coneGeometry.translate( 0, -0.5, 0 );
  32594. }
  32595. this.position.copy( origin );
  32596. /**
  32597. * The line part of the arrow helper.
  32598. *
  32599. * @type {Line}
  32600. */
  32601. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  32602. this.line.matrixAutoUpdate = false;
  32603. this.add( this.line );
  32604. /**
  32605. * The cone part of the arrow helper.
  32606. *
  32607. * @type {Mesh}
  32608. */
  32609. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  32610. this.cone.matrixAutoUpdate = false;
  32611. this.add( this.cone );
  32612. this.setDirection( dir );
  32613. this.setLength( length, headLength, headWidth );
  32614. }
  32615. /**
  32616. * Sets the direction of the helper.
  32617. *
  32618. * @param {Vector3} dir - The normalized direction vector.
  32619. */
  32620. setDirection( dir ) {
  32621. // dir is assumed to be normalized
  32622. if ( dir.y > 0.99999 ) {
  32623. this.quaternion.set( 0, 0, 0, 1 );
  32624. } else if ( dir.y < -0.99999 ) {
  32625. this.quaternion.set( 1, 0, 0, 0 );
  32626. } else {
  32627. _axis.set( dir.z, 0, - dir.x ).normalize();
  32628. const radians = Math.acos( dir.y );
  32629. this.quaternion.setFromAxisAngle( _axis, radians );
  32630. }
  32631. }
  32632. /**
  32633. * Sets the length of the helper.
  32634. *
  32635. * @param {number} length - Length of the arrow in world units.
  32636. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  32637. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  32638. */
  32639. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  32640. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  32641. this.line.updateMatrix();
  32642. this.cone.scale.set( headWidth, headLength, headWidth );
  32643. this.cone.position.y = length;
  32644. this.cone.updateMatrix();
  32645. }
  32646. /**
  32647. * Sets the color of the helper.
  32648. *
  32649. * @param {number|Color|string} color - The color to set.
  32650. */
  32651. setColor( color ) {
  32652. this.line.material.color.set( color );
  32653. this.cone.material.color.set( color );
  32654. }
  32655. copy( source ) {
  32656. super.copy( source, false );
  32657. this.line.copy( source.line );
  32658. this.cone.copy( source.cone );
  32659. return this;
  32660. }
  32661. /**
  32662. * Frees the GPU-related resources allocated by this instance. Call this
  32663. * method whenever this instance is no longer used in your app.
  32664. */
  32665. dispose() {
  32666. this.line.geometry.dispose();
  32667. this.line.material.dispose();
  32668. this.cone.geometry.dispose();
  32669. this.cone.material.dispose();
  32670. }
  32671. }
  32672. /**
  32673. * An axis object to visualize the 3 axes in a simple way.
  32674. * The X axis is red. The Y axis is green. The Z axis is blue.
  32675. *
  32676. * ```js
  32677. * const axesHelper = new THREE.AxesHelper( 5 );
  32678. * scene.add( axesHelper );
  32679. * ```
  32680. *
  32681. * @augments LineSegments
  32682. */
  32683. class AxesHelper extends LineSegments {
  32684. /**
  32685. * Constructs a new axes helper.
  32686. *
  32687. * @param {number} [size=1] - Size of the lines representing the axes.
  32688. */
  32689. constructor( size = 1 ) {
  32690. const vertices = [
  32691. 0, 0, 0, size, 0, 0,
  32692. 0, 0, 0, 0, size, 0,
  32693. 0, 0, 0, 0, 0, size
  32694. ];
  32695. const colors = [
  32696. 1, 0, 0, 1, 0.6, 0,
  32697. 0, 1, 0, 0.6, 1, 0,
  32698. 0, 0, 1, 0, 0.6, 1
  32699. ];
  32700. const geometry = new BufferGeometry();
  32701. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  32702. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  32703. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  32704. super( geometry, material );
  32705. this.type = 'AxesHelper';
  32706. }
  32707. /**
  32708. * Defines the colors of the axes helper.
  32709. *
  32710. * @param {number|Color|string} xAxisColor - The color for the x axis.
  32711. * @param {number|Color|string} yAxisColor - The color for the y axis.
  32712. * @param {number|Color|string} zAxisColor - The color for the z axis.
  32713. * @return {AxesHelper} A reference to this axes helper.
  32714. */
  32715. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  32716. const color = new Color();
  32717. const array = this.geometry.attributes.color.array;
  32718. color.set( xAxisColor );
  32719. color.toArray( array, 0 );
  32720. color.toArray( array, 3 );
  32721. color.set( yAxisColor );
  32722. color.toArray( array, 6 );
  32723. color.toArray( array, 9 );
  32724. color.set( zAxisColor );
  32725. color.toArray( array, 12 );
  32726. color.toArray( array, 15 );
  32727. this.geometry.attributes.color.needsUpdate = true;
  32728. return this;
  32729. }
  32730. /**
  32731. * Frees the GPU-related resources allocated by this instance. Call this
  32732. * method whenever this instance is no longer used in your app.
  32733. */
  32734. dispose() {
  32735. this.geometry.dispose();
  32736. this.material.dispose();
  32737. }
  32738. }
  32739. /**
  32740. * This class is used to convert a series of paths to an array of
  32741. * shapes. It is specifically used in context of fonts and SVG.
  32742. */
  32743. class ShapePath {
  32744. /**
  32745. * Constructs a new shape path.
  32746. */
  32747. constructor() {
  32748. this.type = 'ShapePath';
  32749. /**
  32750. * The color of the shape.
  32751. *
  32752. * @type {Color}
  32753. */
  32754. this.color = new Color();
  32755. /**
  32756. * The paths that have been generated for this shape.
  32757. *
  32758. * @type {Array<Path>}
  32759. * @default null
  32760. */
  32761. this.subPaths = [];
  32762. /**
  32763. * The current path that is being generated.
  32764. *
  32765. * @type {?Path}
  32766. * @default null
  32767. */
  32768. this.currentPath = null;
  32769. }
  32770. /**
  32771. * Creates a new path and moves it current point to the given one.
  32772. *
  32773. * @param {number} x - The x coordinate.
  32774. * @param {number} y - The y coordinate.
  32775. * @return {ShapePath} A reference to this shape path.
  32776. */
  32777. moveTo( x, y ) {
  32778. this.currentPath = new Path();
  32779. this.subPaths.push( this.currentPath );
  32780. this.currentPath.moveTo( x, y );
  32781. return this;
  32782. }
  32783. /**
  32784. * Adds an instance of {@link LineCurve} to the path by connecting
  32785. * the current point with the given one.
  32786. *
  32787. * @param {number} x - The x coordinate of the end point.
  32788. * @param {number} y - The y coordinate of the end point.
  32789. * @return {ShapePath} A reference to this shape path.
  32790. */
  32791. lineTo( x, y ) {
  32792. this.currentPath.lineTo( x, y );
  32793. return this;
  32794. }
  32795. /**
  32796. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  32797. * the current point with the given one.
  32798. *
  32799. * @param {number} aCPx - The x coordinate of the control point.
  32800. * @param {number} aCPy - The y coordinate of the control point.
  32801. * @param {number} aX - The x coordinate of the end point.
  32802. * @param {number} aY - The y coordinate of the end point.
  32803. * @return {ShapePath} A reference to this shape path.
  32804. */
  32805. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  32806. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  32807. return this;
  32808. }
  32809. /**
  32810. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  32811. * the current point with the given one.
  32812. *
  32813. * @param {number} aCP1x - The x coordinate of the first control point.
  32814. * @param {number} aCP1y - The y coordinate of the first control point.
  32815. * @param {number} aCP2x - The x coordinate of the second control point.
  32816. * @param {number} aCP2y - The y coordinate of the second control point.
  32817. * @param {number} aX - The x coordinate of the end point.
  32818. * @param {number} aY - The y coordinate of the end point.
  32819. * @return {ShapePath} A reference to this shape path.
  32820. */
  32821. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  32822. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  32823. return this;
  32824. }
  32825. /**
  32826. * Adds an instance of {@link SplineCurve} to the path by connecting
  32827. * the current point with the given list of points.
  32828. *
  32829. * @param {Array<Vector2>} pts - An array of points in 2D space.
  32830. * @return {ShapePath} A reference to this shape path.
  32831. */
  32832. splineThru( pts ) {
  32833. this.currentPath.splineThru( pts );
  32834. return this;
  32835. }
  32836. /**
  32837. * Converts the paths into an array of shapes.
  32838. *
  32839. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  32840. * If this flag is set to `true`, then those are flipped.
  32841. * @return {Array<Shape>} An array of shapes.
  32842. */
  32843. toShapes( isCCW ) {
  32844. function toShapesNoHoles( inSubpaths ) {
  32845. const shapes = [];
  32846. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  32847. const tmpPath = inSubpaths[ i ];
  32848. const tmpShape = new Shape();
  32849. tmpShape.curves = tmpPath.curves;
  32850. shapes.push( tmpShape );
  32851. }
  32852. return shapes;
  32853. }
  32854. function isPointInsidePolygon( inPt, inPolygon ) {
  32855. const polyLen = inPolygon.length;
  32856. // inPt on polygon contour => immediate success or
  32857. // toggling of inside/outside at every single! intersection point of an edge
  32858. // with the horizontal line through inPt, left of inPt
  32859. // not counting lowerY endpoints of edges and whole edges on that line
  32860. let inside = false;
  32861. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  32862. let edgeLowPt = inPolygon[ p ];
  32863. let edgeHighPt = inPolygon[ q ];
  32864. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  32865. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  32866. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  32867. // not parallel
  32868. if ( edgeDy < 0 ) {
  32869. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  32870. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  32871. }
  32872. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  32873. if ( inPt.y === edgeLowPt.y ) {
  32874. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  32875. // continue; // no intersection or edgeLowPt => doesn't count !!!
  32876. } else {
  32877. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  32878. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  32879. if ( perpEdge < 0 ) continue;
  32880. inside = ! inside; // true intersection left of inPt
  32881. }
  32882. } else {
  32883. // parallel or collinear
  32884. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  32885. // edge lies on the same horizontal line as inPt
  32886. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  32887. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  32888. // continue;
  32889. }
  32890. }
  32891. return inside;
  32892. }
  32893. const isClockWise = ShapeUtils.isClockWise;
  32894. const subPaths = this.subPaths;
  32895. if ( subPaths.length === 0 ) return [];
  32896. let solid, tmpPath, tmpShape;
  32897. const shapes = [];
  32898. if ( subPaths.length === 1 ) {
  32899. tmpPath = subPaths[ 0 ];
  32900. tmpShape = new Shape();
  32901. tmpShape.curves = tmpPath.curves;
  32902. shapes.push( tmpShape );
  32903. return shapes;
  32904. }
  32905. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  32906. holesFirst = isCCW ? ! holesFirst : holesFirst;
  32907. // console.log("Holes first", holesFirst);
  32908. const betterShapeHoles = [];
  32909. const newShapes = [];
  32910. let newShapeHoles = [];
  32911. let mainIdx = 0;
  32912. let tmpPoints;
  32913. newShapes[ mainIdx ] = undefined;
  32914. newShapeHoles[ mainIdx ] = [];
  32915. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  32916. tmpPath = subPaths[ i ];
  32917. tmpPoints = tmpPath.getPoints();
  32918. solid = isClockWise( tmpPoints );
  32919. solid = isCCW ? ! solid : solid;
  32920. if ( solid ) {
  32921. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  32922. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  32923. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  32924. if ( holesFirst ) mainIdx ++;
  32925. newShapeHoles[ mainIdx ] = [];
  32926. //console.log('cw', i);
  32927. } else {
  32928. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  32929. //console.log('ccw', i);
  32930. }
  32931. }
  32932. // only Holes? -> probably all Shapes with wrong orientation
  32933. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  32934. if ( newShapes.length > 1 ) {
  32935. let ambiguous = false;
  32936. let toChange = 0;
  32937. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  32938. betterShapeHoles[ sIdx ] = [];
  32939. }
  32940. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  32941. const sho = newShapeHoles[ sIdx ];
  32942. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  32943. const ho = sho[ hIdx ];
  32944. let hole_unassigned = true;
  32945. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  32946. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  32947. if ( sIdx !== s2Idx ) toChange ++;
  32948. if ( hole_unassigned ) {
  32949. hole_unassigned = false;
  32950. betterShapeHoles[ s2Idx ].push( ho );
  32951. } else {
  32952. ambiguous = true;
  32953. }
  32954. }
  32955. }
  32956. if ( hole_unassigned ) {
  32957. betterShapeHoles[ sIdx ].push( ho );
  32958. }
  32959. }
  32960. }
  32961. if ( toChange > 0 && ambiguous === false ) {
  32962. newShapeHoles = betterShapeHoles;
  32963. }
  32964. }
  32965. let tmpHoles;
  32966. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  32967. tmpShape = newShapes[ i ].s;
  32968. shapes.push( tmpShape );
  32969. tmpHoles = newShapeHoles[ i ];
  32970. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  32971. tmpShape.holes.push( tmpHoles[ j ].h );
  32972. }
  32973. }
  32974. //console.log("shape", shapes);
  32975. return shapes;
  32976. }
  32977. }
  32978. /**
  32979. * Abstract base class for controls.
  32980. *
  32981. * @abstract
  32982. * @augments EventDispatcher
  32983. */
  32984. class Controls extends EventDispatcher {
  32985. /**
  32986. * Constructs a new controls instance.
  32987. *
  32988. * @param {Object3D} object - The object that is managed by the controls.
  32989. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  32990. */
  32991. constructor( object, domElement = null ) {
  32992. super();
  32993. /**
  32994. * The object that is managed by the controls.
  32995. *
  32996. * @type {Object3D}
  32997. */
  32998. this.object = object;
  32999. /**
  33000. * The HTML element used for event listeners.
  33001. *
  33002. * @type {?HTMLDOMElement}
  33003. * @default null
  33004. */
  33005. this.domElement = domElement;
  33006. /**
  33007. * Whether the controls responds to user input or not.
  33008. *
  33009. * @type {boolean}
  33010. * @default true
  33011. */
  33012. this.enabled = true;
  33013. /**
  33014. * The internal state of the controls.
  33015. *
  33016. * @type {number}
  33017. * @default -1
  33018. */
  33019. this.state = -1;
  33020. /**
  33021. * This object defines the keyboard input of the controls.
  33022. *
  33023. * @type {Object}
  33024. */
  33025. this.keys = {};
  33026. /**
  33027. * This object defines what type of actions are assigned to the available mouse buttons.
  33028. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  33029. *
  33030. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  33031. */
  33032. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  33033. /**
  33034. * This object defines what type of actions are assigned to what kind of touch interaction.
  33035. * It depends on the control implementation what kind of touch interaction and actions are supported.
  33036. *
  33037. * @type {{ONE: ?number, TWO: ?number}}
  33038. */
  33039. this.touches = { ONE: null, TWO: null };
  33040. }
  33041. /**
  33042. * Connects the controls to the DOM. This method has so called "side effects" since
  33043. * it adds the module's event listeners to the DOM.
  33044. */
  33045. connect() {}
  33046. /**
  33047. * Disconnects the controls from the DOM.
  33048. */
  33049. disconnect() {}
  33050. /**
  33051. * Call this method if you no longer want use to the controls. It frees all internal
  33052. * resources and removes all event listeners.
  33053. */
  33054. dispose() {}
  33055. /**
  33056. * Controls should implement this method if they have to update their internal state
  33057. * per simulation step.
  33058. *
  33059. * @param {number} [delta] - The time delta in seconds.
  33060. */
  33061. update( /* delta */ ) {}
  33062. }
  33063. /**
  33064. * Scales the texture as large as possible within its surface without cropping
  33065. * or stretching the texture. The method preserves the original aspect ratio of
  33066. * the texture. Akin to CSS `object-fit: contain`
  33067. *
  33068. * @param {Texture} texture - The texture.
  33069. * @param {number} aspect - The texture's aspect ratio.
  33070. * @return {Texture} The updated texture.
  33071. */
  33072. function contain( texture, aspect ) {
  33073. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  33074. if ( imageAspect > aspect ) {
  33075. texture.repeat.x = 1;
  33076. texture.repeat.y = imageAspect / aspect;
  33077. texture.offset.x = 0;
  33078. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  33079. } else {
  33080. texture.repeat.x = aspect / imageAspect;
  33081. texture.repeat.y = 1;
  33082. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  33083. texture.offset.y = 0;
  33084. }
  33085. return texture;
  33086. }
  33087. /**
  33088. * Scales the texture to the smallest possible size to fill the surface, leaving
  33089. * no empty space. The method preserves the original aspect ratio of the texture.
  33090. * Akin to CSS `object-fit: cover`.
  33091. *
  33092. * @param {Texture} texture - The texture.
  33093. * @param {number} aspect - The texture's aspect ratio.
  33094. * @return {Texture} The updated texture.
  33095. */
  33096. function cover( texture, aspect ) {
  33097. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  33098. if ( imageAspect > aspect ) {
  33099. texture.repeat.x = aspect / imageAspect;
  33100. texture.repeat.y = 1;
  33101. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  33102. texture.offset.y = 0;
  33103. } else {
  33104. texture.repeat.x = 1;
  33105. texture.repeat.y = imageAspect / aspect;
  33106. texture.offset.x = 0;
  33107. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  33108. }
  33109. return texture;
  33110. }
  33111. /**
  33112. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  33113. *
  33114. * @param {Texture} texture - The texture.
  33115. * @return {Texture} The updated texture.
  33116. */
  33117. function fill( texture ) {
  33118. texture.repeat.x = 1;
  33119. texture.repeat.y = 1;
  33120. texture.offset.x = 0;
  33121. texture.offset.y = 0;
  33122. return texture;
  33123. }
  33124. /**
  33125. * Determines how many bytes must be used to represent the texture.
  33126. *
  33127. * @param {number} width - The width of the texture.
  33128. * @param {number} height - The height of the texture.
  33129. * @param {number} format - The texture's format.
  33130. * @param {number} type - The texture's type.
  33131. * @return {number} The byte length.
  33132. */
  33133. function getByteLength( width, height, format, type ) {
  33134. const typeByteLength = getTextureTypeByteLength( type );
  33135. switch ( format ) {
  33136. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  33137. case AlphaFormat:
  33138. return width * height;
  33139. case LuminanceFormat:
  33140. return width * height;
  33141. case LuminanceAlphaFormat:
  33142. return width * height * 2;
  33143. case RedFormat:
  33144. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  33145. case RedIntegerFormat:
  33146. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  33147. case RGFormat:
  33148. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  33149. case RGIntegerFormat:
  33150. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  33151. case RGBFormat:
  33152. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  33153. case RGBAFormat:
  33154. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  33155. case RGBAIntegerFormat:
  33156. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  33157. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  33158. case RGB_S3TC_DXT1_Format:
  33159. case RGBA_S3TC_DXT1_Format:
  33160. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  33161. case RGBA_S3TC_DXT3_Format:
  33162. case RGBA_S3TC_DXT5_Format:
  33163. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  33164. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  33165. case RGB_PVRTC_2BPPV1_Format:
  33166. case RGBA_PVRTC_2BPPV1_Format:
  33167. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  33168. case RGB_PVRTC_4BPPV1_Format:
  33169. case RGBA_PVRTC_4BPPV1_Format:
  33170. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  33171. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  33172. case RGB_ETC1_Format:
  33173. case RGB_ETC2_Format:
  33174. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  33175. case RGBA_ETC2_EAC_Format:
  33176. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  33177. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  33178. case RGBA_ASTC_4x4_Format:
  33179. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  33180. case RGBA_ASTC_5x4_Format:
  33181. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  33182. case RGBA_ASTC_5x5_Format:
  33183. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  33184. case RGBA_ASTC_6x5_Format:
  33185. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  33186. case RGBA_ASTC_6x6_Format:
  33187. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  33188. case RGBA_ASTC_8x5_Format:
  33189. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  33190. case RGBA_ASTC_8x6_Format:
  33191. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  33192. case RGBA_ASTC_8x8_Format:
  33193. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  33194. case RGBA_ASTC_10x5_Format:
  33195. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  33196. case RGBA_ASTC_10x6_Format:
  33197. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  33198. case RGBA_ASTC_10x8_Format:
  33199. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  33200. case RGBA_ASTC_10x10_Format:
  33201. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  33202. case RGBA_ASTC_12x10_Format:
  33203. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  33204. case RGBA_ASTC_12x12_Format:
  33205. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  33206. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  33207. case RGBA_BPTC_Format:
  33208. case RGB_BPTC_SIGNED_Format:
  33209. case RGB_BPTC_UNSIGNED_Format:
  33210. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  33211. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  33212. case RED_RGTC1_Format:
  33213. case SIGNED_RED_RGTC1_Format:
  33214. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  33215. case RED_GREEN_RGTC2_Format:
  33216. case SIGNED_RED_GREEN_RGTC2_Format:
  33217. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  33218. }
  33219. throw new Error(
  33220. `Unable to determine texture byte length for ${format} format.`,
  33221. );
  33222. }
  33223. function getTextureTypeByteLength( type ) {
  33224. switch ( type ) {
  33225. case UnsignedByteType:
  33226. case ByteType:
  33227. return { byteLength: 1, components: 1 };
  33228. case UnsignedShortType:
  33229. case ShortType:
  33230. case HalfFloatType:
  33231. return { byteLength: 2, components: 1 };
  33232. case UnsignedShort4444Type:
  33233. case UnsignedShort5551Type:
  33234. return { byteLength: 2, components: 4 };
  33235. case UnsignedIntType:
  33236. case IntType:
  33237. case FloatType:
  33238. return { byteLength: 4, components: 1 };
  33239. case UnsignedInt5999Type:
  33240. return { byteLength: 4, components: 3 };
  33241. }
  33242. throw new Error( `Unknown texture type ${type}.` );
  33243. }
  33244. /**
  33245. * A class containing utility functions for textures.
  33246. *
  33247. * @hideconstructor
  33248. */
  33249. class TextureUtils {
  33250. /**
  33251. * Scales the texture as large as possible within its surface without cropping
  33252. * or stretching the texture. The method preserves the original aspect ratio of
  33253. * the texture. Akin to CSS `object-fit: contain`
  33254. *
  33255. * @param {Texture} texture - The texture.
  33256. * @param {number} aspect - The texture's aspect ratio.
  33257. * @return {Texture} The updated texture.
  33258. */
  33259. static contain( texture, aspect ) {
  33260. return contain( texture, aspect );
  33261. }
  33262. /**
  33263. * Scales the texture to the smallest possible size to fill the surface, leaving
  33264. * no empty space. The method preserves the original aspect ratio of the texture.
  33265. * Akin to CSS `object-fit: cover`.
  33266. *
  33267. * @param {Texture} texture - The texture.
  33268. * @param {number} aspect - The texture's aspect ratio.
  33269. * @return {Texture} The updated texture.
  33270. */
  33271. static cover( texture, aspect ) {
  33272. return cover( texture, aspect );
  33273. }
  33274. /**
  33275. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  33276. *
  33277. * @param {Texture} texture - The texture.
  33278. * @return {Texture} The updated texture.
  33279. */
  33280. static fill( texture ) {
  33281. return fill( texture );
  33282. }
  33283. /**
  33284. * Determines how many bytes must be used to represent the texture.
  33285. *
  33286. * @param {number} width - The width of the texture.
  33287. * @param {number} height - The height of the texture.
  33288. * @param {number} format - The texture's format.
  33289. * @param {number} type - The texture's type.
  33290. * @return {number} The byte length.
  33291. */
  33292. static getByteLength( width, height, format, type ) {
  33293. return getByteLength( width, height, format, type );
  33294. }
  33295. }
  33296. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  33297. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  33298. revision: REVISION,
  33299. } } ) );
  33300. }
  33301. if ( typeof window !== 'undefined' ) {
  33302. if ( window.__THREE__ ) {
  33303. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  33304. } else {
  33305. window.__THREE__ = REVISION;
  33306. }
  33307. }
  33308. function WebGLAnimation() {
  33309. let context = null;
  33310. let isAnimating = false;
  33311. let animationLoop = null;
  33312. let requestId = null;
  33313. function onAnimationFrame( time, frame ) {
  33314. animationLoop( time, frame );
  33315. requestId = context.requestAnimationFrame( onAnimationFrame );
  33316. }
  33317. return {
  33318. start: function () {
  33319. if ( isAnimating === true ) return;
  33320. if ( animationLoop === null ) return;
  33321. requestId = context.requestAnimationFrame( onAnimationFrame );
  33322. isAnimating = true;
  33323. },
  33324. stop: function () {
  33325. context.cancelAnimationFrame( requestId );
  33326. isAnimating = false;
  33327. },
  33328. setAnimationLoop: function ( callback ) {
  33329. animationLoop = callback;
  33330. },
  33331. setContext: function ( value ) {
  33332. context = value;
  33333. }
  33334. };
  33335. }
  33336. function WebGLAttributes( gl ) {
  33337. const buffers = new WeakMap();
  33338. function createBuffer( attribute, bufferType ) {
  33339. const array = attribute.array;
  33340. const usage = attribute.usage;
  33341. const size = array.byteLength;
  33342. const buffer = gl.createBuffer();
  33343. gl.bindBuffer( bufferType, buffer );
  33344. gl.bufferData( bufferType, array, usage );
  33345. attribute.onUploadCallback();
  33346. let type;
  33347. if ( array instanceof Float32Array ) {
  33348. type = gl.FLOAT;
  33349. } else if ( array instanceof Uint16Array ) {
  33350. if ( attribute.isFloat16BufferAttribute ) {
  33351. type = gl.HALF_FLOAT;
  33352. } else {
  33353. type = gl.UNSIGNED_SHORT;
  33354. }
  33355. } else if ( array instanceof Int16Array ) {
  33356. type = gl.SHORT;
  33357. } else if ( array instanceof Uint32Array ) {
  33358. type = gl.UNSIGNED_INT;
  33359. } else if ( array instanceof Int32Array ) {
  33360. type = gl.INT;
  33361. } else if ( array instanceof Int8Array ) {
  33362. type = gl.BYTE;
  33363. } else if ( array instanceof Uint8Array ) {
  33364. type = gl.UNSIGNED_BYTE;
  33365. } else if ( array instanceof Uint8ClampedArray ) {
  33366. type = gl.UNSIGNED_BYTE;
  33367. } else {
  33368. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  33369. }
  33370. return {
  33371. buffer: buffer,
  33372. type: type,
  33373. bytesPerElement: array.BYTES_PER_ELEMENT,
  33374. version: attribute.version,
  33375. size: size
  33376. };
  33377. }
  33378. function updateBuffer( buffer, attribute, bufferType ) {
  33379. const array = attribute.array;
  33380. const updateRanges = attribute.updateRanges;
  33381. gl.bindBuffer( bufferType, buffer );
  33382. if ( updateRanges.length === 0 ) {
  33383. // Not using update ranges
  33384. gl.bufferSubData( bufferType, 0, array );
  33385. } else {
  33386. // Before applying update ranges, we merge any adjacent / overlapping
  33387. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  33388. // to performance improvements for applications which make heavy use of
  33389. // update ranges. Likely due to GPU command overhead.
  33390. //
  33391. // Note that to reduce garbage collection between frames, we merge the
  33392. // update ranges in-place. This is safe because this method will clear the
  33393. // update ranges once updated.
  33394. updateRanges.sort( ( a, b ) => a.start - b.start );
  33395. // To merge the update ranges in-place, we work from left to right in the
  33396. // existing updateRanges array, merging ranges. This may result in a final
  33397. // array which is smaller than the original. This index tracks the last
  33398. // index representing a merged range, any data after this index can be
  33399. // trimmed once the merge algorithm is completed.
  33400. let mergeIndex = 0;
  33401. for ( let i = 1; i < updateRanges.length; i ++ ) {
  33402. const previousRange = updateRanges[ mergeIndex ];
  33403. const range = updateRanges[ i ];
  33404. // We add one here to merge adjacent ranges. This is safe because ranges
  33405. // operate over positive integers.
  33406. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  33407. previousRange.count = Math.max(
  33408. previousRange.count,
  33409. range.start + range.count - previousRange.start
  33410. );
  33411. } else {
  33412. ++ mergeIndex;
  33413. updateRanges[ mergeIndex ] = range;
  33414. }
  33415. }
  33416. // Trim the array to only contain the merged ranges.
  33417. updateRanges.length = mergeIndex + 1;
  33418. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  33419. const range = updateRanges[ i ];
  33420. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  33421. array, range.start, range.count );
  33422. }
  33423. attribute.clearUpdateRanges();
  33424. }
  33425. attribute.onUploadCallback();
  33426. }
  33427. //
  33428. function get( attribute ) {
  33429. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  33430. return buffers.get( attribute );
  33431. }
  33432. function remove( attribute ) {
  33433. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  33434. const data = buffers.get( attribute );
  33435. if ( data ) {
  33436. gl.deleteBuffer( data.buffer );
  33437. buffers.delete( attribute );
  33438. }
  33439. }
  33440. function update( attribute, bufferType ) {
  33441. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  33442. if ( attribute.isGLBufferAttribute ) {
  33443. const cached = buffers.get( attribute );
  33444. if ( ! cached || cached.version < attribute.version ) {
  33445. buffers.set( attribute, {
  33446. buffer: attribute.buffer,
  33447. type: attribute.type,
  33448. bytesPerElement: attribute.elementSize,
  33449. version: attribute.version
  33450. } );
  33451. }
  33452. return;
  33453. }
  33454. const data = buffers.get( attribute );
  33455. if ( data === undefined ) {
  33456. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  33457. } else if ( data.version < attribute.version ) {
  33458. if ( data.size !== attribute.array.byteLength ) {
  33459. 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.' );
  33460. }
  33461. updateBuffer( data.buffer, attribute, bufferType );
  33462. data.version = attribute.version;
  33463. }
  33464. }
  33465. return {
  33466. get: get,
  33467. remove: remove,
  33468. update: update
  33469. };
  33470. }
  33471. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  33472. 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";
  33473. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  33474. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  33475. 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";
  33476. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  33477. 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";
  33478. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  33479. 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";
  33480. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  33481. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  33482. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  33483. 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";
  33484. 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";
  33485. 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";
  33486. 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";
  33487. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  33488. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  33489. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  33490. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  33491. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  33492. 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";
  33493. 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";
  33494. 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";
  33495. 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";
  33496. 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";
  33497. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  33498. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  33499. 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";
  33500. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  33501. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  33502. 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}";
  33503. 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";
  33504. 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";
  33505. 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";
  33506. 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";
  33507. 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";
  33508. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  33509. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  33510. 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";
  33511. 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";
  33512. 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}";
  33513. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  33514. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  33515. 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";
  33516. 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";
  33517. 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";
  33518. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  33519. 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";
  33520. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  33521. 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";
  33522. 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";
  33523. 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}";
  33524. 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";
  33525. 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";
  33526. 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";
  33527. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  33528. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  33529. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  33530. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  33531. 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";
  33532. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  33533. 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";
  33534. 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";
  33535. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  33536. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  33537. 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";
  33538. 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";
  33539. 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";
  33540. 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";
  33541. 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";
  33542. 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;";
  33543. 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";
  33544. 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";
  33545. 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";
  33546. 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";
  33547. 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";
  33548. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  33549. 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";
  33550. 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";
  33551. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  33552. 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 );";
  33553. 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}";
  33554. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  33555. 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;";
  33556. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  33557. 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";
  33558. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  33559. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  33560. 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";
  33561. 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";
  33562. 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";
  33563. 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}";
  33564. 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";
  33565. 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";
  33566. 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";
  33567. 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";
  33568. 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";
  33569. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  33570. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  33571. 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; }";
  33572. 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";
  33573. 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";
  33574. 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";
  33575. 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";
  33576. 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";
  33577. 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";
  33578. 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}";
  33579. 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}";
  33580. 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}";
  33581. 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}";
  33582. 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}";
  33583. 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}";
  33584. 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}";
  33585. 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}";
  33586. 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}";
  33587. 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}";
  33588. 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}";
  33589. 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}";
  33590. 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}";
  33591. 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}";
  33592. 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}";
  33593. 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}";
  33594. 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}";
  33595. 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}";
  33596. 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}";
  33597. 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}";
  33598. 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}";
  33599. 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}";
  33600. 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}";
  33601. 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}";
  33602. 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}";
  33603. 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}";
  33604. 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}";
  33605. 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}";
  33606. 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}";
  33607. 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}";
  33608. 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}";
  33609. 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}";
  33610. 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}";
  33611. 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}";
  33612. const ShaderChunk = {
  33613. alphahash_fragment: alphahash_fragment,
  33614. alphahash_pars_fragment: alphahash_pars_fragment,
  33615. alphamap_fragment: alphamap_fragment,
  33616. alphamap_pars_fragment: alphamap_pars_fragment,
  33617. alphatest_fragment: alphatest_fragment,
  33618. alphatest_pars_fragment: alphatest_pars_fragment,
  33619. aomap_fragment: aomap_fragment,
  33620. aomap_pars_fragment: aomap_pars_fragment,
  33621. batching_pars_vertex: batching_pars_vertex,
  33622. batching_vertex: batching_vertex,
  33623. begin_vertex: begin_vertex,
  33624. beginnormal_vertex: beginnormal_vertex,
  33625. bsdfs: bsdfs,
  33626. iridescence_fragment: iridescence_fragment,
  33627. bumpmap_pars_fragment: bumpmap_pars_fragment,
  33628. clipping_planes_fragment: clipping_planes_fragment,
  33629. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  33630. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  33631. clipping_planes_vertex: clipping_planes_vertex,
  33632. color_fragment: color_fragment,
  33633. color_pars_fragment: color_pars_fragment,
  33634. color_pars_vertex: color_pars_vertex,
  33635. color_vertex: color_vertex,
  33636. common: common,
  33637. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  33638. defaultnormal_vertex: defaultnormal_vertex,
  33639. displacementmap_pars_vertex: displacementmap_pars_vertex,
  33640. displacementmap_vertex: displacementmap_vertex,
  33641. emissivemap_fragment: emissivemap_fragment,
  33642. emissivemap_pars_fragment: emissivemap_pars_fragment,
  33643. colorspace_fragment: colorspace_fragment,
  33644. colorspace_pars_fragment: colorspace_pars_fragment,
  33645. envmap_fragment: envmap_fragment,
  33646. envmap_common_pars_fragment: envmap_common_pars_fragment,
  33647. envmap_pars_fragment: envmap_pars_fragment,
  33648. envmap_pars_vertex: envmap_pars_vertex,
  33649. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  33650. envmap_vertex: envmap_vertex,
  33651. fog_vertex: fog_vertex,
  33652. fog_pars_vertex: fog_pars_vertex,
  33653. fog_fragment: fog_fragment,
  33654. fog_pars_fragment: fog_pars_fragment,
  33655. gradientmap_pars_fragment: gradientmap_pars_fragment,
  33656. lightmap_pars_fragment: lightmap_pars_fragment,
  33657. lights_lambert_fragment: lights_lambert_fragment,
  33658. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  33659. lights_pars_begin: lights_pars_begin,
  33660. lights_toon_fragment: lights_toon_fragment,
  33661. lights_toon_pars_fragment: lights_toon_pars_fragment,
  33662. lights_phong_fragment: lights_phong_fragment,
  33663. lights_phong_pars_fragment: lights_phong_pars_fragment,
  33664. lights_physical_fragment: lights_physical_fragment,
  33665. lights_physical_pars_fragment: lights_physical_pars_fragment,
  33666. lights_fragment_begin: lights_fragment_begin,
  33667. lights_fragment_maps: lights_fragment_maps,
  33668. lights_fragment_end: lights_fragment_end,
  33669. logdepthbuf_fragment: logdepthbuf_fragment,
  33670. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  33671. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  33672. logdepthbuf_vertex: logdepthbuf_vertex,
  33673. map_fragment: map_fragment,
  33674. map_pars_fragment: map_pars_fragment,
  33675. map_particle_fragment: map_particle_fragment,
  33676. map_particle_pars_fragment: map_particle_pars_fragment,
  33677. metalnessmap_fragment: metalnessmap_fragment,
  33678. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  33679. morphinstance_vertex: morphinstance_vertex,
  33680. morphcolor_vertex: morphcolor_vertex,
  33681. morphnormal_vertex: morphnormal_vertex,
  33682. morphtarget_pars_vertex: morphtarget_pars_vertex,
  33683. morphtarget_vertex: morphtarget_vertex,
  33684. normal_fragment_begin: normal_fragment_begin,
  33685. normal_fragment_maps: normal_fragment_maps,
  33686. normal_pars_fragment: normal_pars_fragment,
  33687. normal_pars_vertex: normal_pars_vertex,
  33688. normal_vertex: normal_vertex,
  33689. normalmap_pars_fragment: normalmap_pars_fragment,
  33690. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  33691. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  33692. clearcoat_pars_fragment: clearcoat_pars_fragment,
  33693. iridescence_pars_fragment: iridescence_pars_fragment,
  33694. opaque_fragment: opaque_fragment,
  33695. packing: packing,
  33696. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  33697. project_vertex: project_vertex,
  33698. dithering_fragment: dithering_fragment,
  33699. dithering_pars_fragment: dithering_pars_fragment,
  33700. roughnessmap_fragment: roughnessmap_fragment,
  33701. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  33702. shadowmap_pars_fragment: shadowmap_pars_fragment,
  33703. shadowmap_pars_vertex: shadowmap_pars_vertex,
  33704. shadowmap_vertex: shadowmap_vertex,
  33705. shadowmask_pars_fragment: shadowmask_pars_fragment,
  33706. skinbase_vertex: skinbase_vertex,
  33707. skinning_pars_vertex: skinning_pars_vertex,
  33708. skinning_vertex: skinning_vertex,
  33709. skinnormal_vertex: skinnormal_vertex,
  33710. specularmap_fragment: specularmap_fragment,
  33711. specularmap_pars_fragment: specularmap_pars_fragment,
  33712. tonemapping_fragment: tonemapping_fragment,
  33713. tonemapping_pars_fragment: tonemapping_pars_fragment,
  33714. transmission_fragment: transmission_fragment,
  33715. transmission_pars_fragment: transmission_pars_fragment,
  33716. uv_pars_fragment: uv_pars_fragment,
  33717. uv_pars_vertex: uv_pars_vertex,
  33718. uv_vertex: uv_vertex,
  33719. worldpos_vertex: worldpos_vertex,
  33720. background_vert: vertex$h,
  33721. background_frag: fragment$h,
  33722. backgroundCube_vert: vertex$g,
  33723. backgroundCube_frag: fragment$g,
  33724. cube_vert: vertex$f,
  33725. cube_frag: fragment$f,
  33726. depth_vert: vertex$e,
  33727. depth_frag: fragment$e,
  33728. distanceRGBA_vert: vertex$d,
  33729. distanceRGBA_frag: fragment$d,
  33730. equirect_vert: vertex$c,
  33731. equirect_frag: fragment$c,
  33732. linedashed_vert: vertex$b,
  33733. linedashed_frag: fragment$b,
  33734. meshbasic_vert: vertex$a,
  33735. meshbasic_frag: fragment$a,
  33736. meshlambert_vert: vertex$9,
  33737. meshlambert_frag: fragment$9,
  33738. meshmatcap_vert: vertex$8,
  33739. meshmatcap_frag: fragment$8,
  33740. meshnormal_vert: vertex$7,
  33741. meshnormal_frag: fragment$7,
  33742. meshphong_vert: vertex$6,
  33743. meshphong_frag: fragment$6,
  33744. meshphysical_vert: vertex$5,
  33745. meshphysical_frag: fragment$5,
  33746. meshtoon_vert: vertex$4,
  33747. meshtoon_frag: fragment$4,
  33748. points_vert: vertex$3,
  33749. points_frag: fragment$3,
  33750. shadow_vert: vertex$2,
  33751. shadow_frag: fragment$2,
  33752. sprite_vert: vertex$1,
  33753. sprite_frag: fragment$1
  33754. };
  33755. /**
  33756. * Uniforms library for shared webgl shaders
  33757. */
  33758. const UniformsLib = {
  33759. common: {
  33760. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  33761. opacity: { value: 1.0 },
  33762. map: { value: null },
  33763. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  33764. alphaMap: { value: null },
  33765. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  33766. alphaTest: { value: 0 }
  33767. },
  33768. specularmap: {
  33769. specularMap: { value: null },
  33770. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  33771. },
  33772. envmap: {
  33773. envMap: { value: null },
  33774. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  33775. flipEnvMap: { value: -1 },
  33776. reflectivity: { value: 1.0 }, // basic, lambert, phong
  33777. ior: { value: 1.5 }, // physical
  33778. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  33779. },
  33780. aomap: {
  33781. aoMap: { value: null },
  33782. aoMapIntensity: { value: 1 },
  33783. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  33784. },
  33785. lightmap: {
  33786. lightMap: { value: null },
  33787. lightMapIntensity: { value: 1 },
  33788. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  33789. },
  33790. bumpmap: {
  33791. bumpMap: { value: null },
  33792. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  33793. bumpScale: { value: 1 }
  33794. },
  33795. normalmap: {
  33796. normalMap: { value: null },
  33797. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  33798. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  33799. },
  33800. displacementmap: {
  33801. displacementMap: { value: null },
  33802. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  33803. displacementScale: { value: 1 },
  33804. displacementBias: { value: 0 }
  33805. },
  33806. emissivemap: {
  33807. emissiveMap: { value: null },
  33808. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  33809. },
  33810. metalnessmap: {
  33811. metalnessMap: { value: null },
  33812. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  33813. },
  33814. roughnessmap: {
  33815. roughnessMap: { value: null },
  33816. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  33817. },
  33818. gradientmap: {
  33819. gradientMap: { value: null }
  33820. },
  33821. fog: {
  33822. fogDensity: { value: 0.00025 },
  33823. fogNear: { value: 1 },
  33824. fogFar: { value: 2000 },
  33825. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  33826. },
  33827. lights: {
  33828. ambientLightColor: { value: [] },
  33829. lightProbe: { value: [] },
  33830. directionalLights: { value: [], properties: {
  33831. direction: {},
  33832. color: {}
  33833. } },
  33834. directionalLightShadows: { value: [], properties: {
  33835. shadowIntensity: 1,
  33836. shadowBias: {},
  33837. shadowNormalBias: {},
  33838. shadowRadius: {},
  33839. shadowMapSize: {}
  33840. } },
  33841. directionalShadowMap: { value: [] },
  33842. directionalShadowMatrix: { value: [] },
  33843. spotLights: { value: [], properties: {
  33844. color: {},
  33845. position: {},
  33846. direction: {},
  33847. distance: {},
  33848. coneCos: {},
  33849. penumbraCos: {},
  33850. decay: {}
  33851. } },
  33852. spotLightShadows: { value: [], properties: {
  33853. shadowIntensity: 1,
  33854. shadowBias: {},
  33855. shadowNormalBias: {},
  33856. shadowRadius: {},
  33857. shadowMapSize: {}
  33858. } },
  33859. spotLightMap: { value: [] },
  33860. spotShadowMap: { value: [] },
  33861. spotLightMatrix: { value: [] },
  33862. pointLights: { value: [], properties: {
  33863. color: {},
  33864. position: {},
  33865. decay: {},
  33866. distance: {}
  33867. } },
  33868. pointLightShadows: { value: [], properties: {
  33869. shadowIntensity: 1,
  33870. shadowBias: {},
  33871. shadowNormalBias: {},
  33872. shadowRadius: {},
  33873. shadowMapSize: {},
  33874. shadowCameraNear: {},
  33875. shadowCameraFar: {}
  33876. } },
  33877. pointShadowMap: { value: [] },
  33878. pointShadowMatrix: { value: [] },
  33879. hemisphereLights: { value: [], properties: {
  33880. direction: {},
  33881. skyColor: {},
  33882. groundColor: {}
  33883. } },
  33884. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  33885. rectAreaLights: { value: [], properties: {
  33886. color: {},
  33887. position: {},
  33888. width: {},
  33889. height: {}
  33890. } },
  33891. ltc_1: { value: null },
  33892. ltc_2: { value: null }
  33893. },
  33894. points: {
  33895. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  33896. opacity: { value: 1.0 },
  33897. size: { value: 1.0 },
  33898. scale: { value: 1.0 },
  33899. map: { value: null },
  33900. alphaMap: { value: null },
  33901. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  33902. alphaTest: { value: 0 },
  33903. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  33904. },
  33905. sprite: {
  33906. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  33907. opacity: { value: 1.0 },
  33908. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  33909. rotation: { value: 0.0 },
  33910. map: { value: null },
  33911. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  33912. alphaMap: { value: null },
  33913. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  33914. alphaTest: { value: 0 }
  33915. }
  33916. };
  33917. const ShaderLib = {
  33918. basic: {
  33919. uniforms: /*@__PURE__*/ mergeUniforms( [
  33920. UniformsLib.common,
  33921. UniformsLib.specularmap,
  33922. UniformsLib.envmap,
  33923. UniformsLib.aomap,
  33924. UniformsLib.lightmap,
  33925. UniformsLib.fog
  33926. ] ),
  33927. vertexShader: ShaderChunk.meshbasic_vert,
  33928. fragmentShader: ShaderChunk.meshbasic_frag
  33929. },
  33930. lambert: {
  33931. uniforms: /*@__PURE__*/ mergeUniforms( [
  33932. UniformsLib.common,
  33933. UniformsLib.specularmap,
  33934. UniformsLib.envmap,
  33935. UniformsLib.aomap,
  33936. UniformsLib.lightmap,
  33937. UniformsLib.emissivemap,
  33938. UniformsLib.bumpmap,
  33939. UniformsLib.normalmap,
  33940. UniformsLib.displacementmap,
  33941. UniformsLib.fog,
  33942. UniformsLib.lights,
  33943. {
  33944. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  33945. }
  33946. ] ),
  33947. vertexShader: ShaderChunk.meshlambert_vert,
  33948. fragmentShader: ShaderChunk.meshlambert_frag
  33949. },
  33950. phong: {
  33951. uniforms: /*@__PURE__*/ mergeUniforms( [
  33952. UniformsLib.common,
  33953. UniformsLib.specularmap,
  33954. UniformsLib.envmap,
  33955. UniformsLib.aomap,
  33956. UniformsLib.lightmap,
  33957. UniformsLib.emissivemap,
  33958. UniformsLib.bumpmap,
  33959. UniformsLib.normalmap,
  33960. UniformsLib.displacementmap,
  33961. UniformsLib.fog,
  33962. UniformsLib.lights,
  33963. {
  33964. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  33965. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  33966. shininess: { value: 30 }
  33967. }
  33968. ] ),
  33969. vertexShader: ShaderChunk.meshphong_vert,
  33970. fragmentShader: ShaderChunk.meshphong_frag
  33971. },
  33972. standard: {
  33973. uniforms: /*@__PURE__*/ mergeUniforms( [
  33974. UniformsLib.common,
  33975. UniformsLib.envmap,
  33976. UniformsLib.aomap,
  33977. UniformsLib.lightmap,
  33978. UniformsLib.emissivemap,
  33979. UniformsLib.bumpmap,
  33980. UniformsLib.normalmap,
  33981. UniformsLib.displacementmap,
  33982. UniformsLib.roughnessmap,
  33983. UniformsLib.metalnessmap,
  33984. UniformsLib.fog,
  33985. UniformsLib.lights,
  33986. {
  33987. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  33988. roughness: { value: 1.0 },
  33989. metalness: { value: 0.0 },
  33990. envMapIntensity: { value: 1 }
  33991. }
  33992. ] ),
  33993. vertexShader: ShaderChunk.meshphysical_vert,
  33994. fragmentShader: ShaderChunk.meshphysical_frag
  33995. },
  33996. toon: {
  33997. uniforms: /*@__PURE__*/ mergeUniforms( [
  33998. UniformsLib.common,
  33999. UniformsLib.aomap,
  34000. UniformsLib.lightmap,
  34001. UniformsLib.emissivemap,
  34002. UniformsLib.bumpmap,
  34003. UniformsLib.normalmap,
  34004. UniformsLib.displacementmap,
  34005. UniformsLib.gradientmap,
  34006. UniformsLib.fog,
  34007. UniformsLib.lights,
  34008. {
  34009. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  34010. }
  34011. ] ),
  34012. vertexShader: ShaderChunk.meshtoon_vert,
  34013. fragmentShader: ShaderChunk.meshtoon_frag
  34014. },
  34015. matcap: {
  34016. uniforms: /*@__PURE__*/ mergeUniforms( [
  34017. UniformsLib.common,
  34018. UniformsLib.bumpmap,
  34019. UniformsLib.normalmap,
  34020. UniformsLib.displacementmap,
  34021. UniformsLib.fog,
  34022. {
  34023. matcap: { value: null }
  34024. }
  34025. ] ),
  34026. vertexShader: ShaderChunk.meshmatcap_vert,
  34027. fragmentShader: ShaderChunk.meshmatcap_frag
  34028. },
  34029. points: {
  34030. uniforms: /*@__PURE__*/ mergeUniforms( [
  34031. UniformsLib.points,
  34032. UniformsLib.fog
  34033. ] ),
  34034. vertexShader: ShaderChunk.points_vert,
  34035. fragmentShader: ShaderChunk.points_frag
  34036. },
  34037. dashed: {
  34038. uniforms: /*@__PURE__*/ mergeUniforms( [
  34039. UniformsLib.common,
  34040. UniformsLib.fog,
  34041. {
  34042. scale: { value: 1 },
  34043. dashSize: { value: 1 },
  34044. totalSize: { value: 2 }
  34045. }
  34046. ] ),
  34047. vertexShader: ShaderChunk.linedashed_vert,
  34048. fragmentShader: ShaderChunk.linedashed_frag
  34049. },
  34050. depth: {
  34051. uniforms: /*@__PURE__*/ mergeUniforms( [
  34052. UniformsLib.common,
  34053. UniformsLib.displacementmap
  34054. ] ),
  34055. vertexShader: ShaderChunk.depth_vert,
  34056. fragmentShader: ShaderChunk.depth_frag
  34057. },
  34058. normal: {
  34059. uniforms: /*@__PURE__*/ mergeUniforms( [
  34060. UniformsLib.common,
  34061. UniformsLib.bumpmap,
  34062. UniformsLib.normalmap,
  34063. UniformsLib.displacementmap,
  34064. {
  34065. opacity: { value: 1.0 }
  34066. }
  34067. ] ),
  34068. vertexShader: ShaderChunk.meshnormal_vert,
  34069. fragmentShader: ShaderChunk.meshnormal_frag
  34070. },
  34071. sprite: {
  34072. uniforms: /*@__PURE__*/ mergeUniforms( [
  34073. UniformsLib.sprite,
  34074. UniformsLib.fog
  34075. ] ),
  34076. vertexShader: ShaderChunk.sprite_vert,
  34077. fragmentShader: ShaderChunk.sprite_frag
  34078. },
  34079. background: {
  34080. uniforms: {
  34081. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  34082. t2D: { value: null },
  34083. backgroundIntensity: { value: 1 }
  34084. },
  34085. vertexShader: ShaderChunk.background_vert,
  34086. fragmentShader: ShaderChunk.background_frag
  34087. },
  34088. backgroundCube: {
  34089. uniforms: {
  34090. envMap: { value: null },
  34091. flipEnvMap: { value: -1 },
  34092. backgroundBlurriness: { value: 0 },
  34093. backgroundIntensity: { value: 1 },
  34094. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  34095. },
  34096. vertexShader: ShaderChunk.backgroundCube_vert,
  34097. fragmentShader: ShaderChunk.backgroundCube_frag
  34098. },
  34099. cube: {
  34100. uniforms: {
  34101. tCube: { value: null },
  34102. tFlip: { value: -1 },
  34103. opacity: { value: 1.0 }
  34104. },
  34105. vertexShader: ShaderChunk.cube_vert,
  34106. fragmentShader: ShaderChunk.cube_frag
  34107. },
  34108. equirect: {
  34109. uniforms: {
  34110. tEquirect: { value: null },
  34111. },
  34112. vertexShader: ShaderChunk.equirect_vert,
  34113. fragmentShader: ShaderChunk.equirect_frag
  34114. },
  34115. distanceRGBA: {
  34116. uniforms: /*@__PURE__*/ mergeUniforms( [
  34117. UniformsLib.common,
  34118. UniformsLib.displacementmap,
  34119. {
  34120. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  34121. nearDistance: { value: 1 },
  34122. farDistance: { value: 1000 }
  34123. }
  34124. ] ),
  34125. vertexShader: ShaderChunk.distanceRGBA_vert,
  34126. fragmentShader: ShaderChunk.distanceRGBA_frag
  34127. },
  34128. shadow: {
  34129. uniforms: /*@__PURE__*/ mergeUniforms( [
  34130. UniformsLib.lights,
  34131. UniformsLib.fog,
  34132. {
  34133. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  34134. opacity: { value: 1.0 }
  34135. },
  34136. ] ),
  34137. vertexShader: ShaderChunk.shadow_vert,
  34138. fragmentShader: ShaderChunk.shadow_frag
  34139. }
  34140. };
  34141. ShaderLib.physical = {
  34142. uniforms: /*@__PURE__*/ mergeUniforms( [
  34143. ShaderLib.standard.uniforms,
  34144. {
  34145. clearcoat: { value: 0 },
  34146. clearcoatMap: { value: null },
  34147. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  34148. clearcoatNormalMap: { value: null },
  34149. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  34150. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  34151. clearcoatRoughness: { value: 0 },
  34152. clearcoatRoughnessMap: { value: null },
  34153. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  34154. dispersion: { value: 0 },
  34155. iridescence: { value: 0 },
  34156. iridescenceMap: { value: null },
  34157. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  34158. iridescenceIOR: { value: 1.3 },
  34159. iridescenceThicknessMinimum: { value: 100 },
  34160. iridescenceThicknessMaximum: { value: 400 },
  34161. iridescenceThicknessMap: { value: null },
  34162. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  34163. sheen: { value: 0 },
  34164. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  34165. sheenColorMap: { value: null },
  34166. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  34167. sheenRoughness: { value: 1 },
  34168. sheenRoughnessMap: { value: null },
  34169. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  34170. transmission: { value: 0 },
  34171. transmissionMap: { value: null },
  34172. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  34173. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  34174. transmissionSamplerMap: { value: null },
  34175. thickness: { value: 0 },
  34176. thicknessMap: { value: null },
  34177. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  34178. attenuationDistance: { value: 0 },
  34179. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  34180. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  34181. specularColorMap: { value: null },
  34182. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  34183. specularIntensity: { value: 1 },
  34184. specularIntensityMap: { value: null },
  34185. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  34186. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  34187. anisotropyMap: { value: null },
  34188. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  34189. }
  34190. ] ),
  34191. vertexShader: ShaderChunk.meshphysical_vert,
  34192. fragmentShader: ShaderChunk.meshphysical_frag
  34193. };
  34194. const _rgb = { r: 0, b: 0, g: 0 };
  34195. const _e1$1 = /*@__PURE__*/ new Euler();
  34196. const _m1$1 = /*@__PURE__*/ new Matrix4();
  34197. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  34198. const clearColor = new Color( 0x000000 );
  34199. let clearAlpha = alpha === true ? 0 : 1;
  34200. let planeMesh;
  34201. let boxMesh;
  34202. let currentBackground = null;
  34203. let currentBackgroundVersion = 0;
  34204. let currentTonemapping = null;
  34205. function getBackground( scene ) {
  34206. let background = scene.isScene === true ? scene.background : null;
  34207. if ( background && background.isTexture ) {
  34208. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  34209. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  34210. }
  34211. return background;
  34212. }
  34213. function render( scene ) {
  34214. let forceClear = false;
  34215. const background = getBackground( scene );
  34216. if ( background === null ) {
  34217. setClear( clearColor, clearAlpha );
  34218. } else if ( background && background.isColor ) {
  34219. setClear( background, 1 );
  34220. forceClear = true;
  34221. }
  34222. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  34223. if ( environmentBlendMode === 'additive' ) {
  34224. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  34225. } else if ( environmentBlendMode === 'alpha-blend' ) {
  34226. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  34227. }
  34228. if ( renderer.autoClear || forceClear ) {
  34229. // buffers might not be writable which is required to ensure a correct clear
  34230. state.buffers.depth.setTest( true );
  34231. state.buffers.depth.setMask( true );
  34232. state.buffers.color.setMask( true );
  34233. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  34234. }
  34235. }
  34236. function addToRenderList( renderList, scene ) {
  34237. const background = getBackground( scene );
  34238. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  34239. if ( boxMesh === undefined ) {
  34240. boxMesh = new Mesh(
  34241. new BoxGeometry( 1, 1, 1 ),
  34242. new ShaderMaterial( {
  34243. name: 'BackgroundCubeMaterial',
  34244. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  34245. vertexShader: ShaderLib.backgroundCube.vertexShader,
  34246. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  34247. side: BackSide,
  34248. depthTest: false,
  34249. depthWrite: false,
  34250. fog: false
  34251. } )
  34252. );
  34253. boxMesh.geometry.deleteAttribute( 'normal' );
  34254. boxMesh.geometry.deleteAttribute( 'uv' );
  34255. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  34256. this.matrixWorld.copyPosition( camera.matrixWorld );
  34257. };
  34258. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  34259. Object.defineProperty( boxMesh.material, 'envMap', {
  34260. get: function () {
  34261. return this.uniforms.envMap.value;
  34262. }
  34263. } );
  34264. objects.update( boxMesh );
  34265. }
  34266. _e1$1.copy( scene.backgroundRotation );
  34267. // accommodate left-handed frame
  34268. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  34269. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  34270. // environment maps which are not cube render targets or PMREMs follow a different convention
  34271. _e1$1.y *= -1;
  34272. _e1$1.z *= -1;
  34273. }
  34274. boxMesh.material.uniforms.envMap.value = background;
  34275. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  34276. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  34277. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  34278. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  34279. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  34280. if ( currentBackground !== background ||
  34281. currentBackgroundVersion !== background.version ||
  34282. currentTonemapping !== renderer.toneMapping ) {
  34283. boxMesh.material.needsUpdate = true;
  34284. currentBackground = background;
  34285. currentBackgroundVersion = background.version;
  34286. currentTonemapping = renderer.toneMapping;
  34287. }
  34288. boxMesh.layers.enableAll();
  34289. // push to the pre-sorted opaque render list
  34290. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  34291. } else if ( background && background.isTexture ) {
  34292. if ( planeMesh === undefined ) {
  34293. planeMesh = new Mesh(
  34294. new PlaneGeometry( 2, 2 ),
  34295. new ShaderMaterial( {
  34296. name: 'BackgroundMaterial',
  34297. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  34298. vertexShader: ShaderLib.background.vertexShader,
  34299. fragmentShader: ShaderLib.background.fragmentShader,
  34300. side: FrontSide,
  34301. depthTest: false,
  34302. depthWrite: false,
  34303. fog: false
  34304. } )
  34305. );
  34306. planeMesh.geometry.deleteAttribute( 'normal' );
  34307. // add "map" material property so the renderer can evaluate it like for built-in materials
  34308. Object.defineProperty( planeMesh.material, 'map', {
  34309. get: function () {
  34310. return this.uniforms.t2D.value;
  34311. }
  34312. } );
  34313. objects.update( planeMesh );
  34314. }
  34315. planeMesh.material.uniforms.t2D.value = background;
  34316. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  34317. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  34318. if ( background.matrixAutoUpdate === true ) {
  34319. background.updateMatrix();
  34320. }
  34321. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  34322. if ( currentBackground !== background ||
  34323. currentBackgroundVersion !== background.version ||
  34324. currentTonemapping !== renderer.toneMapping ) {
  34325. planeMesh.material.needsUpdate = true;
  34326. currentBackground = background;
  34327. currentBackgroundVersion = background.version;
  34328. currentTonemapping = renderer.toneMapping;
  34329. }
  34330. planeMesh.layers.enableAll();
  34331. // push to the pre-sorted opaque render list
  34332. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  34333. }
  34334. }
  34335. function setClear( color, alpha ) {
  34336. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  34337. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  34338. }
  34339. function dispose() {
  34340. if ( boxMesh !== undefined ) {
  34341. boxMesh.geometry.dispose();
  34342. boxMesh.material.dispose();
  34343. boxMesh = undefined;
  34344. }
  34345. if ( planeMesh !== undefined ) {
  34346. planeMesh.geometry.dispose();
  34347. planeMesh.material.dispose();
  34348. planeMesh = undefined;
  34349. }
  34350. }
  34351. return {
  34352. getClearColor: function () {
  34353. return clearColor;
  34354. },
  34355. setClearColor: function ( color, alpha = 1 ) {
  34356. clearColor.set( color );
  34357. clearAlpha = alpha;
  34358. setClear( clearColor, clearAlpha );
  34359. },
  34360. getClearAlpha: function () {
  34361. return clearAlpha;
  34362. },
  34363. setClearAlpha: function ( alpha ) {
  34364. clearAlpha = alpha;
  34365. setClear( clearColor, clearAlpha );
  34366. },
  34367. render: render,
  34368. addToRenderList: addToRenderList,
  34369. dispose: dispose
  34370. };
  34371. }
  34372. function WebGLBindingStates( gl, attributes ) {
  34373. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  34374. const bindingStates = {};
  34375. const defaultState = createBindingState( null );
  34376. let currentState = defaultState;
  34377. let forceUpdate = false;
  34378. function setup( object, material, program, geometry, index ) {
  34379. let updateBuffers = false;
  34380. const state = getBindingState( geometry, program, material );
  34381. if ( currentState !== state ) {
  34382. currentState = state;
  34383. bindVertexArrayObject( currentState.object );
  34384. }
  34385. updateBuffers = needsUpdate( object, geometry, program, index );
  34386. if ( updateBuffers ) saveCache( object, geometry, program, index );
  34387. if ( index !== null ) {
  34388. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  34389. }
  34390. if ( updateBuffers || forceUpdate ) {
  34391. forceUpdate = false;
  34392. setupVertexAttributes( object, material, program, geometry );
  34393. if ( index !== null ) {
  34394. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  34395. }
  34396. }
  34397. }
  34398. function createVertexArrayObject() {
  34399. return gl.createVertexArray();
  34400. }
  34401. function bindVertexArrayObject( vao ) {
  34402. return gl.bindVertexArray( vao );
  34403. }
  34404. function deleteVertexArrayObject( vao ) {
  34405. return gl.deleteVertexArray( vao );
  34406. }
  34407. function getBindingState( geometry, program, material ) {
  34408. const wireframe = ( material.wireframe === true );
  34409. let programMap = bindingStates[ geometry.id ];
  34410. if ( programMap === undefined ) {
  34411. programMap = {};
  34412. bindingStates[ geometry.id ] = programMap;
  34413. }
  34414. let stateMap = programMap[ program.id ];
  34415. if ( stateMap === undefined ) {
  34416. stateMap = {};
  34417. programMap[ program.id ] = stateMap;
  34418. }
  34419. let state = stateMap[ wireframe ];
  34420. if ( state === undefined ) {
  34421. state = createBindingState( createVertexArrayObject() );
  34422. stateMap[ wireframe ] = state;
  34423. }
  34424. return state;
  34425. }
  34426. function createBindingState( vao ) {
  34427. const newAttributes = [];
  34428. const enabledAttributes = [];
  34429. const attributeDivisors = [];
  34430. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  34431. newAttributes[ i ] = 0;
  34432. enabledAttributes[ i ] = 0;
  34433. attributeDivisors[ i ] = 0;
  34434. }
  34435. return {
  34436. // for backward compatibility on non-VAO support browser
  34437. geometry: null,
  34438. program: null,
  34439. wireframe: false,
  34440. newAttributes: newAttributes,
  34441. enabledAttributes: enabledAttributes,
  34442. attributeDivisors: attributeDivisors,
  34443. object: vao,
  34444. attributes: {},
  34445. index: null
  34446. };
  34447. }
  34448. function needsUpdate( object, geometry, program, index ) {
  34449. const cachedAttributes = currentState.attributes;
  34450. const geometryAttributes = geometry.attributes;
  34451. let attributesNum = 0;
  34452. const programAttributes = program.getAttributes();
  34453. for ( const name in programAttributes ) {
  34454. const programAttribute = programAttributes[ name ];
  34455. if ( programAttribute.location >= 0 ) {
  34456. const cachedAttribute = cachedAttributes[ name ];
  34457. let geometryAttribute = geometryAttributes[ name ];
  34458. if ( geometryAttribute === undefined ) {
  34459. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  34460. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  34461. }
  34462. if ( cachedAttribute === undefined ) return true;
  34463. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  34464. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  34465. attributesNum ++;
  34466. }
  34467. }
  34468. if ( currentState.attributesNum !== attributesNum ) return true;
  34469. if ( currentState.index !== index ) return true;
  34470. return false;
  34471. }
  34472. function saveCache( object, geometry, program, index ) {
  34473. const cache = {};
  34474. const attributes = geometry.attributes;
  34475. let attributesNum = 0;
  34476. const programAttributes = program.getAttributes();
  34477. for ( const name in programAttributes ) {
  34478. const programAttribute = programAttributes[ name ];
  34479. if ( programAttribute.location >= 0 ) {
  34480. let attribute = attributes[ name ];
  34481. if ( attribute === undefined ) {
  34482. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  34483. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  34484. }
  34485. const data = {};
  34486. data.attribute = attribute;
  34487. if ( attribute && attribute.data ) {
  34488. data.data = attribute.data;
  34489. }
  34490. cache[ name ] = data;
  34491. attributesNum ++;
  34492. }
  34493. }
  34494. currentState.attributes = cache;
  34495. currentState.attributesNum = attributesNum;
  34496. currentState.index = index;
  34497. }
  34498. function initAttributes() {
  34499. const newAttributes = currentState.newAttributes;
  34500. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  34501. newAttributes[ i ] = 0;
  34502. }
  34503. }
  34504. function enableAttribute( attribute ) {
  34505. enableAttributeAndDivisor( attribute, 0 );
  34506. }
  34507. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  34508. const newAttributes = currentState.newAttributes;
  34509. const enabledAttributes = currentState.enabledAttributes;
  34510. const attributeDivisors = currentState.attributeDivisors;
  34511. newAttributes[ attribute ] = 1;
  34512. if ( enabledAttributes[ attribute ] === 0 ) {
  34513. gl.enableVertexAttribArray( attribute );
  34514. enabledAttributes[ attribute ] = 1;
  34515. }
  34516. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  34517. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  34518. attributeDivisors[ attribute ] = meshPerAttribute;
  34519. }
  34520. }
  34521. function disableUnusedAttributes() {
  34522. const newAttributes = currentState.newAttributes;
  34523. const enabledAttributes = currentState.enabledAttributes;
  34524. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  34525. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  34526. gl.disableVertexAttribArray( i );
  34527. enabledAttributes[ i ] = 0;
  34528. }
  34529. }
  34530. }
  34531. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  34532. if ( integer === true ) {
  34533. gl.vertexAttribIPointer( index, size, type, stride, offset );
  34534. } else {
  34535. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  34536. }
  34537. }
  34538. function setupVertexAttributes( object, material, program, geometry ) {
  34539. initAttributes();
  34540. const geometryAttributes = geometry.attributes;
  34541. const programAttributes = program.getAttributes();
  34542. const materialDefaultAttributeValues = material.defaultAttributeValues;
  34543. for ( const name in programAttributes ) {
  34544. const programAttribute = programAttributes[ name ];
  34545. if ( programAttribute.location >= 0 ) {
  34546. let geometryAttribute = geometryAttributes[ name ];
  34547. if ( geometryAttribute === undefined ) {
  34548. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  34549. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  34550. }
  34551. if ( geometryAttribute !== undefined ) {
  34552. const normalized = geometryAttribute.normalized;
  34553. const size = geometryAttribute.itemSize;
  34554. const attribute = attributes.get( geometryAttribute );
  34555. // TODO Attribute may not be available on context restore
  34556. if ( attribute === undefined ) continue;
  34557. const buffer = attribute.buffer;
  34558. const type = attribute.type;
  34559. const bytesPerElement = attribute.bytesPerElement;
  34560. // check for integer attributes
  34561. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  34562. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  34563. const data = geometryAttribute.data;
  34564. const stride = data.stride;
  34565. const offset = geometryAttribute.offset;
  34566. if ( data.isInstancedInterleavedBuffer ) {
  34567. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  34568. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  34569. }
  34570. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  34571. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  34572. }
  34573. } else {
  34574. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  34575. enableAttribute( programAttribute.location + i );
  34576. }
  34577. }
  34578. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  34579. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  34580. vertexAttribPointer(
  34581. programAttribute.location + i,
  34582. size / programAttribute.locationSize,
  34583. type,
  34584. normalized,
  34585. stride * bytesPerElement,
  34586. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  34587. integer
  34588. );
  34589. }
  34590. } else {
  34591. if ( geometryAttribute.isInstancedBufferAttribute ) {
  34592. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  34593. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  34594. }
  34595. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  34596. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  34597. }
  34598. } else {
  34599. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  34600. enableAttribute( programAttribute.location + i );
  34601. }
  34602. }
  34603. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  34604. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  34605. vertexAttribPointer(
  34606. programAttribute.location + i,
  34607. size / programAttribute.locationSize,
  34608. type,
  34609. normalized,
  34610. size * bytesPerElement,
  34611. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  34612. integer
  34613. );
  34614. }
  34615. }
  34616. } else if ( materialDefaultAttributeValues !== undefined ) {
  34617. const value = materialDefaultAttributeValues[ name ];
  34618. if ( value !== undefined ) {
  34619. switch ( value.length ) {
  34620. case 2:
  34621. gl.vertexAttrib2fv( programAttribute.location, value );
  34622. break;
  34623. case 3:
  34624. gl.vertexAttrib3fv( programAttribute.location, value );
  34625. break;
  34626. case 4:
  34627. gl.vertexAttrib4fv( programAttribute.location, value );
  34628. break;
  34629. default:
  34630. gl.vertexAttrib1fv( programAttribute.location, value );
  34631. }
  34632. }
  34633. }
  34634. }
  34635. }
  34636. disableUnusedAttributes();
  34637. }
  34638. function dispose() {
  34639. reset();
  34640. for ( const geometryId in bindingStates ) {
  34641. const programMap = bindingStates[ geometryId ];
  34642. for ( const programId in programMap ) {
  34643. const stateMap = programMap[ programId ];
  34644. for ( const wireframe in stateMap ) {
  34645. deleteVertexArrayObject( stateMap[ wireframe ].object );
  34646. delete stateMap[ wireframe ];
  34647. }
  34648. delete programMap[ programId ];
  34649. }
  34650. delete bindingStates[ geometryId ];
  34651. }
  34652. }
  34653. function releaseStatesOfGeometry( geometry ) {
  34654. if ( bindingStates[ geometry.id ] === undefined ) return;
  34655. const programMap = bindingStates[ geometry.id ];
  34656. for ( const programId in programMap ) {
  34657. const stateMap = programMap[ programId ];
  34658. for ( const wireframe in stateMap ) {
  34659. deleteVertexArrayObject( stateMap[ wireframe ].object );
  34660. delete stateMap[ wireframe ];
  34661. }
  34662. delete programMap[ programId ];
  34663. }
  34664. delete bindingStates[ geometry.id ];
  34665. }
  34666. function releaseStatesOfProgram( program ) {
  34667. for ( const geometryId in bindingStates ) {
  34668. const programMap = bindingStates[ geometryId ];
  34669. if ( programMap[ program.id ] === undefined ) continue;
  34670. const stateMap = programMap[ program.id ];
  34671. for ( const wireframe in stateMap ) {
  34672. deleteVertexArrayObject( stateMap[ wireframe ].object );
  34673. delete stateMap[ wireframe ];
  34674. }
  34675. delete programMap[ program.id ];
  34676. }
  34677. }
  34678. function reset() {
  34679. resetDefaultState();
  34680. forceUpdate = true;
  34681. if ( currentState === defaultState ) return;
  34682. currentState = defaultState;
  34683. bindVertexArrayObject( currentState.object );
  34684. }
  34685. // for backward-compatibility
  34686. function resetDefaultState() {
  34687. defaultState.geometry = null;
  34688. defaultState.program = null;
  34689. defaultState.wireframe = false;
  34690. }
  34691. return {
  34692. setup: setup,
  34693. reset: reset,
  34694. resetDefaultState: resetDefaultState,
  34695. dispose: dispose,
  34696. releaseStatesOfGeometry: releaseStatesOfGeometry,
  34697. releaseStatesOfProgram: releaseStatesOfProgram,
  34698. initAttributes: initAttributes,
  34699. enableAttribute: enableAttribute,
  34700. disableUnusedAttributes: disableUnusedAttributes
  34701. };
  34702. }
  34703. function WebGLBufferRenderer( gl, extensions, info ) {
  34704. let mode;
  34705. function setMode( value ) {
  34706. mode = value;
  34707. }
  34708. function render( start, count ) {
  34709. gl.drawArrays( mode, start, count );
  34710. info.update( count, mode, 1 );
  34711. }
  34712. function renderInstances( start, count, primcount ) {
  34713. if ( primcount === 0 ) return;
  34714. gl.drawArraysInstanced( mode, start, count, primcount );
  34715. info.update( count, mode, primcount );
  34716. }
  34717. function renderMultiDraw( starts, counts, drawCount ) {
  34718. if ( drawCount === 0 ) return;
  34719. const extension = extensions.get( 'WEBGL_multi_draw' );
  34720. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  34721. let elementCount = 0;
  34722. for ( let i = 0; i < drawCount; i ++ ) {
  34723. elementCount += counts[ i ];
  34724. }
  34725. info.update( elementCount, mode, 1 );
  34726. }
  34727. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  34728. if ( drawCount === 0 ) return;
  34729. const extension = extensions.get( 'WEBGL_multi_draw' );
  34730. if ( extension === null ) {
  34731. for ( let i = 0; i < starts.length; i ++ ) {
  34732. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  34733. }
  34734. } else {
  34735. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  34736. let elementCount = 0;
  34737. for ( let i = 0; i < drawCount; i ++ ) {
  34738. elementCount += counts[ i ] * primcount[ i ];
  34739. }
  34740. info.update( elementCount, mode, 1 );
  34741. }
  34742. }
  34743. //
  34744. this.setMode = setMode;
  34745. this.render = render;
  34746. this.renderInstances = renderInstances;
  34747. this.renderMultiDraw = renderMultiDraw;
  34748. this.renderMultiDrawInstances = renderMultiDrawInstances;
  34749. }
  34750. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  34751. let maxAnisotropy;
  34752. function getMaxAnisotropy() {
  34753. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  34754. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  34755. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  34756. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  34757. } else {
  34758. maxAnisotropy = 0;
  34759. }
  34760. return maxAnisotropy;
  34761. }
  34762. function textureFormatReadable( textureFormat ) {
  34763. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  34764. return false;
  34765. }
  34766. return true;
  34767. }
  34768. function textureTypeReadable( textureType ) {
  34769. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  34770. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  34771. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  34772. return false;
  34773. }
  34774. return true;
  34775. }
  34776. function getMaxPrecision( precision ) {
  34777. if ( precision === 'highp' ) {
  34778. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  34779. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  34780. return 'highp';
  34781. }
  34782. precision = 'mediump';
  34783. }
  34784. if ( precision === 'mediump' ) {
  34785. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  34786. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  34787. return 'mediump';
  34788. }
  34789. }
  34790. return 'lowp';
  34791. }
  34792. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  34793. const maxPrecision = getMaxPrecision( precision );
  34794. if ( maxPrecision !== precision ) {
  34795. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  34796. precision = maxPrecision;
  34797. }
  34798. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  34799. const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  34800. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  34801. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  34802. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  34803. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  34804. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  34805. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  34806. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  34807. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  34808. const vertexTextures = maxVertexTextures > 0;
  34809. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  34810. return {
  34811. isWebGL2: true, // keeping this for backwards compatibility
  34812. getMaxAnisotropy: getMaxAnisotropy,
  34813. getMaxPrecision: getMaxPrecision,
  34814. textureFormatReadable: textureFormatReadable,
  34815. textureTypeReadable: textureTypeReadable,
  34816. precision: precision,
  34817. logarithmicDepthBuffer: logarithmicDepthBuffer,
  34818. reverseDepthBuffer: reverseDepthBuffer,
  34819. maxTextures: maxTextures,
  34820. maxVertexTextures: maxVertexTextures,
  34821. maxTextureSize: maxTextureSize,
  34822. maxCubemapSize: maxCubemapSize,
  34823. maxAttributes: maxAttributes,
  34824. maxVertexUniforms: maxVertexUniforms,
  34825. maxVaryings: maxVaryings,
  34826. maxFragmentUniforms: maxFragmentUniforms,
  34827. vertexTextures: vertexTextures,
  34828. maxSamples: maxSamples
  34829. };
  34830. }
  34831. function WebGLClipping( properties ) {
  34832. const scope = this;
  34833. let globalState = null,
  34834. numGlobalPlanes = 0,
  34835. localClippingEnabled = false,
  34836. renderingShadows = false;
  34837. const plane = new Plane(),
  34838. viewNormalMatrix = new Matrix3(),
  34839. uniform = { value: null, needsUpdate: false };
  34840. this.uniform = uniform;
  34841. this.numPlanes = 0;
  34842. this.numIntersection = 0;
  34843. this.init = function ( planes, enableLocalClipping ) {
  34844. const enabled =
  34845. planes.length !== 0 ||
  34846. enableLocalClipping ||
  34847. // enable state of previous frame - the clipping code has to
  34848. // run another frame in order to reset the state:
  34849. numGlobalPlanes !== 0 ||
  34850. localClippingEnabled;
  34851. localClippingEnabled = enableLocalClipping;
  34852. numGlobalPlanes = planes.length;
  34853. return enabled;
  34854. };
  34855. this.beginShadows = function () {
  34856. renderingShadows = true;
  34857. projectPlanes( null );
  34858. };
  34859. this.endShadows = function () {
  34860. renderingShadows = false;
  34861. };
  34862. this.setGlobalState = function ( planes, camera ) {
  34863. globalState = projectPlanes( planes, camera, 0 );
  34864. };
  34865. this.setState = function ( material, camera, useCache ) {
  34866. const planes = material.clippingPlanes,
  34867. clipIntersection = material.clipIntersection,
  34868. clipShadows = material.clipShadows;
  34869. const materialProperties = properties.get( material );
  34870. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  34871. // there's no local clipping
  34872. if ( renderingShadows ) {
  34873. // there's no global clipping
  34874. projectPlanes( null );
  34875. } else {
  34876. resetGlobalState();
  34877. }
  34878. } else {
  34879. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  34880. lGlobal = nGlobal * 4;
  34881. let dstArray = materialProperties.clippingState || null;
  34882. uniform.value = dstArray; // ensure unique state
  34883. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  34884. for ( let i = 0; i !== lGlobal; ++ i ) {
  34885. dstArray[ i ] = globalState[ i ];
  34886. }
  34887. materialProperties.clippingState = dstArray;
  34888. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  34889. this.numPlanes += nGlobal;
  34890. }
  34891. };
  34892. function resetGlobalState() {
  34893. if ( uniform.value !== globalState ) {
  34894. uniform.value = globalState;
  34895. uniform.needsUpdate = numGlobalPlanes > 0;
  34896. }
  34897. scope.numPlanes = numGlobalPlanes;
  34898. scope.numIntersection = 0;
  34899. }
  34900. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  34901. const nPlanes = planes !== null ? planes.length : 0;
  34902. let dstArray = null;
  34903. if ( nPlanes !== 0 ) {
  34904. dstArray = uniform.value;
  34905. if ( skipTransform !== true || dstArray === null ) {
  34906. const flatSize = dstOffset + nPlanes * 4,
  34907. viewMatrix = camera.matrixWorldInverse;
  34908. viewNormalMatrix.getNormalMatrix( viewMatrix );
  34909. if ( dstArray === null || dstArray.length < flatSize ) {
  34910. dstArray = new Float32Array( flatSize );
  34911. }
  34912. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  34913. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  34914. plane.normal.toArray( dstArray, i4 );
  34915. dstArray[ i4 + 3 ] = plane.constant;
  34916. }
  34917. }
  34918. uniform.value = dstArray;
  34919. uniform.needsUpdate = true;
  34920. }
  34921. scope.numPlanes = nPlanes;
  34922. scope.numIntersection = 0;
  34923. return dstArray;
  34924. }
  34925. }
  34926. function WebGLCubeMaps( renderer ) {
  34927. let cubemaps = new WeakMap();
  34928. function mapTextureMapping( texture, mapping ) {
  34929. if ( mapping === EquirectangularReflectionMapping ) {
  34930. texture.mapping = CubeReflectionMapping;
  34931. } else if ( mapping === EquirectangularRefractionMapping ) {
  34932. texture.mapping = CubeRefractionMapping;
  34933. }
  34934. return texture;
  34935. }
  34936. function get( texture ) {
  34937. if ( texture && texture.isTexture ) {
  34938. const mapping = texture.mapping;
  34939. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  34940. if ( cubemaps.has( texture ) ) {
  34941. const cubemap = cubemaps.get( texture ).texture;
  34942. return mapTextureMapping( cubemap, texture.mapping );
  34943. } else {
  34944. const image = texture.image;
  34945. if ( image && image.height > 0 ) {
  34946. const renderTarget = new WebGLCubeRenderTarget( image.height );
  34947. renderTarget.fromEquirectangularTexture( renderer, texture );
  34948. cubemaps.set( texture, renderTarget );
  34949. texture.addEventListener( 'dispose', onTextureDispose );
  34950. return mapTextureMapping( renderTarget.texture, texture.mapping );
  34951. } else {
  34952. // image not yet ready. try the conversion next frame
  34953. return null;
  34954. }
  34955. }
  34956. }
  34957. }
  34958. return texture;
  34959. }
  34960. function onTextureDispose( event ) {
  34961. const texture = event.target;
  34962. texture.removeEventListener( 'dispose', onTextureDispose );
  34963. const cubemap = cubemaps.get( texture );
  34964. if ( cubemap !== undefined ) {
  34965. cubemaps.delete( texture );
  34966. cubemap.dispose();
  34967. }
  34968. }
  34969. function dispose() {
  34970. cubemaps = new WeakMap();
  34971. }
  34972. return {
  34973. get: get,
  34974. dispose: dispose
  34975. };
  34976. }
  34977. const LOD_MIN = 4;
  34978. // The standard deviations (radians) associated with the extra mips. These are
  34979. // chosen to approximate a Trowbridge-Reitz distribution function times the
  34980. // geometric shadowing function. These sigma values squared must match the
  34981. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  34982. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  34983. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  34984. // samples and exit early, but not recompile the shader.
  34985. const MAX_SAMPLES = 20;
  34986. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  34987. const _clearColor = /*@__PURE__*/ new Color();
  34988. let _oldTarget = null;
  34989. let _oldActiveCubeFace = 0;
  34990. let _oldActiveMipmapLevel = 0;
  34991. let _oldXrEnabled = false;
  34992. // Golden Ratio
  34993. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  34994. const INV_PHI = 1 / PHI;
  34995. // Vertices of a dodecahedron (except the opposites, which represent the
  34996. // same axis), used as axis directions evenly spread on a sphere.
  34997. const _axisDirections = [
  34998. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  34999. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  35000. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  35001. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  35002. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  35003. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  35004. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  35005. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  35006. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  35007. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  35008. const _origin = /*@__PURE__*/ new Vector3();
  35009. /**
  35010. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  35011. * (PMREM) from a cubeMap environment texture. This allows different levels of
  35012. * blur to be quickly accessed based on material roughness. It is packed into a
  35013. * special CubeUV format that allows us to perform custom interpolation so that
  35014. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  35015. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  35016. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  35017. * higher roughness levels. In this way we maintain resolution to smoothly
  35018. * interpolate diffuse lighting while limiting sampling computation.
  35019. *
  35020. * Paper: Fast, Accurate Image-Based Lighting
  35021. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  35022. */
  35023. class PMREMGenerator {
  35024. constructor( renderer ) {
  35025. this._renderer = renderer;
  35026. this._pingPongRenderTarget = null;
  35027. this._lodMax = 0;
  35028. this._cubeSize = 0;
  35029. this._lodPlanes = [];
  35030. this._sizeLods = [];
  35031. this._sigmas = [];
  35032. this._blurMaterial = null;
  35033. this._cubemapMaterial = null;
  35034. this._equirectMaterial = null;
  35035. this._compileMaterial( this._blurMaterial );
  35036. }
  35037. /**
  35038. * Generates a PMREM from a supplied Scene, which can be faster than using an
  35039. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  35040. * in radians to be applied to the scene before PMREM generation. Optional near
  35041. * and far planes ensure the scene is rendered in its entirety.
  35042. *
  35043. * @param {Scene} scene
  35044. * @param {number} sigma
  35045. * @param {number} near
  35046. * @param {number} far
  35047. * @param {Object} [options={}]
  35048. * @return {WebGLRenderTarget}
  35049. */
  35050. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  35051. const {
  35052. size = 256,
  35053. position = _origin,
  35054. } = options;
  35055. _oldTarget = this._renderer.getRenderTarget();
  35056. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  35057. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  35058. _oldXrEnabled = this._renderer.xr.enabled;
  35059. this._renderer.xr.enabled = false;
  35060. this._setSize( size );
  35061. const cubeUVRenderTarget = this._allocateTargets();
  35062. cubeUVRenderTarget.depthBuffer = true;
  35063. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  35064. if ( sigma > 0 ) {
  35065. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  35066. }
  35067. this._applyPMREM( cubeUVRenderTarget );
  35068. this._cleanup( cubeUVRenderTarget );
  35069. return cubeUVRenderTarget;
  35070. }
  35071. /**
  35072. * Generates a PMREM from an equirectangular texture, which can be either LDR
  35073. * or HDR. The ideal input image size is 1k (1024 x 512),
  35074. * as this matches best with the 256 x 256 cubemap output.
  35075. * The smallest supported equirectangular image size is 64 x 32.
  35076. *
  35077. * @param {Texture} equirectangular
  35078. * @param {?WebGLRenderTarget} [renderTarget=null] - Optional render target.
  35079. * @return {WebGLRenderTarget}
  35080. */
  35081. fromEquirectangular( equirectangular, renderTarget = null ) {
  35082. return this._fromTexture( equirectangular, renderTarget );
  35083. }
  35084. /**
  35085. * Generates a PMREM from an cubemap texture, which can be either LDR
  35086. * or HDR. The ideal input cube size is 256 x 256,
  35087. * as this matches best with the 256 x 256 cubemap output.
  35088. * The smallest supported cube size is 16 x 16.
  35089. *
  35090. * @param {Texture} cubemap
  35091. * @param {null} [renderTarget=null] - Optional render target.
  35092. * @return {WebGLRenderTarget}
  35093. */
  35094. fromCubemap( cubemap, renderTarget = null ) {
  35095. return this._fromTexture( cubemap, renderTarget );
  35096. }
  35097. /**
  35098. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  35099. * your texture's network fetch for increased concurrency.
  35100. */
  35101. compileCubemapShader() {
  35102. if ( this._cubemapMaterial === null ) {
  35103. this._cubemapMaterial = _getCubemapMaterial();
  35104. this._compileMaterial( this._cubemapMaterial );
  35105. }
  35106. }
  35107. /**
  35108. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  35109. * your texture's network fetch for increased concurrency.
  35110. */
  35111. compileEquirectangularShader() {
  35112. if ( this._equirectMaterial === null ) {
  35113. this._equirectMaterial = _getEquirectMaterial();
  35114. this._compileMaterial( this._equirectMaterial );
  35115. }
  35116. }
  35117. /**
  35118. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  35119. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  35120. * one of them will cause any others to also become unusable.
  35121. */
  35122. dispose() {
  35123. this._dispose();
  35124. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  35125. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  35126. }
  35127. // private interface
  35128. _setSize( cubeSize ) {
  35129. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  35130. this._cubeSize = Math.pow( 2, this._lodMax );
  35131. }
  35132. _dispose() {
  35133. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  35134. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  35135. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  35136. this._lodPlanes[ i ].dispose();
  35137. }
  35138. }
  35139. _cleanup( outputTarget ) {
  35140. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  35141. this._renderer.xr.enabled = _oldXrEnabled;
  35142. outputTarget.scissorTest = false;
  35143. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  35144. }
  35145. _fromTexture( texture, renderTarget ) {
  35146. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  35147. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  35148. } else { // Equirectangular
  35149. this._setSize( texture.image.width / 4 );
  35150. }
  35151. _oldTarget = this._renderer.getRenderTarget();
  35152. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  35153. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  35154. _oldXrEnabled = this._renderer.xr.enabled;
  35155. this._renderer.xr.enabled = false;
  35156. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  35157. this._textureToCubeUV( texture, cubeUVRenderTarget );
  35158. this._applyPMREM( cubeUVRenderTarget );
  35159. this._cleanup( cubeUVRenderTarget );
  35160. return cubeUVRenderTarget;
  35161. }
  35162. _allocateTargets() {
  35163. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  35164. const height = 4 * this._cubeSize;
  35165. const params = {
  35166. magFilter: LinearFilter,
  35167. minFilter: LinearFilter,
  35168. generateMipmaps: false,
  35169. type: HalfFloatType,
  35170. format: RGBAFormat,
  35171. colorSpace: LinearSRGBColorSpace,
  35172. depthBuffer: false
  35173. };
  35174. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  35175. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  35176. if ( this._pingPongRenderTarget !== null ) {
  35177. this._dispose();
  35178. }
  35179. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  35180. const { _lodMax } = this;
  35181. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  35182. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  35183. }
  35184. return cubeUVRenderTarget;
  35185. }
  35186. _compileMaterial( material ) {
  35187. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  35188. this._renderer.compile( tmpMesh, _flatCamera );
  35189. }
  35190. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  35191. const fov = 90;
  35192. const aspect = 1;
  35193. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  35194. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  35195. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  35196. const renderer = this._renderer;
  35197. const originalAutoClear = renderer.autoClear;
  35198. const toneMapping = renderer.toneMapping;
  35199. renderer.getClearColor( _clearColor );
  35200. renderer.toneMapping = NoToneMapping;
  35201. renderer.autoClear = false;
  35202. const backgroundMaterial = new MeshBasicMaterial( {
  35203. name: 'PMREM.Background',
  35204. side: BackSide,
  35205. depthWrite: false,
  35206. depthTest: false,
  35207. } );
  35208. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  35209. let useSolidColor = false;
  35210. const background = scene.background;
  35211. if ( background ) {
  35212. if ( background.isColor ) {
  35213. backgroundMaterial.color.copy( background );
  35214. scene.background = null;
  35215. useSolidColor = true;
  35216. }
  35217. } else {
  35218. backgroundMaterial.color.copy( _clearColor );
  35219. useSolidColor = true;
  35220. }
  35221. for ( let i = 0; i < 6; i ++ ) {
  35222. const col = i % 3;
  35223. if ( col === 0 ) {
  35224. cubeCamera.up.set( 0, upSign[ i ], 0 );
  35225. cubeCamera.position.set( position.x, position.y, position.z );
  35226. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  35227. } else if ( col === 1 ) {
  35228. cubeCamera.up.set( 0, 0, upSign[ i ] );
  35229. cubeCamera.position.set( position.x, position.y, position.z );
  35230. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  35231. } else {
  35232. cubeCamera.up.set( 0, upSign[ i ], 0 );
  35233. cubeCamera.position.set( position.x, position.y, position.z );
  35234. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  35235. }
  35236. const size = this._cubeSize;
  35237. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  35238. renderer.setRenderTarget( cubeUVRenderTarget );
  35239. if ( useSolidColor ) {
  35240. renderer.render( backgroundBox, cubeCamera );
  35241. }
  35242. renderer.render( scene, cubeCamera );
  35243. }
  35244. backgroundBox.geometry.dispose();
  35245. backgroundBox.material.dispose();
  35246. renderer.toneMapping = toneMapping;
  35247. renderer.autoClear = originalAutoClear;
  35248. scene.background = background;
  35249. }
  35250. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  35251. const renderer = this._renderer;
  35252. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  35253. if ( isCubeTexture ) {
  35254. if ( this._cubemapMaterial === null ) {
  35255. this._cubemapMaterial = _getCubemapMaterial();
  35256. }
  35257. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  35258. } else {
  35259. if ( this._equirectMaterial === null ) {
  35260. this._equirectMaterial = _getEquirectMaterial();
  35261. }
  35262. }
  35263. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  35264. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  35265. const uniforms = material.uniforms;
  35266. uniforms[ 'envMap' ].value = texture;
  35267. const size = this._cubeSize;
  35268. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  35269. renderer.setRenderTarget( cubeUVRenderTarget );
  35270. renderer.render( mesh, _flatCamera );
  35271. }
  35272. _applyPMREM( cubeUVRenderTarget ) {
  35273. const renderer = this._renderer;
  35274. const autoClear = renderer.autoClear;
  35275. renderer.autoClear = false;
  35276. const n = this._lodPlanes.length;
  35277. for ( let i = 1; i < n; i ++ ) {
  35278. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  35279. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  35280. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  35281. }
  35282. renderer.autoClear = autoClear;
  35283. }
  35284. /**
  35285. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  35286. * vertically and horizontally, but this breaks down on a cube. Here we apply
  35287. * the blur latitudinally (around the poles), and then longitudinally (towards
  35288. * the poles) to approximate the orthogonally-separable blur. It is least
  35289. * accurate at the poles, but still does a decent job.
  35290. *
  35291. * @param {WebGLRenderTarget} cubeUVRenderTarget
  35292. * @param {number} lodIn
  35293. * @param {number} lodOut
  35294. * @param {number} sigma
  35295. * @param {Vector3} [poleAxis]
  35296. */
  35297. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  35298. const pingPongRenderTarget = this._pingPongRenderTarget;
  35299. this._halfBlur(
  35300. cubeUVRenderTarget,
  35301. pingPongRenderTarget,
  35302. lodIn,
  35303. lodOut,
  35304. sigma,
  35305. 'latitudinal',
  35306. poleAxis );
  35307. this._halfBlur(
  35308. pingPongRenderTarget,
  35309. cubeUVRenderTarget,
  35310. lodOut,
  35311. lodOut,
  35312. sigma,
  35313. 'longitudinal',
  35314. poleAxis );
  35315. }
  35316. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  35317. const renderer = this._renderer;
  35318. const blurMaterial = this._blurMaterial;
  35319. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  35320. console.error(
  35321. 'blur direction must be either latitudinal or longitudinal!' );
  35322. }
  35323. // Number of standard deviations at which to cut off the discrete approximation.
  35324. const STANDARD_DEVIATIONS = 3;
  35325. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  35326. const blurUniforms = blurMaterial.uniforms;
  35327. const pixels = this._sizeLods[ lodIn ] - 1;
  35328. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  35329. const sigmaPixels = sigmaRadians / radiansPerPixel;
  35330. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  35331. if ( samples > MAX_SAMPLES ) {
  35332. console.warn( `sigmaRadians, ${
  35333. sigmaRadians}, is too large and will clip, as it requested ${
  35334. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  35335. }
  35336. const weights = [];
  35337. let sum = 0;
  35338. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  35339. const x = i / sigmaPixels;
  35340. const weight = Math.exp( - x * x / 2 );
  35341. weights.push( weight );
  35342. if ( i === 0 ) {
  35343. sum += weight;
  35344. } else if ( i < samples ) {
  35345. sum += 2 * weight;
  35346. }
  35347. }
  35348. for ( let i = 0; i < weights.length; i ++ ) {
  35349. weights[ i ] = weights[ i ] / sum;
  35350. }
  35351. blurUniforms[ 'envMap' ].value = targetIn.texture;
  35352. blurUniforms[ 'samples' ].value = samples;
  35353. blurUniforms[ 'weights' ].value = weights;
  35354. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  35355. if ( poleAxis ) {
  35356. blurUniforms[ 'poleAxis' ].value = poleAxis;
  35357. }
  35358. const { _lodMax } = this;
  35359. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  35360. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  35361. const outputSize = this._sizeLods[ lodOut ];
  35362. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  35363. const y = 4 * ( this._cubeSize - outputSize );
  35364. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  35365. renderer.setRenderTarget( targetOut );
  35366. renderer.render( blurMesh, _flatCamera );
  35367. }
  35368. }
  35369. function _createPlanes( lodMax ) {
  35370. const lodPlanes = [];
  35371. const sizeLods = [];
  35372. const sigmas = [];
  35373. let lod = lodMax;
  35374. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  35375. for ( let i = 0; i < totalLods; i ++ ) {
  35376. const sizeLod = Math.pow( 2, lod );
  35377. sizeLods.push( sizeLod );
  35378. let sigma = 1.0 / sizeLod;
  35379. if ( i > lodMax - LOD_MIN ) {
  35380. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  35381. } else if ( i === 0 ) {
  35382. sigma = 0;
  35383. }
  35384. sigmas.push( sigma );
  35385. const texelSize = 1.0 / ( sizeLod - 2 );
  35386. const min = - texelSize;
  35387. const max = 1 + texelSize;
  35388. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  35389. const cubeFaces = 6;
  35390. const vertices = 6;
  35391. const positionSize = 3;
  35392. const uvSize = 2;
  35393. const faceIndexSize = 1;
  35394. const position = new Float32Array( positionSize * vertices * cubeFaces );
  35395. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  35396. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  35397. for ( let face = 0; face < cubeFaces; face ++ ) {
  35398. const x = ( face % 3 ) * 2 / 3 - 1;
  35399. const y = face > 2 ? 0 : -1;
  35400. const coordinates = [
  35401. x, y, 0,
  35402. x + 2 / 3, y, 0,
  35403. x + 2 / 3, y + 1, 0,
  35404. x, y, 0,
  35405. x + 2 / 3, y + 1, 0,
  35406. x, y + 1, 0
  35407. ];
  35408. position.set( coordinates, positionSize * vertices * face );
  35409. uv.set( uv1, uvSize * vertices * face );
  35410. const fill = [ face, face, face, face, face, face ];
  35411. faceIndex.set( fill, faceIndexSize * vertices * face );
  35412. }
  35413. const planes = new BufferGeometry();
  35414. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  35415. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  35416. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  35417. lodPlanes.push( planes );
  35418. if ( lod > LOD_MIN ) {
  35419. lod --;
  35420. }
  35421. }
  35422. return { lodPlanes, sizeLods, sigmas };
  35423. }
  35424. function _createRenderTarget( width, height, params ) {
  35425. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  35426. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  35427. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  35428. cubeUVRenderTarget.scissorTest = true;
  35429. return cubeUVRenderTarget;
  35430. }
  35431. function _setViewport( target, x, y, width, height ) {
  35432. target.viewport.set( x, y, width, height );
  35433. target.scissor.set( x, y, width, height );
  35434. }
  35435. function _getBlurShader( lodMax, width, height ) {
  35436. const weights = new Float32Array( MAX_SAMPLES );
  35437. const poleAxis = new Vector3( 0, 1, 0 );
  35438. const shaderMaterial = new ShaderMaterial( {
  35439. name: 'SphericalGaussianBlur',
  35440. defines: {
  35441. 'n': MAX_SAMPLES,
  35442. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  35443. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  35444. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  35445. },
  35446. uniforms: {
  35447. 'envMap': { value: null },
  35448. 'samples': { value: 1 },
  35449. 'weights': { value: weights },
  35450. 'latitudinal': { value: false },
  35451. 'dTheta': { value: 0 },
  35452. 'mipInt': { value: 0 },
  35453. 'poleAxis': { value: poleAxis }
  35454. },
  35455. vertexShader: _getCommonVertexShader(),
  35456. fragmentShader: /* glsl */`
  35457. precision mediump float;
  35458. precision mediump int;
  35459. varying vec3 vOutputDirection;
  35460. uniform sampler2D envMap;
  35461. uniform int samples;
  35462. uniform float weights[ n ];
  35463. uniform bool latitudinal;
  35464. uniform float dTheta;
  35465. uniform float mipInt;
  35466. uniform vec3 poleAxis;
  35467. #define ENVMAP_TYPE_CUBE_UV
  35468. #include <cube_uv_reflection_fragment>
  35469. vec3 getSample( float theta, vec3 axis ) {
  35470. float cosTheta = cos( theta );
  35471. // Rodrigues' axis-angle rotation
  35472. vec3 sampleDirection = vOutputDirection * cosTheta
  35473. + cross( axis, vOutputDirection ) * sin( theta )
  35474. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  35475. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  35476. }
  35477. void main() {
  35478. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  35479. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  35480. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  35481. }
  35482. axis = normalize( axis );
  35483. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  35484. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  35485. for ( int i = 1; i < n; i++ ) {
  35486. if ( i >= samples ) {
  35487. break;
  35488. }
  35489. float theta = dTheta * float( i );
  35490. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  35491. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  35492. }
  35493. }
  35494. `,
  35495. blending: NoBlending,
  35496. depthTest: false,
  35497. depthWrite: false
  35498. } );
  35499. return shaderMaterial;
  35500. }
  35501. function _getEquirectMaterial() {
  35502. return new ShaderMaterial( {
  35503. name: 'EquirectangularToCubeUV',
  35504. uniforms: {
  35505. 'envMap': { value: null }
  35506. },
  35507. vertexShader: _getCommonVertexShader(),
  35508. fragmentShader: /* glsl */`
  35509. precision mediump float;
  35510. precision mediump int;
  35511. varying vec3 vOutputDirection;
  35512. uniform sampler2D envMap;
  35513. #include <common>
  35514. void main() {
  35515. vec3 outputDirection = normalize( vOutputDirection );
  35516. vec2 uv = equirectUv( outputDirection );
  35517. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  35518. }
  35519. `,
  35520. blending: NoBlending,
  35521. depthTest: false,
  35522. depthWrite: false
  35523. } );
  35524. }
  35525. function _getCubemapMaterial() {
  35526. return new ShaderMaterial( {
  35527. name: 'CubemapToCubeUV',
  35528. uniforms: {
  35529. 'envMap': { value: null },
  35530. 'flipEnvMap': { value: -1 }
  35531. },
  35532. vertexShader: _getCommonVertexShader(),
  35533. fragmentShader: /* glsl */`
  35534. precision mediump float;
  35535. precision mediump int;
  35536. uniform float flipEnvMap;
  35537. varying vec3 vOutputDirection;
  35538. uniform samplerCube envMap;
  35539. void main() {
  35540. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  35541. }
  35542. `,
  35543. blending: NoBlending,
  35544. depthTest: false,
  35545. depthWrite: false
  35546. } );
  35547. }
  35548. function _getCommonVertexShader() {
  35549. return /* glsl */`
  35550. precision mediump float;
  35551. precision mediump int;
  35552. attribute float faceIndex;
  35553. varying vec3 vOutputDirection;
  35554. // RH coordinate system; PMREM face-indexing convention
  35555. vec3 getDirection( vec2 uv, float face ) {
  35556. uv = 2.0 * uv - 1.0;
  35557. vec3 direction = vec3( uv, 1.0 );
  35558. if ( face == 0.0 ) {
  35559. direction = direction.zyx; // ( 1, v, u ) pos x
  35560. } else if ( face == 1.0 ) {
  35561. direction = direction.xzy;
  35562. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  35563. } else if ( face == 2.0 ) {
  35564. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  35565. } else if ( face == 3.0 ) {
  35566. direction = direction.zyx;
  35567. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  35568. } else if ( face == 4.0 ) {
  35569. direction = direction.xzy;
  35570. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  35571. } else if ( face == 5.0 ) {
  35572. direction.z *= -1.0; // ( u, v, -1 ) neg z
  35573. }
  35574. return direction;
  35575. }
  35576. void main() {
  35577. vOutputDirection = getDirection( uv, faceIndex );
  35578. gl_Position = vec4( position, 1.0 );
  35579. }
  35580. `;
  35581. }
  35582. function WebGLCubeUVMaps( renderer ) {
  35583. let cubeUVmaps = new WeakMap();
  35584. let pmremGenerator = null;
  35585. function get( texture ) {
  35586. if ( texture && texture.isTexture ) {
  35587. const mapping = texture.mapping;
  35588. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  35589. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  35590. // equirect/cube map to cubeUV conversion
  35591. if ( isEquirectMap || isCubeMap ) {
  35592. let renderTarget = cubeUVmaps.get( texture );
  35593. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  35594. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  35595. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  35596. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  35597. renderTarget.texture.pmremVersion = texture.pmremVersion;
  35598. cubeUVmaps.set( texture, renderTarget );
  35599. return renderTarget.texture;
  35600. } else {
  35601. if ( renderTarget !== undefined ) {
  35602. return renderTarget.texture;
  35603. } else {
  35604. const image = texture.image;
  35605. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  35606. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  35607. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  35608. renderTarget.texture.pmremVersion = texture.pmremVersion;
  35609. cubeUVmaps.set( texture, renderTarget );
  35610. texture.addEventListener( 'dispose', onTextureDispose );
  35611. return renderTarget.texture;
  35612. } else {
  35613. // image not yet ready. try the conversion next frame
  35614. return null;
  35615. }
  35616. }
  35617. }
  35618. }
  35619. }
  35620. return texture;
  35621. }
  35622. function isCubeTextureComplete( image ) {
  35623. let count = 0;
  35624. const length = 6;
  35625. for ( let i = 0; i < length; i ++ ) {
  35626. if ( image[ i ] !== undefined ) count ++;
  35627. }
  35628. return count === length;
  35629. }
  35630. function onTextureDispose( event ) {
  35631. const texture = event.target;
  35632. texture.removeEventListener( 'dispose', onTextureDispose );
  35633. const cubemapUV = cubeUVmaps.get( texture );
  35634. if ( cubemapUV !== undefined ) {
  35635. cubeUVmaps.delete( texture );
  35636. cubemapUV.dispose();
  35637. }
  35638. }
  35639. function dispose() {
  35640. cubeUVmaps = new WeakMap();
  35641. if ( pmremGenerator !== null ) {
  35642. pmremGenerator.dispose();
  35643. pmremGenerator = null;
  35644. }
  35645. }
  35646. return {
  35647. get: get,
  35648. dispose: dispose
  35649. };
  35650. }
  35651. function WebGLExtensions( gl ) {
  35652. const extensions = {};
  35653. function getExtension( name ) {
  35654. if ( extensions[ name ] !== undefined ) {
  35655. return extensions[ name ];
  35656. }
  35657. let extension;
  35658. switch ( name ) {
  35659. case 'WEBGL_depth_texture':
  35660. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  35661. break;
  35662. case 'EXT_texture_filter_anisotropic':
  35663. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  35664. break;
  35665. case 'WEBGL_compressed_texture_s3tc':
  35666. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  35667. break;
  35668. case 'WEBGL_compressed_texture_pvrtc':
  35669. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  35670. break;
  35671. default:
  35672. extension = gl.getExtension( name );
  35673. }
  35674. extensions[ name ] = extension;
  35675. return extension;
  35676. }
  35677. return {
  35678. has: function ( name ) {
  35679. return getExtension( name ) !== null;
  35680. },
  35681. init: function () {
  35682. getExtension( 'EXT_color_buffer_float' );
  35683. getExtension( 'WEBGL_clip_cull_distance' );
  35684. getExtension( 'OES_texture_float_linear' );
  35685. getExtension( 'EXT_color_buffer_half_float' );
  35686. getExtension( 'WEBGL_multisampled_render_to_texture' );
  35687. getExtension( 'WEBGL_render_shared_exponent' );
  35688. },
  35689. get: function ( name ) {
  35690. const extension = getExtension( name );
  35691. if ( extension === null ) {
  35692. warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  35693. }
  35694. return extension;
  35695. }
  35696. };
  35697. }
  35698. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  35699. const geometries = {};
  35700. const wireframeAttributes = new WeakMap();
  35701. function onGeometryDispose( event ) {
  35702. const geometry = event.target;
  35703. if ( geometry.index !== null ) {
  35704. attributes.remove( geometry.index );
  35705. }
  35706. for ( const name in geometry.attributes ) {
  35707. attributes.remove( geometry.attributes[ name ] );
  35708. }
  35709. geometry.removeEventListener( 'dispose', onGeometryDispose );
  35710. delete geometries[ geometry.id ];
  35711. const attribute = wireframeAttributes.get( geometry );
  35712. if ( attribute ) {
  35713. attributes.remove( attribute );
  35714. wireframeAttributes.delete( geometry );
  35715. }
  35716. bindingStates.releaseStatesOfGeometry( geometry );
  35717. if ( geometry.isInstancedBufferGeometry === true ) {
  35718. delete geometry._maxInstanceCount;
  35719. }
  35720. //
  35721. info.memory.geometries --;
  35722. }
  35723. function get( object, geometry ) {
  35724. if ( geometries[ geometry.id ] === true ) return geometry;
  35725. geometry.addEventListener( 'dispose', onGeometryDispose );
  35726. geometries[ geometry.id ] = true;
  35727. info.memory.geometries ++;
  35728. return geometry;
  35729. }
  35730. function update( geometry ) {
  35731. const geometryAttributes = geometry.attributes;
  35732. // Updating index buffer in VAO now. See WebGLBindingStates.
  35733. for ( const name in geometryAttributes ) {
  35734. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  35735. }
  35736. }
  35737. function updateWireframeAttribute( geometry ) {
  35738. const indices = [];
  35739. const geometryIndex = geometry.index;
  35740. const geometryPosition = geometry.attributes.position;
  35741. let version = 0;
  35742. if ( geometryIndex !== null ) {
  35743. const array = geometryIndex.array;
  35744. version = geometryIndex.version;
  35745. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  35746. const a = array[ i + 0 ];
  35747. const b = array[ i + 1 ];
  35748. const c = array[ i + 2 ];
  35749. indices.push( a, b, b, c, c, a );
  35750. }
  35751. } else if ( geometryPosition !== undefined ) {
  35752. const array = geometryPosition.array;
  35753. version = geometryPosition.version;
  35754. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  35755. const a = i + 0;
  35756. const b = i + 1;
  35757. const c = i + 2;
  35758. indices.push( a, b, b, c, c, a );
  35759. }
  35760. } else {
  35761. return;
  35762. }
  35763. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  35764. attribute.version = version;
  35765. // Updating index buffer in VAO now. See WebGLBindingStates
  35766. //
  35767. const previousAttribute = wireframeAttributes.get( geometry );
  35768. if ( previousAttribute ) attributes.remove( previousAttribute );
  35769. //
  35770. wireframeAttributes.set( geometry, attribute );
  35771. }
  35772. function getWireframeAttribute( geometry ) {
  35773. const currentAttribute = wireframeAttributes.get( geometry );
  35774. if ( currentAttribute ) {
  35775. const geometryIndex = geometry.index;
  35776. if ( geometryIndex !== null ) {
  35777. // if the attribute is obsolete, create a new one
  35778. if ( currentAttribute.version < geometryIndex.version ) {
  35779. updateWireframeAttribute( geometry );
  35780. }
  35781. }
  35782. } else {
  35783. updateWireframeAttribute( geometry );
  35784. }
  35785. return wireframeAttributes.get( geometry );
  35786. }
  35787. return {
  35788. get: get,
  35789. update: update,
  35790. getWireframeAttribute: getWireframeAttribute
  35791. };
  35792. }
  35793. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  35794. let mode;
  35795. function setMode( value ) {
  35796. mode = value;
  35797. }
  35798. let type, bytesPerElement;
  35799. function setIndex( value ) {
  35800. type = value.type;
  35801. bytesPerElement = value.bytesPerElement;
  35802. }
  35803. function render( start, count ) {
  35804. gl.drawElements( mode, count, type, start * bytesPerElement );
  35805. info.update( count, mode, 1 );
  35806. }
  35807. function renderInstances( start, count, primcount ) {
  35808. if ( primcount === 0 ) return;
  35809. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  35810. info.update( count, mode, primcount );
  35811. }
  35812. function renderMultiDraw( starts, counts, drawCount ) {
  35813. if ( drawCount === 0 ) return;
  35814. const extension = extensions.get( 'WEBGL_multi_draw' );
  35815. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  35816. let elementCount = 0;
  35817. for ( let i = 0; i < drawCount; i ++ ) {
  35818. elementCount += counts[ i ];
  35819. }
  35820. info.update( elementCount, mode, 1 );
  35821. }
  35822. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  35823. if ( drawCount === 0 ) return;
  35824. const extension = extensions.get( 'WEBGL_multi_draw' );
  35825. if ( extension === null ) {
  35826. for ( let i = 0; i < starts.length; i ++ ) {
  35827. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  35828. }
  35829. } else {
  35830. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  35831. let elementCount = 0;
  35832. for ( let i = 0; i < drawCount; i ++ ) {
  35833. elementCount += counts[ i ] * primcount[ i ];
  35834. }
  35835. info.update( elementCount, mode, 1 );
  35836. }
  35837. }
  35838. //
  35839. this.setMode = setMode;
  35840. this.setIndex = setIndex;
  35841. this.render = render;
  35842. this.renderInstances = renderInstances;
  35843. this.renderMultiDraw = renderMultiDraw;
  35844. this.renderMultiDrawInstances = renderMultiDrawInstances;
  35845. }
  35846. function WebGLInfo( gl ) {
  35847. const memory = {
  35848. geometries: 0,
  35849. textures: 0
  35850. };
  35851. const render = {
  35852. frame: 0,
  35853. calls: 0,
  35854. triangles: 0,
  35855. points: 0,
  35856. lines: 0
  35857. };
  35858. function update( count, mode, instanceCount ) {
  35859. render.calls ++;
  35860. switch ( mode ) {
  35861. case gl.TRIANGLES:
  35862. render.triangles += instanceCount * ( count / 3 );
  35863. break;
  35864. case gl.LINES:
  35865. render.lines += instanceCount * ( count / 2 );
  35866. break;
  35867. case gl.LINE_STRIP:
  35868. render.lines += instanceCount * ( count - 1 );
  35869. break;
  35870. case gl.LINE_LOOP:
  35871. render.lines += instanceCount * count;
  35872. break;
  35873. case gl.POINTS:
  35874. render.points += instanceCount * count;
  35875. break;
  35876. default:
  35877. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  35878. break;
  35879. }
  35880. }
  35881. function reset() {
  35882. render.calls = 0;
  35883. render.triangles = 0;
  35884. render.points = 0;
  35885. render.lines = 0;
  35886. }
  35887. return {
  35888. memory: memory,
  35889. render: render,
  35890. programs: null,
  35891. autoReset: true,
  35892. reset: reset,
  35893. update: update
  35894. };
  35895. }
  35896. function WebGLMorphtargets( gl, capabilities, textures ) {
  35897. const morphTextures = new WeakMap();
  35898. const morph = new Vector4();
  35899. function update( object, geometry, program ) {
  35900. const objectInfluences = object.morphTargetInfluences;
  35901. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  35902. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  35903. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  35904. let entry = morphTextures.get( geometry );
  35905. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  35906. if ( entry !== undefined ) entry.texture.dispose();
  35907. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  35908. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  35909. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  35910. const morphTargets = geometry.morphAttributes.position || [];
  35911. const morphNormals = geometry.morphAttributes.normal || [];
  35912. const morphColors = geometry.morphAttributes.color || [];
  35913. let vertexDataCount = 0;
  35914. if ( hasMorphPosition === true ) vertexDataCount = 1;
  35915. if ( hasMorphNormals === true ) vertexDataCount = 2;
  35916. if ( hasMorphColors === true ) vertexDataCount = 3;
  35917. let width = geometry.attributes.position.count * vertexDataCount;
  35918. let height = 1;
  35919. if ( width > capabilities.maxTextureSize ) {
  35920. height = Math.ceil( width / capabilities.maxTextureSize );
  35921. width = capabilities.maxTextureSize;
  35922. }
  35923. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  35924. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  35925. texture.type = FloatType;
  35926. texture.needsUpdate = true;
  35927. // fill buffer
  35928. const vertexDataStride = vertexDataCount * 4;
  35929. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  35930. const morphTarget = morphTargets[ i ];
  35931. const morphNormal = morphNormals[ i ];
  35932. const morphColor = morphColors[ i ];
  35933. const offset = width * height * 4 * i;
  35934. for ( let j = 0; j < morphTarget.count; j ++ ) {
  35935. const stride = j * vertexDataStride;
  35936. if ( hasMorphPosition === true ) {
  35937. morph.fromBufferAttribute( morphTarget, j );
  35938. buffer[ offset + stride + 0 ] = morph.x;
  35939. buffer[ offset + stride + 1 ] = morph.y;
  35940. buffer[ offset + stride + 2 ] = morph.z;
  35941. buffer[ offset + stride + 3 ] = 0;
  35942. }
  35943. if ( hasMorphNormals === true ) {
  35944. morph.fromBufferAttribute( morphNormal, j );
  35945. buffer[ offset + stride + 4 ] = morph.x;
  35946. buffer[ offset + stride + 5 ] = morph.y;
  35947. buffer[ offset + stride + 6 ] = morph.z;
  35948. buffer[ offset + stride + 7 ] = 0;
  35949. }
  35950. if ( hasMorphColors === true ) {
  35951. morph.fromBufferAttribute( morphColor, j );
  35952. buffer[ offset + stride + 8 ] = morph.x;
  35953. buffer[ offset + stride + 9 ] = morph.y;
  35954. buffer[ offset + stride + 10 ] = morph.z;
  35955. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  35956. }
  35957. }
  35958. }
  35959. entry = {
  35960. count: morphTargetsCount,
  35961. texture: texture,
  35962. size: new Vector2( width, height )
  35963. };
  35964. morphTextures.set( geometry, entry );
  35965. function disposeTexture() {
  35966. texture.dispose();
  35967. morphTextures.delete( geometry );
  35968. geometry.removeEventListener( 'dispose', disposeTexture );
  35969. }
  35970. geometry.addEventListener( 'dispose', disposeTexture );
  35971. }
  35972. //
  35973. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  35974. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  35975. } else {
  35976. let morphInfluencesSum = 0;
  35977. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  35978. morphInfluencesSum += objectInfluences[ i ];
  35979. }
  35980. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  35981. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  35982. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  35983. }
  35984. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  35985. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  35986. }
  35987. return {
  35988. update: update
  35989. };
  35990. }
  35991. function WebGLObjects( gl, geometries, attributes, info ) {
  35992. let updateMap = new WeakMap();
  35993. function update( object ) {
  35994. const frame = info.render.frame;
  35995. const geometry = object.geometry;
  35996. const buffergeometry = geometries.get( object, geometry );
  35997. // Update once per frame
  35998. if ( updateMap.get( buffergeometry ) !== frame ) {
  35999. geometries.update( buffergeometry );
  36000. updateMap.set( buffergeometry, frame );
  36001. }
  36002. if ( object.isInstancedMesh ) {
  36003. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  36004. object.addEventListener( 'dispose', onInstancedMeshDispose );
  36005. }
  36006. if ( updateMap.get( object ) !== frame ) {
  36007. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  36008. if ( object.instanceColor !== null ) {
  36009. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  36010. }
  36011. updateMap.set( object, frame );
  36012. }
  36013. }
  36014. if ( object.isSkinnedMesh ) {
  36015. const skeleton = object.skeleton;
  36016. if ( updateMap.get( skeleton ) !== frame ) {
  36017. skeleton.update();
  36018. updateMap.set( skeleton, frame );
  36019. }
  36020. }
  36021. return buffergeometry;
  36022. }
  36023. function dispose() {
  36024. updateMap = new WeakMap();
  36025. }
  36026. function onInstancedMeshDispose( event ) {
  36027. const instancedMesh = event.target;
  36028. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  36029. attributes.remove( instancedMesh.instanceMatrix );
  36030. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  36031. }
  36032. return {
  36033. update: update,
  36034. dispose: dispose
  36035. };
  36036. }
  36037. /**
  36038. * Uniforms of a program.
  36039. * Those form a tree structure with a special top-level container for the root,
  36040. * which you get by calling 'new WebGLUniforms( gl, program )'.
  36041. *
  36042. *
  36043. * Properties of inner nodes including the top-level container:
  36044. *
  36045. * .seq - array of nested uniforms
  36046. * .map - nested uniforms by name
  36047. *
  36048. *
  36049. * Methods of all nodes except the top-level container:
  36050. *
  36051. * .setValue( gl, value, [textures] )
  36052. *
  36053. * uploads a uniform value(s)
  36054. * the 'textures' parameter is needed for sampler uniforms
  36055. *
  36056. *
  36057. * Static methods of the top-level container (textures factorizations):
  36058. *
  36059. * .upload( gl, seq, values, textures )
  36060. *
  36061. * sets uniforms in 'seq' to 'values[id].value'
  36062. *
  36063. * .seqWithValue( seq, values ) : filteredSeq
  36064. *
  36065. * filters 'seq' entries with corresponding entry in values
  36066. *
  36067. *
  36068. * Methods of the top-level container (textures factorizations):
  36069. *
  36070. * .setValue( gl, name, value, textures )
  36071. *
  36072. * sets uniform with name 'name' to 'value'
  36073. *
  36074. * .setOptional( gl, obj, prop )
  36075. *
  36076. * like .set for an optional property of the object
  36077. *
  36078. */
  36079. const emptyTexture = /*@__PURE__*/ new Texture();
  36080. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  36081. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  36082. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  36083. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  36084. // --- Utilities ---
  36085. // Array Caches (provide typed arrays for temporary by size)
  36086. const arrayCacheF32 = [];
  36087. const arrayCacheI32 = [];
  36088. // Float32Array caches used for uploading Matrix uniforms
  36089. const mat4array = new Float32Array( 16 );
  36090. const mat3array = new Float32Array( 9 );
  36091. const mat2array = new Float32Array( 4 );
  36092. // Flattening for arrays of vectors and matrices
  36093. function flatten( array, nBlocks, blockSize ) {
  36094. const firstElem = array[ 0 ];
  36095. if ( firstElem <= 0 || firstElem > 0 ) return array;
  36096. // unoptimized: ! isNaN( firstElem )
  36097. // see http://jacksondunstan.com/articles/983
  36098. const n = nBlocks * blockSize;
  36099. let r = arrayCacheF32[ n ];
  36100. if ( r === undefined ) {
  36101. r = new Float32Array( n );
  36102. arrayCacheF32[ n ] = r;
  36103. }
  36104. if ( nBlocks !== 0 ) {
  36105. firstElem.toArray( r, 0 );
  36106. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  36107. offset += blockSize;
  36108. array[ i ].toArray( r, offset );
  36109. }
  36110. }
  36111. return r;
  36112. }
  36113. function arraysEqual( a, b ) {
  36114. if ( a.length !== b.length ) return false;
  36115. for ( let i = 0, l = a.length; i < l; i ++ ) {
  36116. if ( a[ i ] !== b[ i ] ) return false;
  36117. }
  36118. return true;
  36119. }
  36120. function copyArray( a, b ) {
  36121. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36122. a[ i ] = b[ i ];
  36123. }
  36124. }
  36125. // Texture unit allocation
  36126. function allocTexUnits( textures, n ) {
  36127. let r = arrayCacheI32[ n ];
  36128. if ( r === undefined ) {
  36129. r = new Int32Array( n );
  36130. arrayCacheI32[ n ] = r;
  36131. }
  36132. for ( let i = 0; i !== n; ++ i ) {
  36133. r[ i ] = textures.allocateTextureUnit();
  36134. }
  36135. return r;
  36136. }
  36137. // --- Setters ---
  36138. // Note: Defining these methods externally, because they come in a bunch
  36139. // and this way their names minify.
  36140. // Single scalar
  36141. function setValueV1f( gl, v ) {
  36142. const cache = this.cache;
  36143. if ( cache[ 0 ] === v ) return;
  36144. gl.uniform1f( this.addr, v );
  36145. cache[ 0 ] = v;
  36146. }
  36147. // Single float vector (from flat array or THREE.VectorN)
  36148. function setValueV2f( gl, v ) {
  36149. const cache = this.cache;
  36150. if ( v.x !== undefined ) {
  36151. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  36152. gl.uniform2f( this.addr, v.x, v.y );
  36153. cache[ 0 ] = v.x;
  36154. cache[ 1 ] = v.y;
  36155. }
  36156. } else {
  36157. if ( arraysEqual( cache, v ) ) return;
  36158. gl.uniform2fv( this.addr, v );
  36159. copyArray( cache, v );
  36160. }
  36161. }
  36162. function setValueV3f( gl, v ) {
  36163. const cache = this.cache;
  36164. if ( v.x !== undefined ) {
  36165. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  36166. gl.uniform3f( this.addr, v.x, v.y, v.z );
  36167. cache[ 0 ] = v.x;
  36168. cache[ 1 ] = v.y;
  36169. cache[ 2 ] = v.z;
  36170. }
  36171. } else if ( v.r !== undefined ) {
  36172. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  36173. gl.uniform3f( this.addr, v.r, v.g, v.b );
  36174. cache[ 0 ] = v.r;
  36175. cache[ 1 ] = v.g;
  36176. cache[ 2 ] = v.b;
  36177. }
  36178. } else {
  36179. if ( arraysEqual( cache, v ) ) return;
  36180. gl.uniform3fv( this.addr, v );
  36181. copyArray( cache, v );
  36182. }
  36183. }
  36184. function setValueV4f( gl, v ) {
  36185. const cache = this.cache;
  36186. if ( v.x !== undefined ) {
  36187. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  36188. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  36189. cache[ 0 ] = v.x;
  36190. cache[ 1 ] = v.y;
  36191. cache[ 2 ] = v.z;
  36192. cache[ 3 ] = v.w;
  36193. }
  36194. } else {
  36195. if ( arraysEqual( cache, v ) ) return;
  36196. gl.uniform4fv( this.addr, v );
  36197. copyArray( cache, v );
  36198. }
  36199. }
  36200. // Single matrix (from flat array or THREE.MatrixN)
  36201. function setValueM2( gl, v ) {
  36202. const cache = this.cache;
  36203. const elements = v.elements;
  36204. if ( elements === undefined ) {
  36205. if ( arraysEqual( cache, v ) ) return;
  36206. gl.uniformMatrix2fv( this.addr, false, v );
  36207. copyArray( cache, v );
  36208. } else {
  36209. if ( arraysEqual( cache, elements ) ) return;
  36210. mat2array.set( elements );
  36211. gl.uniformMatrix2fv( this.addr, false, mat2array );
  36212. copyArray( cache, elements );
  36213. }
  36214. }
  36215. function setValueM3( gl, v ) {
  36216. const cache = this.cache;
  36217. const elements = v.elements;
  36218. if ( elements === undefined ) {
  36219. if ( arraysEqual( cache, v ) ) return;
  36220. gl.uniformMatrix3fv( this.addr, false, v );
  36221. copyArray( cache, v );
  36222. } else {
  36223. if ( arraysEqual( cache, elements ) ) return;
  36224. mat3array.set( elements );
  36225. gl.uniformMatrix3fv( this.addr, false, mat3array );
  36226. copyArray( cache, elements );
  36227. }
  36228. }
  36229. function setValueM4( gl, v ) {
  36230. const cache = this.cache;
  36231. const elements = v.elements;
  36232. if ( elements === undefined ) {
  36233. if ( arraysEqual( cache, v ) ) return;
  36234. gl.uniformMatrix4fv( this.addr, false, v );
  36235. copyArray( cache, v );
  36236. } else {
  36237. if ( arraysEqual( cache, elements ) ) return;
  36238. mat4array.set( elements );
  36239. gl.uniformMatrix4fv( this.addr, false, mat4array );
  36240. copyArray( cache, elements );
  36241. }
  36242. }
  36243. // Single integer / boolean
  36244. function setValueV1i( gl, v ) {
  36245. const cache = this.cache;
  36246. if ( cache[ 0 ] === v ) return;
  36247. gl.uniform1i( this.addr, v );
  36248. cache[ 0 ] = v;
  36249. }
  36250. // Single integer / boolean vector (from flat array or THREE.VectorN)
  36251. function setValueV2i( gl, v ) {
  36252. const cache = this.cache;
  36253. if ( v.x !== undefined ) {
  36254. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  36255. gl.uniform2i( this.addr, v.x, v.y );
  36256. cache[ 0 ] = v.x;
  36257. cache[ 1 ] = v.y;
  36258. }
  36259. } else {
  36260. if ( arraysEqual( cache, v ) ) return;
  36261. gl.uniform2iv( this.addr, v );
  36262. copyArray( cache, v );
  36263. }
  36264. }
  36265. function setValueV3i( gl, v ) {
  36266. const cache = this.cache;
  36267. if ( v.x !== undefined ) {
  36268. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  36269. gl.uniform3i( this.addr, v.x, v.y, v.z );
  36270. cache[ 0 ] = v.x;
  36271. cache[ 1 ] = v.y;
  36272. cache[ 2 ] = v.z;
  36273. }
  36274. } else {
  36275. if ( arraysEqual( cache, v ) ) return;
  36276. gl.uniform3iv( this.addr, v );
  36277. copyArray( cache, v );
  36278. }
  36279. }
  36280. function setValueV4i( gl, v ) {
  36281. const cache = this.cache;
  36282. if ( v.x !== undefined ) {
  36283. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  36284. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  36285. cache[ 0 ] = v.x;
  36286. cache[ 1 ] = v.y;
  36287. cache[ 2 ] = v.z;
  36288. cache[ 3 ] = v.w;
  36289. }
  36290. } else {
  36291. if ( arraysEqual( cache, v ) ) return;
  36292. gl.uniform4iv( this.addr, v );
  36293. copyArray( cache, v );
  36294. }
  36295. }
  36296. // Single unsigned integer
  36297. function setValueV1ui( gl, v ) {
  36298. const cache = this.cache;
  36299. if ( cache[ 0 ] === v ) return;
  36300. gl.uniform1ui( this.addr, v );
  36301. cache[ 0 ] = v;
  36302. }
  36303. // Single unsigned integer vector (from flat array or THREE.VectorN)
  36304. function setValueV2ui( gl, v ) {
  36305. const cache = this.cache;
  36306. if ( v.x !== undefined ) {
  36307. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  36308. gl.uniform2ui( this.addr, v.x, v.y );
  36309. cache[ 0 ] = v.x;
  36310. cache[ 1 ] = v.y;
  36311. }
  36312. } else {
  36313. if ( arraysEqual( cache, v ) ) return;
  36314. gl.uniform2uiv( this.addr, v );
  36315. copyArray( cache, v );
  36316. }
  36317. }
  36318. function setValueV3ui( gl, v ) {
  36319. const cache = this.cache;
  36320. if ( v.x !== undefined ) {
  36321. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  36322. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  36323. cache[ 0 ] = v.x;
  36324. cache[ 1 ] = v.y;
  36325. cache[ 2 ] = v.z;
  36326. }
  36327. } else {
  36328. if ( arraysEqual( cache, v ) ) return;
  36329. gl.uniform3uiv( this.addr, v );
  36330. copyArray( cache, v );
  36331. }
  36332. }
  36333. function setValueV4ui( gl, v ) {
  36334. const cache = this.cache;
  36335. if ( v.x !== undefined ) {
  36336. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  36337. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  36338. cache[ 0 ] = v.x;
  36339. cache[ 1 ] = v.y;
  36340. cache[ 2 ] = v.z;
  36341. cache[ 3 ] = v.w;
  36342. }
  36343. } else {
  36344. if ( arraysEqual( cache, v ) ) return;
  36345. gl.uniform4uiv( this.addr, v );
  36346. copyArray( cache, v );
  36347. }
  36348. }
  36349. // Single texture (2D / Cube)
  36350. function setValueT1( gl, v, textures ) {
  36351. const cache = this.cache;
  36352. const unit = textures.allocateTextureUnit();
  36353. if ( cache[ 0 ] !== unit ) {
  36354. gl.uniform1i( this.addr, unit );
  36355. cache[ 0 ] = unit;
  36356. }
  36357. let emptyTexture2D;
  36358. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  36359. emptyShadowTexture.compareFunction = LessEqualCompare; // #28670
  36360. emptyTexture2D = emptyShadowTexture;
  36361. } else {
  36362. emptyTexture2D = emptyTexture;
  36363. }
  36364. textures.setTexture2D( v || emptyTexture2D, unit );
  36365. }
  36366. function setValueT3D1( gl, v, textures ) {
  36367. const cache = this.cache;
  36368. const unit = textures.allocateTextureUnit();
  36369. if ( cache[ 0 ] !== unit ) {
  36370. gl.uniform1i( this.addr, unit );
  36371. cache[ 0 ] = unit;
  36372. }
  36373. textures.setTexture3D( v || empty3dTexture, unit );
  36374. }
  36375. function setValueT6( gl, v, textures ) {
  36376. const cache = this.cache;
  36377. const unit = textures.allocateTextureUnit();
  36378. if ( cache[ 0 ] !== unit ) {
  36379. gl.uniform1i( this.addr, unit );
  36380. cache[ 0 ] = unit;
  36381. }
  36382. textures.setTextureCube( v || emptyCubeTexture, unit );
  36383. }
  36384. function setValueT2DArray1( gl, v, textures ) {
  36385. const cache = this.cache;
  36386. const unit = textures.allocateTextureUnit();
  36387. if ( cache[ 0 ] !== unit ) {
  36388. gl.uniform1i( this.addr, unit );
  36389. cache[ 0 ] = unit;
  36390. }
  36391. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  36392. }
  36393. // Helper to pick the right setter for the singular case
  36394. function getSingularSetter( type ) {
  36395. switch ( type ) {
  36396. case 0x1406: return setValueV1f; // FLOAT
  36397. case 0x8b50: return setValueV2f; // _VEC2
  36398. case 0x8b51: return setValueV3f; // _VEC3
  36399. case 0x8b52: return setValueV4f; // _VEC4
  36400. case 0x8b5a: return setValueM2; // _MAT2
  36401. case 0x8b5b: return setValueM3; // _MAT3
  36402. case 0x8b5c: return setValueM4; // _MAT4
  36403. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  36404. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  36405. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  36406. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  36407. case 0x1405: return setValueV1ui; // UINT
  36408. case 0x8dc6: return setValueV2ui; // _VEC2
  36409. case 0x8dc7: return setValueV3ui; // _VEC3
  36410. case 0x8dc8: return setValueV4ui; // _VEC4
  36411. case 0x8b5e: // SAMPLER_2D
  36412. case 0x8d66: // SAMPLER_EXTERNAL_OES
  36413. case 0x8dca: // INT_SAMPLER_2D
  36414. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  36415. case 0x8b62: // SAMPLER_2D_SHADOW
  36416. return setValueT1;
  36417. case 0x8b5f: // SAMPLER_3D
  36418. case 0x8dcb: // INT_SAMPLER_3D
  36419. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  36420. return setValueT3D1;
  36421. case 0x8b60: // SAMPLER_CUBE
  36422. case 0x8dcc: // INT_SAMPLER_CUBE
  36423. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  36424. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  36425. return setValueT6;
  36426. case 0x8dc1: // SAMPLER_2D_ARRAY
  36427. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  36428. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  36429. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  36430. return setValueT2DArray1;
  36431. }
  36432. }
  36433. // Array of scalars
  36434. function setValueV1fArray( gl, v ) {
  36435. gl.uniform1fv( this.addr, v );
  36436. }
  36437. // Array of vectors (from flat array or array of THREE.VectorN)
  36438. function setValueV2fArray( gl, v ) {
  36439. const data = flatten( v, this.size, 2 );
  36440. gl.uniform2fv( this.addr, data );
  36441. }
  36442. function setValueV3fArray( gl, v ) {
  36443. const data = flatten( v, this.size, 3 );
  36444. gl.uniform3fv( this.addr, data );
  36445. }
  36446. function setValueV4fArray( gl, v ) {
  36447. const data = flatten( v, this.size, 4 );
  36448. gl.uniform4fv( this.addr, data );
  36449. }
  36450. // Array of matrices (from flat array or array of THREE.MatrixN)
  36451. function setValueM2Array( gl, v ) {
  36452. const data = flatten( v, this.size, 4 );
  36453. gl.uniformMatrix2fv( this.addr, false, data );
  36454. }
  36455. function setValueM3Array( gl, v ) {
  36456. const data = flatten( v, this.size, 9 );
  36457. gl.uniformMatrix3fv( this.addr, false, data );
  36458. }
  36459. function setValueM4Array( gl, v ) {
  36460. const data = flatten( v, this.size, 16 );
  36461. gl.uniformMatrix4fv( this.addr, false, data );
  36462. }
  36463. // Array of integer / boolean
  36464. function setValueV1iArray( gl, v ) {
  36465. gl.uniform1iv( this.addr, v );
  36466. }
  36467. // Array of integer / boolean vectors (from flat array)
  36468. function setValueV2iArray( gl, v ) {
  36469. gl.uniform2iv( this.addr, v );
  36470. }
  36471. function setValueV3iArray( gl, v ) {
  36472. gl.uniform3iv( this.addr, v );
  36473. }
  36474. function setValueV4iArray( gl, v ) {
  36475. gl.uniform4iv( this.addr, v );
  36476. }
  36477. // Array of unsigned integer
  36478. function setValueV1uiArray( gl, v ) {
  36479. gl.uniform1uiv( this.addr, v );
  36480. }
  36481. // Array of unsigned integer vectors (from flat array)
  36482. function setValueV2uiArray( gl, v ) {
  36483. gl.uniform2uiv( this.addr, v );
  36484. }
  36485. function setValueV3uiArray( gl, v ) {
  36486. gl.uniform3uiv( this.addr, v );
  36487. }
  36488. function setValueV4uiArray( gl, v ) {
  36489. gl.uniform4uiv( this.addr, v );
  36490. }
  36491. // Array of textures (2D / 3D / Cube / 2DArray)
  36492. function setValueT1Array( gl, v, textures ) {
  36493. const cache = this.cache;
  36494. const n = v.length;
  36495. const units = allocTexUnits( textures, n );
  36496. if ( ! arraysEqual( cache, units ) ) {
  36497. gl.uniform1iv( this.addr, units );
  36498. copyArray( cache, units );
  36499. }
  36500. for ( let i = 0; i !== n; ++ i ) {
  36501. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  36502. }
  36503. }
  36504. function setValueT3DArray( gl, v, textures ) {
  36505. const cache = this.cache;
  36506. const n = v.length;
  36507. const units = allocTexUnits( textures, n );
  36508. if ( ! arraysEqual( cache, units ) ) {
  36509. gl.uniform1iv( this.addr, units );
  36510. copyArray( cache, units );
  36511. }
  36512. for ( let i = 0; i !== n; ++ i ) {
  36513. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  36514. }
  36515. }
  36516. function setValueT6Array( gl, v, textures ) {
  36517. const cache = this.cache;
  36518. const n = v.length;
  36519. const units = allocTexUnits( textures, n );
  36520. if ( ! arraysEqual( cache, units ) ) {
  36521. gl.uniform1iv( this.addr, units );
  36522. copyArray( cache, units );
  36523. }
  36524. for ( let i = 0; i !== n; ++ i ) {
  36525. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  36526. }
  36527. }
  36528. function setValueT2DArrayArray( gl, v, textures ) {
  36529. const cache = this.cache;
  36530. const n = v.length;
  36531. const units = allocTexUnits( textures, n );
  36532. if ( ! arraysEqual( cache, units ) ) {
  36533. gl.uniform1iv( this.addr, units );
  36534. copyArray( cache, units );
  36535. }
  36536. for ( let i = 0; i !== n; ++ i ) {
  36537. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  36538. }
  36539. }
  36540. // Helper to pick the right setter for a pure (bottom-level) array
  36541. function getPureArraySetter( type ) {
  36542. switch ( type ) {
  36543. case 0x1406: return setValueV1fArray; // FLOAT
  36544. case 0x8b50: return setValueV2fArray; // _VEC2
  36545. case 0x8b51: return setValueV3fArray; // _VEC3
  36546. case 0x8b52: return setValueV4fArray; // _VEC4
  36547. case 0x8b5a: return setValueM2Array; // _MAT2
  36548. case 0x8b5b: return setValueM3Array; // _MAT3
  36549. case 0x8b5c: return setValueM4Array; // _MAT4
  36550. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  36551. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  36552. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  36553. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  36554. case 0x1405: return setValueV1uiArray; // UINT
  36555. case 0x8dc6: return setValueV2uiArray; // _VEC2
  36556. case 0x8dc7: return setValueV3uiArray; // _VEC3
  36557. case 0x8dc8: return setValueV4uiArray; // _VEC4
  36558. case 0x8b5e: // SAMPLER_2D
  36559. case 0x8d66: // SAMPLER_EXTERNAL_OES
  36560. case 0x8dca: // INT_SAMPLER_2D
  36561. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  36562. case 0x8b62: // SAMPLER_2D_SHADOW
  36563. return setValueT1Array;
  36564. case 0x8b5f: // SAMPLER_3D
  36565. case 0x8dcb: // INT_SAMPLER_3D
  36566. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  36567. return setValueT3DArray;
  36568. case 0x8b60: // SAMPLER_CUBE
  36569. case 0x8dcc: // INT_SAMPLER_CUBE
  36570. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  36571. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  36572. return setValueT6Array;
  36573. case 0x8dc1: // SAMPLER_2D_ARRAY
  36574. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  36575. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  36576. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  36577. return setValueT2DArrayArray;
  36578. }
  36579. }
  36580. // --- Uniform Classes ---
  36581. class SingleUniform {
  36582. constructor( id, activeInfo, addr ) {
  36583. this.id = id;
  36584. this.addr = addr;
  36585. this.cache = [];
  36586. this.type = activeInfo.type;
  36587. this.setValue = getSingularSetter( activeInfo.type );
  36588. // this.path = activeInfo.name; // DEBUG
  36589. }
  36590. }
  36591. class PureArrayUniform {
  36592. constructor( id, activeInfo, addr ) {
  36593. this.id = id;
  36594. this.addr = addr;
  36595. this.cache = [];
  36596. this.type = activeInfo.type;
  36597. this.size = activeInfo.size;
  36598. this.setValue = getPureArraySetter( activeInfo.type );
  36599. // this.path = activeInfo.name; // DEBUG
  36600. }
  36601. }
  36602. class StructuredUniform {
  36603. constructor( id ) {
  36604. this.id = id;
  36605. this.seq = [];
  36606. this.map = {};
  36607. }
  36608. setValue( gl, value, textures ) {
  36609. const seq = this.seq;
  36610. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  36611. const u = seq[ i ];
  36612. u.setValue( gl, value[ u.id ], textures );
  36613. }
  36614. }
  36615. }
  36616. // --- Top-level ---
  36617. // Parser - builds up the property tree from the path strings
  36618. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  36619. // extracts
  36620. // - the identifier (member name or array index)
  36621. // - followed by an optional right bracket (found when array index)
  36622. // - followed by an optional left bracket or dot (type of subscript)
  36623. //
  36624. // Note: These portions can be read in a non-overlapping fashion and
  36625. // allow straightforward parsing of the hierarchy that WebGL encodes
  36626. // in the uniform names.
  36627. function addUniform( container, uniformObject ) {
  36628. container.seq.push( uniformObject );
  36629. container.map[ uniformObject.id ] = uniformObject;
  36630. }
  36631. function parseUniform( activeInfo, addr, container ) {
  36632. const path = activeInfo.name,
  36633. pathLength = path.length;
  36634. // reset RegExp object, because of the early exit of a previous run
  36635. RePathPart.lastIndex = 0;
  36636. while ( true ) {
  36637. const match = RePathPart.exec( path ),
  36638. matchEnd = RePathPart.lastIndex;
  36639. let id = match[ 1 ];
  36640. const idIsIndex = match[ 2 ] === ']',
  36641. subscript = match[ 3 ];
  36642. if ( idIsIndex ) id = id | 0; // convert to integer
  36643. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  36644. // bare name or "pure" bottom-level array "[0]" suffix
  36645. addUniform( container, subscript === undefined ?
  36646. new SingleUniform( id, activeInfo, addr ) :
  36647. new PureArrayUniform( id, activeInfo, addr ) );
  36648. break;
  36649. } else {
  36650. // step into inner node / create it in case it doesn't exist
  36651. const map = container.map;
  36652. let next = map[ id ];
  36653. if ( next === undefined ) {
  36654. next = new StructuredUniform( id );
  36655. addUniform( container, next );
  36656. }
  36657. container = next;
  36658. }
  36659. }
  36660. }
  36661. // Root Container
  36662. class WebGLUniforms {
  36663. constructor( gl, program ) {
  36664. this.seq = [];
  36665. this.map = {};
  36666. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  36667. for ( let i = 0; i < n; ++ i ) {
  36668. const info = gl.getActiveUniform( program, i ),
  36669. addr = gl.getUniformLocation( program, info.name );
  36670. parseUniform( info, addr, this );
  36671. }
  36672. }
  36673. setValue( gl, name, value, textures ) {
  36674. const u = this.map[ name ];
  36675. if ( u !== undefined ) u.setValue( gl, value, textures );
  36676. }
  36677. setOptional( gl, object, name ) {
  36678. const v = object[ name ];
  36679. if ( v !== undefined ) this.setValue( gl, name, v );
  36680. }
  36681. static upload( gl, seq, values, textures ) {
  36682. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  36683. const u = seq[ i ],
  36684. v = values[ u.id ];
  36685. if ( v.needsUpdate !== false ) {
  36686. // note: always updating when .needsUpdate is undefined
  36687. u.setValue( gl, v.value, textures );
  36688. }
  36689. }
  36690. }
  36691. static seqWithValue( seq, values ) {
  36692. const r = [];
  36693. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  36694. const u = seq[ i ];
  36695. if ( u.id in values ) r.push( u );
  36696. }
  36697. return r;
  36698. }
  36699. }
  36700. function WebGLShader( gl, type, string ) {
  36701. const shader = gl.createShader( type );
  36702. gl.shaderSource( shader, string );
  36703. gl.compileShader( shader );
  36704. return shader;
  36705. }
  36706. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  36707. const COMPLETION_STATUS_KHR = 0x91B1;
  36708. let programIdCount = 0;
  36709. function handleSource( string, errorLine ) {
  36710. const lines = string.split( '\n' );
  36711. const lines2 = [];
  36712. const from = Math.max( errorLine - 6, 0 );
  36713. const to = Math.min( errorLine + 6, lines.length );
  36714. for ( let i = from; i < to; i ++ ) {
  36715. const line = i + 1;
  36716. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  36717. }
  36718. return lines2.join( '\n' );
  36719. }
  36720. const _m0 = /*@__PURE__*/ new Matrix3();
  36721. function getEncodingComponents( colorSpace ) {
  36722. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  36723. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  36724. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  36725. case LinearTransfer:
  36726. return [ encodingMatrix, 'LinearTransferOETF' ];
  36727. case SRGBTransfer:
  36728. return [ encodingMatrix, 'sRGBTransferOETF' ];
  36729. default:
  36730. console.warn( 'THREE.WebGLProgram: Unsupported color space: ', colorSpace );
  36731. return [ encodingMatrix, 'LinearTransferOETF' ];
  36732. }
  36733. }
  36734. function getShaderErrors( gl, shader, type ) {
  36735. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  36736. const errors = gl.getShaderInfoLog( shader ).trim();
  36737. if ( status && errors === '' ) return '';
  36738. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  36739. if ( errorMatches ) {
  36740. // --enable-privileged-webgl-extension
  36741. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  36742. const errorLine = parseInt( errorMatches[ 1 ] );
  36743. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  36744. } else {
  36745. return errors;
  36746. }
  36747. }
  36748. function getTexelEncodingFunction( functionName, colorSpace ) {
  36749. const components = getEncodingComponents( colorSpace );
  36750. return [
  36751. `vec4 ${functionName}( vec4 value ) {`,
  36752. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  36753. '}',
  36754. ].join( '\n' );
  36755. }
  36756. function getToneMappingFunction( functionName, toneMapping ) {
  36757. let toneMappingName;
  36758. switch ( toneMapping ) {
  36759. case LinearToneMapping:
  36760. toneMappingName = 'Linear';
  36761. break;
  36762. case ReinhardToneMapping:
  36763. toneMappingName = 'Reinhard';
  36764. break;
  36765. case CineonToneMapping:
  36766. toneMappingName = 'Cineon';
  36767. break;
  36768. case ACESFilmicToneMapping:
  36769. toneMappingName = 'ACESFilmic';
  36770. break;
  36771. case AgXToneMapping:
  36772. toneMappingName = 'AgX';
  36773. break;
  36774. case NeutralToneMapping:
  36775. toneMappingName = 'Neutral';
  36776. break;
  36777. case CustomToneMapping:
  36778. toneMappingName = 'Custom';
  36779. break;
  36780. default:
  36781. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  36782. toneMappingName = 'Linear';
  36783. }
  36784. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  36785. }
  36786. const _v0 = /*@__PURE__*/ new Vector3();
  36787. function getLuminanceFunction() {
  36788. ColorManagement.getLuminanceCoefficients( _v0 );
  36789. const r = _v0.x.toFixed( 4 );
  36790. const g = _v0.y.toFixed( 4 );
  36791. const b = _v0.z.toFixed( 4 );
  36792. return [
  36793. 'float luminance( const in vec3 rgb ) {',
  36794. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  36795. ' return dot( weights, rgb );',
  36796. '}'
  36797. ].join( '\n' );
  36798. }
  36799. function generateVertexExtensions( parameters ) {
  36800. const chunks = [
  36801. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  36802. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  36803. ];
  36804. return chunks.filter( filterEmptyLine ).join( '\n' );
  36805. }
  36806. function generateDefines( defines ) {
  36807. const chunks = [];
  36808. for ( const name in defines ) {
  36809. const value = defines[ name ];
  36810. if ( value === false ) continue;
  36811. chunks.push( '#define ' + name + ' ' + value );
  36812. }
  36813. return chunks.join( '\n' );
  36814. }
  36815. function fetchAttributeLocations( gl, program ) {
  36816. const attributes = {};
  36817. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  36818. for ( let i = 0; i < n; i ++ ) {
  36819. const info = gl.getActiveAttrib( program, i );
  36820. const name = info.name;
  36821. let locationSize = 1;
  36822. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  36823. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  36824. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  36825. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  36826. attributes[ name ] = {
  36827. type: info.type,
  36828. location: gl.getAttribLocation( program, name ),
  36829. locationSize: locationSize
  36830. };
  36831. }
  36832. return attributes;
  36833. }
  36834. function filterEmptyLine( string ) {
  36835. return string !== '';
  36836. }
  36837. function replaceLightNums( string, parameters ) {
  36838. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  36839. return string
  36840. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  36841. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  36842. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  36843. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  36844. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  36845. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  36846. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  36847. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  36848. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  36849. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  36850. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  36851. }
  36852. function replaceClippingPlaneNums( string, parameters ) {
  36853. return string
  36854. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  36855. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  36856. }
  36857. // Resolve Includes
  36858. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  36859. function resolveIncludes( string ) {
  36860. return string.replace( includePattern, includeReplacer );
  36861. }
  36862. const shaderChunkMap = new Map();
  36863. function includeReplacer( match, include ) {
  36864. let string = ShaderChunk[ include ];
  36865. if ( string === undefined ) {
  36866. const newInclude = shaderChunkMap.get( include );
  36867. if ( newInclude !== undefined ) {
  36868. string = ShaderChunk[ newInclude ];
  36869. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  36870. } else {
  36871. throw new Error( 'Can not resolve #include <' + include + '>' );
  36872. }
  36873. }
  36874. return resolveIncludes( string );
  36875. }
  36876. // Unroll Loops
  36877. 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;
  36878. function unrollLoops( string ) {
  36879. return string.replace( unrollLoopPattern, loopReplacer );
  36880. }
  36881. function loopReplacer( match, start, end, snippet ) {
  36882. let string = '';
  36883. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  36884. string += snippet
  36885. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  36886. .replace( /UNROLLED_LOOP_INDEX/g, i );
  36887. }
  36888. return string;
  36889. }
  36890. //
  36891. function generatePrecision( parameters ) {
  36892. let precisionstring = `precision ${parameters.precision} float;
  36893. precision ${parameters.precision} int;
  36894. precision ${parameters.precision} sampler2D;
  36895. precision ${parameters.precision} samplerCube;
  36896. precision ${parameters.precision} sampler3D;
  36897. precision ${parameters.precision} sampler2DArray;
  36898. precision ${parameters.precision} sampler2DShadow;
  36899. precision ${parameters.precision} samplerCubeShadow;
  36900. precision ${parameters.precision} sampler2DArrayShadow;
  36901. precision ${parameters.precision} isampler2D;
  36902. precision ${parameters.precision} isampler3D;
  36903. precision ${parameters.precision} isamplerCube;
  36904. precision ${parameters.precision} isampler2DArray;
  36905. precision ${parameters.precision} usampler2D;
  36906. precision ${parameters.precision} usampler3D;
  36907. precision ${parameters.precision} usamplerCube;
  36908. precision ${parameters.precision} usampler2DArray;
  36909. `;
  36910. if ( parameters.precision === 'highp' ) {
  36911. precisionstring += '\n#define HIGH_PRECISION';
  36912. } else if ( parameters.precision === 'mediump' ) {
  36913. precisionstring += '\n#define MEDIUM_PRECISION';
  36914. } else if ( parameters.precision === 'lowp' ) {
  36915. precisionstring += '\n#define LOW_PRECISION';
  36916. }
  36917. return precisionstring;
  36918. }
  36919. function generateShadowMapTypeDefine( parameters ) {
  36920. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  36921. if ( parameters.shadowMapType === PCFShadowMap ) {
  36922. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  36923. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  36924. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  36925. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  36926. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  36927. }
  36928. return shadowMapTypeDefine;
  36929. }
  36930. function generateEnvMapTypeDefine( parameters ) {
  36931. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  36932. if ( parameters.envMap ) {
  36933. switch ( parameters.envMapMode ) {
  36934. case CubeReflectionMapping:
  36935. case CubeRefractionMapping:
  36936. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  36937. break;
  36938. case CubeUVReflectionMapping:
  36939. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  36940. break;
  36941. }
  36942. }
  36943. return envMapTypeDefine;
  36944. }
  36945. function generateEnvMapModeDefine( parameters ) {
  36946. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  36947. if ( parameters.envMap ) {
  36948. switch ( parameters.envMapMode ) {
  36949. case CubeRefractionMapping:
  36950. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  36951. break;
  36952. }
  36953. }
  36954. return envMapModeDefine;
  36955. }
  36956. function generateEnvMapBlendingDefine( parameters ) {
  36957. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  36958. if ( parameters.envMap ) {
  36959. switch ( parameters.combine ) {
  36960. case MultiplyOperation:
  36961. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  36962. break;
  36963. case MixOperation:
  36964. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  36965. break;
  36966. case AddOperation:
  36967. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  36968. break;
  36969. }
  36970. }
  36971. return envMapBlendingDefine;
  36972. }
  36973. function generateCubeUVSize( parameters ) {
  36974. const imageHeight = parameters.envMapCubeUVHeight;
  36975. if ( imageHeight === null ) return null;
  36976. const maxMip = Math.log2( imageHeight ) - 2;
  36977. const texelHeight = 1.0 / imageHeight;
  36978. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  36979. return { texelWidth, texelHeight, maxMip };
  36980. }
  36981. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  36982. // TODO Send this event to Three.js DevTools
  36983. // console.log( 'WebGLProgram', cacheKey );
  36984. const gl = renderer.getContext();
  36985. const defines = parameters.defines;
  36986. let vertexShader = parameters.vertexShader;
  36987. let fragmentShader = parameters.fragmentShader;
  36988. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  36989. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  36990. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  36991. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  36992. const envMapCubeUVSize = generateCubeUVSize( parameters );
  36993. const customVertexExtensions = generateVertexExtensions( parameters );
  36994. const customDefines = generateDefines( defines );
  36995. const program = gl.createProgram();
  36996. let prefixVertex, prefixFragment;
  36997. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  36998. if ( parameters.isRawShaderMaterial ) {
  36999. prefixVertex = [
  37000. '#define SHADER_TYPE ' + parameters.shaderType,
  37001. '#define SHADER_NAME ' + parameters.shaderName,
  37002. customDefines
  37003. ].filter( filterEmptyLine ).join( '\n' );
  37004. if ( prefixVertex.length > 0 ) {
  37005. prefixVertex += '\n';
  37006. }
  37007. prefixFragment = [
  37008. '#define SHADER_TYPE ' + parameters.shaderType,
  37009. '#define SHADER_NAME ' + parameters.shaderName,
  37010. customDefines
  37011. ].filter( filterEmptyLine ).join( '\n' );
  37012. if ( prefixFragment.length > 0 ) {
  37013. prefixFragment += '\n';
  37014. }
  37015. } else {
  37016. prefixVertex = [
  37017. generatePrecision( parameters ),
  37018. '#define SHADER_TYPE ' + parameters.shaderType,
  37019. '#define SHADER_NAME ' + parameters.shaderName,
  37020. customDefines,
  37021. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  37022. parameters.batching ? '#define USE_BATCHING' : '',
  37023. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  37024. parameters.instancing ? '#define USE_INSTANCING' : '',
  37025. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  37026. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  37027. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  37028. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  37029. parameters.map ? '#define USE_MAP' : '',
  37030. parameters.envMap ? '#define USE_ENVMAP' : '',
  37031. parameters.envMap ? '#define ' + envMapModeDefine : '',
  37032. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  37033. parameters.aoMap ? '#define USE_AOMAP' : '',
  37034. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  37035. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  37036. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  37037. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  37038. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  37039. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  37040. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  37041. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  37042. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  37043. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  37044. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  37045. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  37046. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  37047. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  37048. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  37049. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  37050. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  37051. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  37052. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  37053. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  37054. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  37055. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  37056. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  37057. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  37058. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  37059. //
  37060. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  37061. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  37062. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  37063. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  37064. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  37065. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  37066. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  37067. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  37068. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  37069. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  37070. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  37071. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  37072. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  37073. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  37074. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  37075. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  37076. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  37077. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  37078. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  37079. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  37080. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  37081. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  37082. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  37083. //
  37084. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  37085. parameters.vertexColors ? '#define USE_COLOR' : '',
  37086. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  37087. parameters.vertexUv1s ? '#define USE_UV1' : '',
  37088. parameters.vertexUv2s ? '#define USE_UV2' : '',
  37089. parameters.vertexUv3s ? '#define USE_UV3' : '',
  37090. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  37091. parameters.flatShading ? '#define FLAT_SHADED' : '',
  37092. parameters.skinning ? '#define USE_SKINNING' : '',
  37093. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  37094. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  37095. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  37096. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  37097. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  37098. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  37099. parameters.flipSided ? '#define FLIP_SIDED' : '',
  37100. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  37101. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  37102. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  37103. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  37104. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  37105. parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  37106. 'uniform mat4 modelMatrix;',
  37107. 'uniform mat4 modelViewMatrix;',
  37108. 'uniform mat4 projectionMatrix;',
  37109. 'uniform mat4 viewMatrix;',
  37110. 'uniform mat3 normalMatrix;',
  37111. 'uniform vec3 cameraPosition;',
  37112. 'uniform bool isOrthographic;',
  37113. '#ifdef USE_INSTANCING',
  37114. ' attribute mat4 instanceMatrix;',
  37115. '#endif',
  37116. '#ifdef USE_INSTANCING_COLOR',
  37117. ' attribute vec3 instanceColor;',
  37118. '#endif',
  37119. '#ifdef USE_INSTANCING_MORPH',
  37120. ' uniform sampler2D morphTexture;',
  37121. '#endif',
  37122. 'attribute vec3 position;',
  37123. 'attribute vec3 normal;',
  37124. 'attribute vec2 uv;',
  37125. '#ifdef USE_UV1',
  37126. ' attribute vec2 uv1;',
  37127. '#endif',
  37128. '#ifdef USE_UV2',
  37129. ' attribute vec2 uv2;',
  37130. '#endif',
  37131. '#ifdef USE_UV3',
  37132. ' attribute vec2 uv3;',
  37133. '#endif',
  37134. '#ifdef USE_TANGENT',
  37135. ' attribute vec4 tangent;',
  37136. '#endif',
  37137. '#if defined( USE_COLOR_ALPHA )',
  37138. ' attribute vec4 color;',
  37139. '#elif defined( USE_COLOR )',
  37140. ' attribute vec3 color;',
  37141. '#endif',
  37142. '#ifdef USE_SKINNING',
  37143. ' attribute vec4 skinIndex;',
  37144. ' attribute vec4 skinWeight;',
  37145. '#endif',
  37146. '\n'
  37147. ].filter( filterEmptyLine ).join( '\n' );
  37148. prefixFragment = [
  37149. generatePrecision( parameters ),
  37150. '#define SHADER_TYPE ' + parameters.shaderType,
  37151. '#define SHADER_NAME ' + parameters.shaderName,
  37152. customDefines,
  37153. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  37154. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  37155. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  37156. parameters.map ? '#define USE_MAP' : '',
  37157. parameters.matcap ? '#define USE_MATCAP' : '',
  37158. parameters.envMap ? '#define USE_ENVMAP' : '',
  37159. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  37160. parameters.envMap ? '#define ' + envMapModeDefine : '',
  37161. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  37162. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  37163. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  37164. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  37165. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  37166. parameters.aoMap ? '#define USE_AOMAP' : '',
  37167. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  37168. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  37169. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  37170. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  37171. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  37172. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  37173. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  37174. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  37175. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  37176. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  37177. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  37178. parameters.dispersion ? '#define USE_DISPERSION' : '',
  37179. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  37180. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  37181. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  37182. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  37183. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  37184. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  37185. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  37186. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  37187. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  37188. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  37189. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  37190. parameters.sheen ? '#define USE_SHEEN' : '',
  37191. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  37192. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  37193. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  37194. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  37195. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  37196. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  37197. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  37198. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  37199. parameters.vertexUv1s ? '#define USE_UV1' : '',
  37200. parameters.vertexUv2s ? '#define USE_UV2' : '',
  37201. parameters.vertexUv3s ? '#define USE_UV3' : '',
  37202. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  37203. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  37204. parameters.flatShading ? '#define FLAT_SHADED' : '',
  37205. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  37206. parameters.flipSided ? '#define FLIP_SIDED' : '',
  37207. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  37208. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  37209. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  37210. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  37211. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  37212. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  37213. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  37214. parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  37215. 'uniform mat4 viewMatrix;',
  37216. 'uniform vec3 cameraPosition;',
  37217. 'uniform bool isOrthographic;',
  37218. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  37219. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  37220. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  37221. parameters.dithering ? '#define DITHERING' : '',
  37222. parameters.opaque ? '#define OPAQUE' : '',
  37223. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  37224. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  37225. getLuminanceFunction(),
  37226. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  37227. '\n'
  37228. ].filter( filterEmptyLine ).join( '\n' );
  37229. }
  37230. vertexShader = resolveIncludes( vertexShader );
  37231. vertexShader = replaceLightNums( vertexShader, parameters );
  37232. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  37233. fragmentShader = resolveIncludes( fragmentShader );
  37234. fragmentShader = replaceLightNums( fragmentShader, parameters );
  37235. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  37236. vertexShader = unrollLoops( vertexShader );
  37237. fragmentShader = unrollLoops( fragmentShader );
  37238. if ( parameters.isRawShaderMaterial !== true ) {
  37239. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  37240. versionString = '#version 300 es\n';
  37241. prefixVertex = [
  37242. customVertexExtensions,
  37243. '#define attribute in',
  37244. '#define varying out',
  37245. '#define texture2D texture'
  37246. ].join( '\n' ) + '\n' + prefixVertex;
  37247. prefixFragment = [
  37248. '#define varying in',
  37249. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  37250. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  37251. '#define gl_FragDepthEXT gl_FragDepth',
  37252. '#define texture2D texture',
  37253. '#define textureCube texture',
  37254. '#define texture2DProj textureProj',
  37255. '#define texture2DLodEXT textureLod',
  37256. '#define texture2DProjLodEXT textureProjLod',
  37257. '#define textureCubeLodEXT textureLod',
  37258. '#define texture2DGradEXT textureGrad',
  37259. '#define texture2DProjGradEXT textureProjGrad',
  37260. '#define textureCubeGradEXT textureGrad'
  37261. ].join( '\n' ) + '\n' + prefixFragment;
  37262. }
  37263. const vertexGlsl = versionString + prefixVertex + vertexShader;
  37264. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  37265. // console.log( '*VERTEX*', vertexGlsl );
  37266. // console.log( '*FRAGMENT*', fragmentGlsl );
  37267. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  37268. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  37269. gl.attachShader( program, glVertexShader );
  37270. gl.attachShader( program, glFragmentShader );
  37271. // Force a particular attribute to index 0.
  37272. if ( parameters.index0AttributeName !== undefined ) {
  37273. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  37274. } else if ( parameters.morphTargets === true ) {
  37275. // programs with morphTargets displace position out of attribute 0
  37276. gl.bindAttribLocation( program, 0, 'position' );
  37277. }
  37278. gl.linkProgram( program );
  37279. function onFirstUse( self ) {
  37280. // check for link errors
  37281. if ( renderer.debug.checkShaderErrors ) {
  37282. const programLog = gl.getProgramInfoLog( program ).trim();
  37283. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  37284. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  37285. let runnable = true;
  37286. let haveDiagnostics = true;
  37287. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  37288. runnable = false;
  37289. if ( typeof renderer.debug.onShaderError === 'function' ) {
  37290. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  37291. } else {
  37292. // default error reporting
  37293. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  37294. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  37295. console.error(
  37296. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  37297. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  37298. 'Material Name: ' + self.name + '\n' +
  37299. 'Material Type: ' + self.type + '\n\n' +
  37300. 'Program Info Log: ' + programLog + '\n' +
  37301. vertexErrors + '\n' +
  37302. fragmentErrors
  37303. );
  37304. }
  37305. } else if ( programLog !== '' ) {
  37306. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  37307. } else if ( vertexLog === '' || fragmentLog === '' ) {
  37308. haveDiagnostics = false;
  37309. }
  37310. if ( haveDiagnostics ) {
  37311. self.diagnostics = {
  37312. runnable: runnable,
  37313. programLog: programLog,
  37314. vertexShader: {
  37315. log: vertexLog,
  37316. prefix: prefixVertex
  37317. },
  37318. fragmentShader: {
  37319. log: fragmentLog,
  37320. prefix: prefixFragment
  37321. }
  37322. };
  37323. }
  37324. }
  37325. // Clean up
  37326. // Crashes in iOS9 and iOS10. #18402
  37327. // gl.detachShader( program, glVertexShader );
  37328. // gl.detachShader( program, glFragmentShader );
  37329. gl.deleteShader( glVertexShader );
  37330. gl.deleteShader( glFragmentShader );
  37331. cachedUniforms = new WebGLUniforms( gl, program );
  37332. cachedAttributes = fetchAttributeLocations( gl, program );
  37333. }
  37334. // set up caching for uniform locations
  37335. let cachedUniforms;
  37336. this.getUniforms = function () {
  37337. if ( cachedUniforms === undefined ) {
  37338. // Populates cachedUniforms and cachedAttributes
  37339. onFirstUse( this );
  37340. }
  37341. return cachedUniforms;
  37342. };
  37343. // set up caching for attribute locations
  37344. let cachedAttributes;
  37345. this.getAttributes = function () {
  37346. if ( cachedAttributes === undefined ) {
  37347. // Populates cachedAttributes and cachedUniforms
  37348. onFirstUse( this );
  37349. }
  37350. return cachedAttributes;
  37351. };
  37352. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  37353. // flag the program as ready immediately. It may cause a stall when it's first used.
  37354. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  37355. this.isReady = function () {
  37356. if ( programReady === false ) {
  37357. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  37358. }
  37359. return programReady;
  37360. };
  37361. // free resource
  37362. this.destroy = function () {
  37363. bindingStates.releaseStatesOfProgram( this );
  37364. gl.deleteProgram( program );
  37365. this.program = undefined;
  37366. };
  37367. //
  37368. this.type = parameters.shaderType;
  37369. this.name = parameters.shaderName;
  37370. this.id = programIdCount ++;
  37371. this.cacheKey = cacheKey;
  37372. this.usedTimes = 1;
  37373. this.program = program;
  37374. this.vertexShader = glVertexShader;
  37375. this.fragmentShader = glFragmentShader;
  37376. return this;
  37377. }
  37378. let _id = 0;
  37379. class WebGLShaderCache {
  37380. constructor() {
  37381. this.shaderCache = new Map();
  37382. this.materialCache = new Map();
  37383. }
  37384. update( material ) {
  37385. const vertexShader = material.vertexShader;
  37386. const fragmentShader = material.fragmentShader;
  37387. const vertexShaderStage = this._getShaderStage( vertexShader );
  37388. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  37389. const materialShaders = this._getShaderCacheForMaterial( material );
  37390. if ( materialShaders.has( vertexShaderStage ) === false ) {
  37391. materialShaders.add( vertexShaderStage );
  37392. vertexShaderStage.usedTimes ++;
  37393. }
  37394. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  37395. materialShaders.add( fragmentShaderStage );
  37396. fragmentShaderStage.usedTimes ++;
  37397. }
  37398. return this;
  37399. }
  37400. remove( material ) {
  37401. const materialShaders = this.materialCache.get( material );
  37402. for ( const shaderStage of materialShaders ) {
  37403. shaderStage.usedTimes --;
  37404. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  37405. }
  37406. this.materialCache.delete( material );
  37407. return this;
  37408. }
  37409. getVertexShaderID( material ) {
  37410. return this._getShaderStage( material.vertexShader ).id;
  37411. }
  37412. getFragmentShaderID( material ) {
  37413. return this._getShaderStage( material.fragmentShader ).id;
  37414. }
  37415. dispose() {
  37416. this.shaderCache.clear();
  37417. this.materialCache.clear();
  37418. }
  37419. _getShaderCacheForMaterial( material ) {
  37420. const cache = this.materialCache;
  37421. let set = cache.get( material );
  37422. if ( set === undefined ) {
  37423. set = new Set();
  37424. cache.set( material, set );
  37425. }
  37426. return set;
  37427. }
  37428. _getShaderStage( code ) {
  37429. const cache = this.shaderCache;
  37430. let stage = cache.get( code );
  37431. if ( stage === undefined ) {
  37432. stage = new WebGLShaderStage( code );
  37433. cache.set( code, stage );
  37434. }
  37435. return stage;
  37436. }
  37437. }
  37438. class WebGLShaderStage {
  37439. constructor( code ) {
  37440. this.id = _id ++;
  37441. this.code = code;
  37442. this.usedTimes = 0;
  37443. }
  37444. }
  37445. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  37446. const _programLayers = new Layers();
  37447. const _customShaders = new WebGLShaderCache();
  37448. const _activeChannels = new Set();
  37449. const programs = [];
  37450. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  37451. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  37452. let precision = capabilities.precision;
  37453. const shaderIDs = {
  37454. MeshDepthMaterial: 'depth',
  37455. MeshDistanceMaterial: 'distanceRGBA',
  37456. MeshNormalMaterial: 'normal',
  37457. MeshBasicMaterial: 'basic',
  37458. MeshLambertMaterial: 'lambert',
  37459. MeshPhongMaterial: 'phong',
  37460. MeshToonMaterial: 'toon',
  37461. MeshStandardMaterial: 'physical',
  37462. MeshPhysicalMaterial: 'physical',
  37463. MeshMatcapMaterial: 'matcap',
  37464. LineBasicMaterial: 'basic',
  37465. LineDashedMaterial: 'dashed',
  37466. PointsMaterial: 'points',
  37467. ShadowMaterial: 'shadow',
  37468. SpriteMaterial: 'sprite'
  37469. };
  37470. function getChannel( value ) {
  37471. _activeChannels.add( value );
  37472. if ( value === 0 ) return 'uv';
  37473. return `uv${ value }`;
  37474. }
  37475. function getParameters( material, lights, shadows, scene, object ) {
  37476. const fog = scene.fog;
  37477. const geometry = object.geometry;
  37478. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  37479. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  37480. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  37481. const shaderID = shaderIDs[ material.type ];
  37482. // heuristics to create shader parameters according to lights in the scene
  37483. // (not to blow over maxLights budget)
  37484. if ( material.precision !== null ) {
  37485. precision = capabilities.getMaxPrecision( material.precision );
  37486. if ( precision !== material.precision ) {
  37487. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  37488. }
  37489. }
  37490. //
  37491. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  37492. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  37493. let morphTextureStride = 0;
  37494. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  37495. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  37496. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  37497. //
  37498. let vertexShader, fragmentShader;
  37499. let customVertexShaderID, customFragmentShaderID;
  37500. if ( shaderID ) {
  37501. const shader = ShaderLib[ shaderID ];
  37502. vertexShader = shader.vertexShader;
  37503. fragmentShader = shader.fragmentShader;
  37504. } else {
  37505. vertexShader = material.vertexShader;
  37506. fragmentShader = material.fragmentShader;
  37507. _customShaders.update( material );
  37508. customVertexShaderID = _customShaders.getVertexShaderID( material );
  37509. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  37510. }
  37511. const currentRenderTarget = renderer.getRenderTarget();
  37512. const reverseDepthBuffer = renderer.state.buffers.depth.getReversed();
  37513. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  37514. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  37515. const HAS_MAP = !! material.map;
  37516. const HAS_MATCAP = !! material.matcap;
  37517. const HAS_ENVMAP = !! envMap;
  37518. const HAS_AOMAP = !! material.aoMap;
  37519. const HAS_LIGHTMAP = !! material.lightMap;
  37520. const HAS_BUMPMAP = !! material.bumpMap;
  37521. const HAS_NORMALMAP = !! material.normalMap;
  37522. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  37523. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  37524. const HAS_METALNESSMAP = !! material.metalnessMap;
  37525. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  37526. const HAS_ANISOTROPY = material.anisotropy > 0;
  37527. const HAS_CLEARCOAT = material.clearcoat > 0;
  37528. const HAS_DISPERSION = material.dispersion > 0;
  37529. const HAS_IRIDESCENCE = material.iridescence > 0;
  37530. const HAS_SHEEN = material.sheen > 0;
  37531. const HAS_TRANSMISSION = material.transmission > 0;
  37532. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  37533. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  37534. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  37535. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  37536. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  37537. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  37538. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  37539. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  37540. const HAS_SPECULARMAP = !! material.specularMap;
  37541. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  37542. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  37543. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  37544. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  37545. const HAS_GRADIENTMAP = !! material.gradientMap;
  37546. const HAS_ALPHAMAP = !! material.alphaMap;
  37547. const HAS_ALPHATEST = material.alphaTest > 0;
  37548. const HAS_ALPHAHASH = !! material.alphaHash;
  37549. const HAS_EXTENSIONS = !! material.extensions;
  37550. let toneMapping = NoToneMapping;
  37551. if ( material.toneMapped ) {
  37552. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  37553. toneMapping = renderer.toneMapping;
  37554. }
  37555. }
  37556. const parameters = {
  37557. shaderID: shaderID,
  37558. shaderType: material.type,
  37559. shaderName: material.name,
  37560. vertexShader: vertexShader,
  37561. fragmentShader: fragmentShader,
  37562. defines: material.defines,
  37563. customVertexShaderID: customVertexShaderID,
  37564. customFragmentShaderID: customFragmentShaderID,
  37565. isRawShaderMaterial: material.isRawShaderMaterial === true,
  37566. glslVersion: material.glslVersion,
  37567. precision: precision,
  37568. batching: IS_BATCHEDMESH,
  37569. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  37570. instancing: IS_INSTANCEDMESH,
  37571. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  37572. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  37573. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  37574. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  37575. alphaToCoverage: !! material.alphaToCoverage,
  37576. map: HAS_MAP,
  37577. matcap: HAS_MATCAP,
  37578. envMap: HAS_ENVMAP,
  37579. envMapMode: HAS_ENVMAP && envMap.mapping,
  37580. envMapCubeUVHeight: envMapCubeUVHeight,
  37581. aoMap: HAS_AOMAP,
  37582. lightMap: HAS_LIGHTMAP,
  37583. bumpMap: HAS_BUMPMAP,
  37584. normalMap: HAS_NORMALMAP,
  37585. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  37586. emissiveMap: HAS_EMISSIVEMAP,
  37587. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  37588. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  37589. metalnessMap: HAS_METALNESSMAP,
  37590. roughnessMap: HAS_ROUGHNESSMAP,
  37591. anisotropy: HAS_ANISOTROPY,
  37592. anisotropyMap: HAS_ANISOTROPYMAP,
  37593. clearcoat: HAS_CLEARCOAT,
  37594. clearcoatMap: HAS_CLEARCOATMAP,
  37595. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  37596. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  37597. dispersion: HAS_DISPERSION,
  37598. iridescence: HAS_IRIDESCENCE,
  37599. iridescenceMap: HAS_IRIDESCENCEMAP,
  37600. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  37601. sheen: HAS_SHEEN,
  37602. sheenColorMap: HAS_SHEEN_COLORMAP,
  37603. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  37604. specularMap: HAS_SPECULARMAP,
  37605. specularColorMap: HAS_SPECULAR_COLORMAP,
  37606. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  37607. transmission: HAS_TRANSMISSION,
  37608. transmissionMap: HAS_TRANSMISSIONMAP,
  37609. thicknessMap: HAS_THICKNESSMAP,
  37610. gradientMap: HAS_GRADIENTMAP,
  37611. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  37612. alphaMap: HAS_ALPHAMAP,
  37613. alphaTest: HAS_ALPHATEST,
  37614. alphaHash: HAS_ALPHAHASH,
  37615. combine: material.combine,
  37616. //
  37617. mapUv: HAS_MAP && getChannel( material.map.channel ),
  37618. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  37619. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  37620. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  37621. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  37622. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  37623. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  37624. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  37625. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  37626. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  37627. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  37628. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  37629. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  37630. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  37631. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  37632. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  37633. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  37634. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  37635. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  37636. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  37637. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  37638. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  37639. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  37640. //
  37641. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  37642. vertexColors: material.vertexColors,
  37643. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  37644. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  37645. fog: !! fog,
  37646. useFog: material.fog === true,
  37647. fogExp2: ( !! fog && fog.isFogExp2 ),
  37648. flatShading: material.flatShading === true,
  37649. sizeAttenuation: material.sizeAttenuation === true,
  37650. logarithmicDepthBuffer: logarithmicDepthBuffer,
  37651. reverseDepthBuffer: reverseDepthBuffer,
  37652. skinning: object.isSkinnedMesh === true,
  37653. morphTargets: geometry.morphAttributes.position !== undefined,
  37654. morphNormals: geometry.morphAttributes.normal !== undefined,
  37655. morphColors: geometry.morphAttributes.color !== undefined,
  37656. morphTargetsCount: morphTargetsCount,
  37657. morphTextureStride: morphTextureStride,
  37658. numDirLights: lights.directional.length,
  37659. numPointLights: lights.point.length,
  37660. numSpotLights: lights.spot.length,
  37661. numSpotLightMaps: lights.spotLightMap.length,
  37662. numRectAreaLights: lights.rectArea.length,
  37663. numHemiLights: lights.hemi.length,
  37664. numDirLightShadows: lights.directionalShadowMap.length,
  37665. numPointLightShadows: lights.pointShadowMap.length,
  37666. numSpotLightShadows: lights.spotShadowMap.length,
  37667. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  37668. numLightProbes: lights.numLightProbes,
  37669. numClippingPlanes: clipping.numPlanes,
  37670. numClipIntersection: clipping.numIntersection,
  37671. dithering: material.dithering,
  37672. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  37673. shadowMapType: renderer.shadowMap.type,
  37674. toneMapping: toneMapping,
  37675. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  37676. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  37677. premultipliedAlpha: material.premultipliedAlpha,
  37678. doubleSided: material.side === DoubleSide,
  37679. flipSided: material.side === BackSide,
  37680. useDepthPacking: material.depthPacking >= 0,
  37681. depthPacking: material.depthPacking || 0,
  37682. index0AttributeName: material.index0AttributeName,
  37683. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  37684. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  37685. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  37686. customProgramCacheKey: material.customProgramCacheKey()
  37687. };
  37688. // the usage of getChannel() determines the active texture channels for this shader
  37689. parameters.vertexUv1s = _activeChannels.has( 1 );
  37690. parameters.vertexUv2s = _activeChannels.has( 2 );
  37691. parameters.vertexUv3s = _activeChannels.has( 3 );
  37692. _activeChannels.clear();
  37693. return parameters;
  37694. }
  37695. function getProgramCacheKey( parameters ) {
  37696. const array = [];
  37697. if ( parameters.shaderID ) {
  37698. array.push( parameters.shaderID );
  37699. } else {
  37700. array.push( parameters.customVertexShaderID );
  37701. array.push( parameters.customFragmentShaderID );
  37702. }
  37703. if ( parameters.defines !== undefined ) {
  37704. for ( const name in parameters.defines ) {
  37705. array.push( name );
  37706. array.push( parameters.defines[ name ] );
  37707. }
  37708. }
  37709. if ( parameters.isRawShaderMaterial === false ) {
  37710. getProgramCacheKeyParameters( array, parameters );
  37711. getProgramCacheKeyBooleans( array, parameters );
  37712. array.push( renderer.outputColorSpace );
  37713. }
  37714. array.push( parameters.customProgramCacheKey );
  37715. return array.join();
  37716. }
  37717. function getProgramCacheKeyParameters( array, parameters ) {
  37718. array.push( parameters.precision );
  37719. array.push( parameters.outputColorSpace );
  37720. array.push( parameters.envMapMode );
  37721. array.push( parameters.envMapCubeUVHeight );
  37722. array.push( parameters.mapUv );
  37723. array.push( parameters.alphaMapUv );
  37724. array.push( parameters.lightMapUv );
  37725. array.push( parameters.aoMapUv );
  37726. array.push( parameters.bumpMapUv );
  37727. array.push( parameters.normalMapUv );
  37728. array.push( parameters.displacementMapUv );
  37729. array.push( parameters.emissiveMapUv );
  37730. array.push( parameters.metalnessMapUv );
  37731. array.push( parameters.roughnessMapUv );
  37732. array.push( parameters.anisotropyMapUv );
  37733. array.push( parameters.clearcoatMapUv );
  37734. array.push( parameters.clearcoatNormalMapUv );
  37735. array.push( parameters.clearcoatRoughnessMapUv );
  37736. array.push( parameters.iridescenceMapUv );
  37737. array.push( parameters.iridescenceThicknessMapUv );
  37738. array.push( parameters.sheenColorMapUv );
  37739. array.push( parameters.sheenRoughnessMapUv );
  37740. array.push( parameters.specularMapUv );
  37741. array.push( parameters.specularColorMapUv );
  37742. array.push( parameters.specularIntensityMapUv );
  37743. array.push( parameters.transmissionMapUv );
  37744. array.push( parameters.thicknessMapUv );
  37745. array.push( parameters.combine );
  37746. array.push( parameters.fogExp2 );
  37747. array.push( parameters.sizeAttenuation );
  37748. array.push( parameters.morphTargetsCount );
  37749. array.push( parameters.morphAttributeCount );
  37750. array.push( parameters.numDirLights );
  37751. array.push( parameters.numPointLights );
  37752. array.push( parameters.numSpotLights );
  37753. array.push( parameters.numSpotLightMaps );
  37754. array.push( parameters.numHemiLights );
  37755. array.push( parameters.numRectAreaLights );
  37756. array.push( parameters.numDirLightShadows );
  37757. array.push( parameters.numPointLightShadows );
  37758. array.push( parameters.numSpotLightShadows );
  37759. array.push( parameters.numSpotLightShadowsWithMaps );
  37760. array.push( parameters.numLightProbes );
  37761. array.push( parameters.shadowMapType );
  37762. array.push( parameters.toneMapping );
  37763. array.push( parameters.numClippingPlanes );
  37764. array.push( parameters.numClipIntersection );
  37765. array.push( parameters.depthPacking );
  37766. }
  37767. function getProgramCacheKeyBooleans( array, parameters ) {
  37768. _programLayers.disableAll();
  37769. if ( parameters.supportsVertexTextures )
  37770. _programLayers.enable( 0 );
  37771. if ( parameters.instancing )
  37772. _programLayers.enable( 1 );
  37773. if ( parameters.instancingColor )
  37774. _programLayers.enable( 2 );
  37775. if ( parameters.instancingMorph )
  37776. _programLayers.enable( 3 );
  37777. if ( parameters.matcap )
  37778. _programLayers.enable( 4 );
  37779. if ( parameters.envMap )
  37780. _programLayers.enable( 5 );
  37781. if ( parameters.normalMapObjectSpace )
  37782. _programLayers.enable( 6 );
  37783. if ( parameters.normalMapTangentSpace )
  37784. _programLayers.enable( 7 );
  37785. if ( parameters.clearcoat )
  37786. _programLayers.enable( 8 );
  37787. if ( parameters.iridescence )
  37788. _programLayers.enable( 9 );
  37789. if ( parameters.alphaTest )
  37790. _programLayers.enable( 10 );
  37791. if ( parameters.vertexColors )
  37792. _programLayers.enable( 11 );
  37793. if ( parameters.vertexAlphas )
  37794. _programLayers.enable( 12 );
  37795. if ( parameters.vertexUv1s )
  37796. _programLayers.enable( 13 );
  37797. if ( parameters.vertexUv2s )
  37798. _programLayers.enable( 14 );
  37799. if ( parameters.vertexUv3s )
  37800. _programLayers.enable( 15 );
  37801. if ( parameters.vertexTangents )
  37802. _programLayers.enable( 16 );
  37803. if ( parameters.anisotropy )
  37804. _programLayers.enable( 17 );
  37805. if ( parameters.alphaHash )
  37806. _programLayers.enable( 18 );
  37807. if ( parameters.batching )
  37808. _programLayers.enable( 19 );
  37809. if ( parameters.dispersion )
  37810. _programLayers.enable( 20 );
  37811. if ( parameters.batchingColor )
  37812. _programLayers.enable( 21 );
  37813. array.push( _programLayers.mask );
  37814. _programLayers.disableAll();
  37815. if ( parameters.fog )
  37816. _programLayers.enable( 0 );
  37817. if ( parameters.useFog )
  37818. _programLayers.enable( 1 );
  37819. if ( parameters.flatShading )
  37820. _programLayers.enable( 2 );
  37821. if ( parameters.logarithmicDepthBuffer )
  37822. _programLayers.enable( 3 );
  37823. if ( parameters.reverseDepthBuffer )
  37824. _programLayers.enable( 4 );
  37825. if ( parameters.skinning )
  37826. _programLayers.enable( 5 );
  37827. if ( parameters.morphTargets )
  37828. _programLayers.enable( 6 );
  37829. if ( parameters.morphNormals )
  37830. _programLayers.enable( 7 );
  37831. if ( parameters.morphColors )
  37832. _programLayers.enable( 8 );
  37833. if ( parameters.premultipliedAlpha )
  37834. _programLayers.enable( 9 );
  37835. if ( parameters.shadowMapEnabled )
  37836. _programLayers.enable( 10 );
  37837. if ( parameters.doubleSided )
  37838. _programLayers.enable( 11 );
  37839. if ( parameters.flipSided )
  37840. _programLayers.enable( 12 );
  37841. if ( parameters.useDepthPacking )
  37842. _programLayers.enable( 13 );
  37843. if ( parameters.dithering )
  37844. _programLayers.enable( 14 );
  37845. if ( parameters.transmission )
  37846. _programLayers.enable( 15 );
  37847. if ( parameters.sheen )
  37848. _programLayers.enable( 16 );
  37849. if ( parameters.opaque )
  37850. _programLayers.enable( 17 );
  37851. if ( parameters.pointsUvs )
  37852. _programLayers.enable( 18 );
  37853. if ( parameters.decodeVideoTexture )
  37854. _programLayers.enable( 19 );
  37855. if ( parameters.decodeVideoTextureEmissive )
  37856. _programLayers.enable( 20 );
  37857. if ( parameters.alphaToCoverage )
  37858. _programLayers.enable( 21 );
  37859. array.push( _programLayers.mask );
  37860. }
  37861. function getUniforms( material ) {
  37862. const shaderID = shaderIDs[ material.type ];
  37863. let uniforms;
  37864. if ( shaderID ) {
  37865. const shader = ShaderLib[ shaderID ];
  37866. uniforms = UniformsUtils.clone( shader.uniforms );
  37867. } else {
  37868. uniforms = material.uniforms;
  37869. }
  37870. return uniforms;
  37871. }
  37872. function acquireProgram( parameters, cacheKey ) {
  37873. let program;
  37874. // Check if code has been already compiled
  37875. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  37876. const preexistingProgram = programs[ p ];
  37877. if ( preexistingProgram.cacheKey === cacheKey ) {
  37878. program = preexistingProgram;
  37879. ++ program.usedTimes;
  37880. break;
  37881. }
  37882. }
  37883. if ( program === undefined ) {
  37884. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  37885. programs.push( program );
  37886. }
  37887. return program;
  37888. }
  37889. function releaseProgram( program ) {
  37890. if ( -- program.usedTimes === 0 ) {
  37891. // Remove from unordered set
  37892. const i = programs.indexOf( program );
  37893. programs[ i ] = programs[ programs.length - 1 ];
  37894. programs.pop();
  37895. // Free WebGL resources
  37896. program.destroy();
  37897. }
  37898. }
  37899. function releaseShaderCache( material ) {
  37900. _customShaders.remove( material );
  37901. }
  37902. function dispose() {
  37903. _customShaders.dispose();
  37904. }
  37905. return {
  37906. getParameters: getParameters,
  37907. getProgramCacheKey: getProgramCacheKey,
  37908. getUniforms: getUniforms,
  37909. acquireProgram: acquireProgram,
  37910. releaseProgram: releaseProgram,
  37911. releaseShaderCache: releaseShaderCache,
  37912. // Exposed for resource monitoring & error feedback via renderer.info:
  37913. programs: programs,
  37914. dispose: dispose
  37915. };
  37916. }
  37917. function WebGLProperties() {
  37918. let properties = new WeakMap();
  37919. function has( object ) {
  37920. return properties.has( object );
  37921. }
  37922. function get( object ) {
  37923. let map = properties.get( object );
  37924. if ( map === undefined ) {
  37925. map = {};
  37926. properties.set( object, map );
  37927. }
  37928. return map;
  37929. }
  37930. function remove( object ) {
  37931. properties.delete( object );
  37932. }
  37933. function update( object, key, value ) {
  37934. properties.get( object )[ key ] = value;
  37935. }
  37936. function dispose() {
  37937. properties = new WeakMap();
  37938. }
  37939. return {
  37940. has: has,
  37941. get: get,
  37942. remove: remove,
  37943. update: update,
  37944. dispose: dispose
  37945. };
  37946. }
  37947. function painterSortStable( a, b ) {
  37948. if ( a.groupOrder !== b.groupOrder ) {
  37949. return a.groupOrder - b.groupOrder;
  37950. } else if ( a.renderOrder !== b.renderOrder ) {
  37951. return a.renderOrder - b.renderOrder;
  37952. } else if ( a.material.id !== b.material.id ) {
  37953. return a.material.id - b.material.id;
  37954. } else if ( a.z !== b.z ) {
  37955. return a.z - b.z;
  37956. } else {
  37957. return a.id - b.id;
  37958. }
  37959. }
  37960. function reversePainterSortStable( a, b ) {
  37961. if ( a.groupOrder !== b.groupOrder ) {
  37962. return a.groupOrder - b.groupOrder;
  37963. } else if ( a.renderOrder !== b.renderOrder ) {
  37964. return a.renderOrder - b.renderOrder;
  37965. } else if ( a.z !== b.z ) {
  37966. return b.z - a.z;
  37967. } else {
  37968. return a.id - b.id;
  37969. }
  37970. }
  37971. function WebGLRenderList() {
  37972. const renderItems = [];
  37973. let renderItemsIndex = 0;
  37974. const opaque = [];
  37975. const transmissive = [];
  37976. const transparent = [];
  37977. function init() {
  37978. renderItemsIndex = 0;
  37979. opaque.length = 0;
  37980. transmissive.length = 0;
  37981. transparent.length = 0;
  37982. }
  37983. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  37984. let renderItem = renderItems[ renderItemsIndex ];
  37985. if ( renderItem === undefined ) {
  37986. renderItem = {
  37987. id: object.id,
  37988. object: object,
  37989. geometry: geometry,
  37990. material: material,
  37991. groupOrder: groupOrder,
  37992. renderOrder: object.renderOrder,
  37993. z: z,
  37994. group: group
  37995. };
  37996. renderItems[ renderItemsIndex ] = renderItem;
  37997. } else {
  37998. renderItem.id = object.id;
  37999. renderItem.object = object;
  38000. renderItem.geometry = geometry;
  38001. renderItem.material = material;
  38002. renderItem.groupOrder = groupOrder;
  38003. renderItem.renderOrder = object.renderOrder;
  38004. renderItem.z = z;
  38005. renderItem.group = group;
  38006. }
  38007. renderItemsIndex ++;
  38008. return renderItem;
  38009. }
  38010. function push( object, geometry, material, groupOrder, z, group ) {
  38011. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  38012. if ( material.transmission > 0.0 ) {
  38013. transmissive.push( renderItem );
  38014. } else if ( material.transparent === true ) {
  38015. transparent.push( renderItem );
  38016. } else {
  38017. opaque.push( renderItem );
  38018. }
  38019. }
  38020. function unshift( object, geometry, material, groupOrder, z, group ) {
  38021. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  38022. if ( material.transmission > 0.0 ) {
  38023. transmissive.unshift( renderItem );
  38024. } else if ( material.transparent === true ) {
  38025. transparent.unshift( renderItem );
  38026. } else {
  38027. opaque.unshift( renderItem );
  38028. }
  38029. }
  38030. function sort( customOpaqueSort, customTransparentSort ) {
  38031. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  38032. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  38033. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  38034. }
  38035. function finish() {
  38036. // Clear references from inactive renderItems in the list
  38037. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  38038. const renderItem = renderItems[ i ];
  38039. if ( renderItem.id === null ) break;
  38040. renderItem.id = null;
  38041. renderItem.object = null;
  38042. renderItem.geometry = null;
  38043. renderItem.material = null;
  38044. renderItem.group = null;
  38045. }
  38046. }
  38047. return {
  38048. opaque: opaque,
  38049. transmissive: transmissive,
  38050. transparent: transparent,
  38051. init: init,
  38052. push: push,
  38053. unshift: unshift,
  38054. finish: finish,
  38055. sort: sort
  38056. };
  38057. }
  38058. function WebGLRenderLists() {
  38059. let lists = new WeakMap();
  38060. function get( scene, renderCallDepth ) {
  38061. const listArray = lists.get( scene );
  38062. let list;
  38063. if ( listArray === undefined ) {
  38064. list = new WebGLRenderList();
  38065. lists.set( scene, [ list ] );
  38066. } else {
  38067. if ( renderCallDepth >= listArray.length ) {
  38068. list = new WebGLRenderList();
  38069. listArray.push( list );
  38070. } else {
  38071. list = listArray[ renderCallDepth ];
  38072. }
  38073. }
  38074. return list;
  38075. }
  38076. function dispose() {
  38077. lists = new WeakMap();
  38078. }
  38079. return {
  38080. get: get,
  38081. dispose: dispose
  38082. };
  38083. }
  38084. function UniformsCache() {
  38085. const lights = {};
  38086. return {
  38087. get: function ( light ) {
  38088. if ( lights[ light.id ] !== undefined ) {
  38089. return lights[ light.id ];
  38090. }
  38091. let uniforms;
  38092. switch ( light.type ) {
  38093. case 'DirectionalLight':
  38094. uniforms = {
  38095. direction: new Vector3(),
  38096. color: new Color()
  38097. };
  38098. break;
  38099. case 'SpotLight':
  38100. uniforms = {
  38101. position: new Vector3(),
  38102. direction: new Vector3(),
  38103. color: new Color(),
  38104. distance: 0,
  38105. coneCos: 0,
  38106. penumbraCos: 0,
  38107. decay: 0
  38108. };
  38109. break;
  38110. case 'PointLight':
  38111. uniforms = {
  38112. position: new Vector3(),
  38113. color: new Color(),
  38114. distance: 0,
  38115. decay: 0
  38116. };
  38117. break;
  38118. case 'HemisphereLight':
  38119. uniforms = {
  38120. direction: new Vector3(),
  38121. skyColor: new Color(),
  38122. groundColor: new Color()
  38123. };
  38124. break;
  38125. case 'RectAreaLight':
  38126. uniforms = {
  38127. color: new Color(),
  38128. position: new Vector3(),
  38129. halfWidth: new Vector3(),
  38130. halfHeight: new Vector3()
  38131. };
  38132. break;
  38133. }
  38134. lights[ light.id ] = uniforms;
  38135. return uniforms;
  38136. }
  38137. };
  38138. }
  38139. function ShadowUniformsCache() {
  38140. const lights = {};
  38141. return {
  38142. get: function ( light ) {
  38143. if ( lights[ light.id ] !== undefined ) {
  38144. return lights[ light.id ];
  38145. }
  38146. let uniforms;
  38147. switch ( light.type ) {
  38148. case 'DirectionalLight':
  38149. uniforms = {
  38150. shadowIntensity: 1,
  38151. shadowBias: 0,
  38152. shadowNormalBias: 0,
  38153. shadowRadius: 1,
  38154. shadowMapSize: new Vector2()
  38155. };
  38156. break;
  38157. case 'SpotLight':
  38158. uniforms = {
  38159. shadowIntensity: 1,
  38160. shadowBias: 0,
  38161. shadowNormalBias: 0,
  38162. shadowRadius: 1,
  38163. shadowMapSize: new Vector2()
  38164. };
  38165. break;
  38166. case 'PointLight':
  38167. uniforms = {
  38168. shadowIntensity: 1,
  38169. shadowBias: 0,
  38170. shadowNormalBias: 0,
  38171. shadowRadius: 1,
  38172. shadowMapSize: new Vector2(),
  38173. shadowCameraNear: 1,
  38174. shadowCameraFar: 1000
  38175. };
  38176. break;
  38177. // TODO (abelnation): set RectAreaLight shadow uniforms
  38178. }
  38179. lights[ light.id ] = uniforms;
  38180. return uniforms;
  38181. }
  38182. };
  38183. }
  38184. let nextVersion = 0;
  38185. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  38186. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  38187. }
  38188. function WebGLLights( extensions ) {
  38189. const cache = new UniformsCache();
  38190. const shadowCache = ShadowUniformsCache();
  38191. const state = {
  38192. version: 0,
  38193. hash: {
  38194. directionalLength: -1,
  38195. pointLength: -1,
  38196. spotLength: -1,
  38197. rectAreaLength: -1,
  38198. hemiLength: -1,
  38199. numDirectionalShadows: -1,
  38200. numPointShadows: -1,
  38201. numSpotShadows: -1,
  38202. numSpotMaps: -1,
  38203. numLightProbes: -1
  38204. },
  38205. ambient: [ 0, 0, 0 ],
  38206. probe: [],
  38207. directional: [],
  38208. directionalShadow: [],
  38209. directionalShadowMap: [],
  38210. directionalShadowMatrix: [],
  38211. spot: [],
  38212. spotLightMap: [],
  38213. spotShadow: [],
  38214. spotShadowMap: [],
  38215. spotLightMatrix: [],
  38216. rectArea: [],
  38217. rectAreaLTC1: null,
  38218. rectAreaLTC2: null,
  38219. point: [],
  38220. pointShadow: [],
  38221. pointShadowMap: [],
  38222. pointShadowMatrix: [],
  38223. hemi: [],
  38224. numSpotLightShadowsWithMaps: 0,
  38225. numLightProbes: 0
  38226. };
  38227. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  38228. const vector3 = new Vector3();
  38229. const matrix4 = new Matrix4();
  38230. const matrix42 = new Matrix4();
  38231. function setup( lights ) {
  38232. let r = 0, g = 0, b = 0;
  38233. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  38234. let directionalLength = 0;
  38235. let pointLength = 0;
  38236. let spotLength = 0;
  38237. let rectAreaLength = 0;
  38238. let hemiLength = 0;
  38239. let numDirectionalShadows = 0;
  38240. let numPointShadows = 0;
  38241. let numSpotShadows = 0;
  38242. let numSpotMaps = 0;
  38243. let numSpotShadowsWithMaps = 0;
  38244. let numLightProbes = 0;
  38245. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  38246. lights.sort( shadowCastingAndTexturingLightsFirst );
  38247. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  38248. const light = lights[ i ];
  38249. const color = light.color;
  38250. const intensity = light.intensity;
  38251. const distance = light.distance;
  38252. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  38253. if ( light.isAmbientLight ) {
  38254. r += color.r * intensity;
  38255. g += color.g * intensity;
  38256. b += color.b * intensity;
  38257. } else if ( light.isLightProbe ) {
  38258. for ( let j = 0; j < 9; j ++ ) {
  38259. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  38260. }
  38261. numLightProbes ++;
  38262. } else if ( light.isDirectionalLight ) {
  38263. const uniforms = cache.get( light );
  38264. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  38265. if ( light.castShadow ) {
  38266. const shadow = light.shadow;
  38267. const shadowUniforms = shadowCache.get( light );
  38268. shadowUniforms.shadowIntensity = shadow.intensity;
  38269. shadowUniforms.shadowBias = shadow.bias;
  38270. shadowUniforms.shadowNormalBias = shadow.normalBias;
  38271. shadowUniforms.shadowRadius = shadow.radius;
  38272. shadowUniforms.shadowMapSize = shadow.mapSize;
  38273. state.directionalShadow[ directionalLength ] = shadowUniforms;
  38274. state.directionalShadowMap[ directionalLength ] = shadowMap;
  38275. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  38276. numDirectionalShadows ++;
  38277. }
  38278. state.directional[ directionalLength ] = uniforms;
  38279. directionalLength ++;
  38280. } else if ( light.isSpotLight ) {
  38281. const uniforms = cache.get( light );
  38282. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  38283. uniforms.color.copy( color ).multiplyScalar( intensity );
  38284. uniforms.distance = distance;
  38285. uniforms.coneCos = Math.cos( light.angle );
  38286. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  38287. uniforms.decay = light.decay;
  38288. state.spot[ spotLength ] = uniforms;
  38289. const shadow = light.shadow;
  38290. if ( light.map ) {
  38291. state.spotLightMap[ numSpotMaps ] = light.map;
  38292. numSpotMaps ++;
  38293. // make sure the lightMatrix is up to date
  38294. // TODO : do it if required only
  38295. shadow.updateMatrices( light );
  38296. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  38297. }
  38298. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  38299. if ( light.castShadow ) {
  38300. const shadowUniforms = shadowCache.get( light );
  38301. shadowUniforms.shadowIntensity = shadow.intensity;
  38302. shadowUniforms.shadowBias = shadow.bias;
  38303. shadowUniforms.shadowNormalBias = shadow.normalBias;
  38304. shadowUniforms.shadowRadius = shadow.radius;
  38305. shadowUniforms.shadowMapSize = shadow.mapSize;
  38306. state.spotShadow[ spotLength ] = shadowUniforms;
  38307. state.spotShadowMap[ spotLength ] = shadowMap;
  38308. numSpotShadows ++;
  38309. }
  38310. spotLength ++;
  38311. } else if ( light.isRectAreaLight ) {
  38312. const uniforms = cache.get( light );
  38313. uniforms.color.copy( color ).multiplyScalar( intensity );
  38314. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  38315. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  38316. state.rectArea[ rectAreaLength ] = uniforms;
  38317. rectAreaLength ++;
  38318. } else if ( light.isPointLight ) {
  38319. const uniforms = cache.get( light );
  38320. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  38321. uniforms.distance = light.distance;
  38322. uniforms.decay = light.decay;
  38323. if ( light.castShadow ) {
  38324. const shadow = light.shadow;
  38325. const shadowUniforms = shadowCache.get( light );
  38326. shadowUniforms.shadowIntensity = shadow.intensity;
  38327. shadowUniforms.shadowBias = shadow.bias;
  38328. shadowUniforms.shadowNormalBias = shadow.normalBias;
  38329. shadowUniforms.shadowRadius = shadow.radius;
  38330. shadowUniforms.shadowMapSize = shadow.mapSize;
  38331. shadowUniforms.shadowCameraNear = shadow.camera.near;
  38332. shadowUniforms.shadowCameraFar = shadow.camera.far;
  38333. state.pointShadow[ pointLength ] = shadowUniforms;
  38334. state.pointShadowMap[ pointLength ] = shadowMap;
  38335. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  38336. numPointShadows ++;
  38337. }
  38338. state.point[ pointLength ] = uniforms;
  38339. pointLength ++;
  38340. } else if ( light.isHemisphereLight ) {
  38341. const uniforms = cache.get( light );
  38342. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  38343. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  38344. state.hemi[ hemiLength ] = uniforms;
  38345. hemiLength ++;
  38346. }
  38347. }
  38348. if ( rectAreaLength > 0 ) {
  38349. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  38350. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  38351. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  38352. } else {
  38353. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  38354. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  38355. }
  38356. }
  38357. state.ambient[ 0 ] = r;
  38358. state.ambient[ 1 ] = g;
  38359. state.ambient[ 2 ] = b;
  38360. const hash = state.hash;
  38361. if ( hash.directionalLength !== directionalLength ||
  38362. hash.pointLength !== pointLength ||
  38363. hash.spotLength !== spotLength ||
  38364. hash.rectAreaLength !== rectAreaLength ||
  38365. hash.hemiLength !== hemiLength ||
  38366. hash.numDirectionalShadows !== numDirectionalShadows ||
  38367. hash.numPointShadows !== numPointShadows ||
  38368. hash.numSpotShadows !== numSpotShadows ||
  38369. hash.numSpotMaps !== numSpotMaps ||
  38370. hash.numLightProbes !== numLightProbes ) {
  38371. state.directional.length = directionalLength;
  38372. state.spot.length = spotLength;
  38373. state.rectArea.length = rectAreaLength;
  38374. state.point.length = pointLength;
  38375. state.hemi.length = hemiLength;
  38376. state.directionalShadow.length = numDirectionalShadows;
  38377. state.directionalShadowMap.length = numDirectionalShadows;
  38378. state.pointShadow.length = numPointShadows;
  38379. state.pointShadowMap.length = numPointShadows;
  38380. state.spotShadow.length = numSpotShadows;
  38381. state.spotShadowMap.length = numSpotShadows;
  38382. state.directionalShadowMatrix.length = numDirectionalShadows;
  38383. state.pointShadowMatrix.length = numPointShadows;
  38384. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  38385. state.spotLightMap.length = numSpotMaps;
  38386. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  38387. state.numLightProbes = numLightProbes;
  38388. hash.directionalLength = directionalLength;
  38389. hash.pointLength = pointLength;
  38390. hash.spotLength = spotLength;
  38391. hash.rectAreaLength = rectAreaLength;
  38392. hash.hemiLength = hemiLength;
  38393. hash.numDirectionalShadows = numDirectionalShadows;
  38394. hash.numPointShadows = numPointShadows;
  38395. hash.numSpotShadows = numSpotShadows;
  38396. hash.numSpotMaps = numSpotMaps;
  38397. hash.numLightProbes = numLightProbes;
  38398. state.version = nextVersion ++;
  38399. }
  38400. }
  38401. function setupView( lights, camera ) {
  38402. let directionalLength = 0;
  38403. let pointLength = 0;
  38404. let spotLength = 0;
  38405. let rectAreaLength = 0;
  38406. let hemiLength = 0;
  38407. const viewMatrix = camera.matrixWorldInverse;
  38408. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  38409. const light = lights[ i ];
  38410. if ( light.isDirectionalLight ) {
  38411. const uniforms = state.directional[ directionalLength ];
  38412. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  38413. vector3.setFromMatrixPosition( light.target.matrixWorld );
  38414. uniforms.direction.sub( vector3 );
  38415. uniforms.direction.transformDirection( viewMatrix );
  38416. directionalLength ++;
  38417. } else if ( light.isSpotLight ) {
  38418. const uniforms = state.spot[ spotLength ];
  38419. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  38420. uniforms.position.applyMatrix4( viewMatrix );
  38421. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  38422. vector3.setFromMatrixPosition( light.target.matrixWorld );
  38423. uniforms.direction.sub( vector3 );
  38424. uniforms.direction.transformDirection( viewMatrix );
  38425. spotLength ++;
  38426. } else if ( light.isRectAreaLight ) {
  38427. const uniforms = state.rectArea[ rectAreaLength ];
  38428. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  38429. uniforms.position.applyMatrix4( viewMatrix );
  38430. // extract local rotation of light to derive width/height half vectors
  38431. matrix42.identity();
  38432. matrix4.copy( light.matrixWorld );
  38433. matrix4.premultiply( viewMatrix );
  38434. matrix42.extractRotation( matrix4 );
  38435. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  38436. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  38437. uniforms.halfWidth.applyMatrix4( matrix42 );
  38438. uniforms.halfHeight.applyMatrix4( matrix42 );
  38439. rectAreaLength ++;
  38440. } else if ( light.isPointLight ) {
  38441. const uniforms = state.point[ pointLength ];
  38442. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  38443. uniforms.position.applyMatrix4( viewMatrix );
  38444. pointLength ++;
  38445. } else if ( light.isHemisphereLight ) {
  38446. const uniforms = state.hemi[ hemiLength ];
  38447. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  38448. uniforms.direction.transformDirection( viewMatrix );
  38449. hemiLength ++;
  38450. }
  38451. }
  38452. }
  38453. return {
  38454. setup: setup,
  38455. setupView: setupView,
  38456. state: state
  38457. };
  38458. }
  38459. function WebGLRenderState( extensions ) {
  38460. const lights = new WebGLLights( extensions );
  38461. const lightsArray = [];
  38462. const shadowsArray = [];
  38463. function init( camera ) {
  38464. state.camera = camera;
  38465. lightsArray.length = 0;
  38466. shadowsArray.length = 0;
  38467. }
  38468. function pushLight( light ) {
  38469. lightsArray.push( light );
  38470. }
  38471. function pushShadow( shadowLight ) {
  38472. shadowsArray.push( shadowLight );
  38473. }
  38474. function setupLights() {
  38475. lights.setup( lightsArray );
  38476. }
  38477. function setupLightsView( camera ) {
  38478. lights.setupView( lightsArray, camera );
  38479. }
  38480. const state = {
  38481. lightsArray: lightsArray,
  38482. shadowsArray: shadowsArray,
  38483. camera: null,
  38484. lights: lights,
  38485. transmissionRenderTarget: {}
  38486. };
  38487. return {
  38488. init: init,
  38489. state: state,
  38490. setupLights: setupLights,
  38491. setupLightsView: setupLightsView,
  38492. pushLight: pushLight,
  38493. pushShadow: pushShadow
  38494. };
  38495. }
  38496. function WebGLRenderStates( extensions ) {
  38497. let renderStates = new WeakMap();
  38498. function get( scene, renderCallDepth = 0 ) {
  38499. const renderStateArray = renderStates.get( scene );
  38500. let renderState;
  38501. if ( renderStateArray === undefined ) {
  38502. renderState = new WebGLRenderState( extensions );
  38503. renderStates.set( scene, [ renderState ] );
  38504. } else {
  38505. if ( renderCallDepth >= renderStateArray.length ) {
  38506. renderState = new WebGLRenderState( extensions );
  38507. renderStateArray.push( renderState );
  38508. } else {
  38509. renderState = renderStateArray[ renderCallDepth ];
  38510. }
  38511. }
  38512. return renderState;
  38513. }
  38514. function dispose() {
  38515. renderStates = new WeakMap();
  38516. }
  38517. return {
  38518. get: get,
  38519. dispose: dispose
  38520. };
  38521. }
  38522. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  38523. 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}";
  38524. function WebGLShadowMap( renderer, objects, capabilities ) {
  38525. let _frustum = new Frustum();
  38526. const _shadowMapSize = new Vector2(),
  38527. _viewportSize = new Vector2(),
  38528. _viewport = new Vector4(),
  38529. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  38530. _distanceMaterial = new MeshDistanceMaterial(),
  38531. _materialCache = {},
  38532. _maxTextureSize = capabilities.maxTextureSize;
  38533. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  38534. const shadowMaterialVertical = new ShaderMaterial( {
  38535. defines: {
  38536. VSM_SAMPLES: 8
  38537. },
  38538. uniforms: {
  38539. shadow_pass: { value: null },
  38540. resolution: { value: new Vector2() },
  38541. radius: { value: 4.0 }
  38542. },
  38543. vertexShader: vertex,
  38544. fragmentShader: fragment
  38545. } );
  38546. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  38547. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  38548. const fullScreenTri = new BufferGeometry();
  38549. fullScreenTri.setAttribute(
  38550. 'position',
  38551. new BufferAttribute(
  38552. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  38553. 3
  38554. )
  38555. );
  38556. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  38557. const scope = this;
  38558. this.enabled = false;
  38559. this.autoUpdate = true;
  38560. this.needsUpdate = false;
  38561. this.type = PCFShadowMap;
  38562. let _previousType = this.type;
  38563. this.render = function ( lights, scene, camera ) {
  38564. if ( scope.enabled === false ) return;
  38565. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  38566. if ( lights.length === 0 ) return;
  38567. const currentRenderTarget = renderer.getRenderTarget();
  38568. const activeCubeFace = renderer.getActiveCubeFace();
  38569. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  38570. const _state = renderer.state;
  38571. // Set GL state for depth map.
  38572. _state.setBlending( NoBlending );
  38573. _state.buffers.color.setClear( 1, 1, 1, 1 );
  38574. _state.buffers.depth.setTest( true );
  38575. _state.setScissorTest( false );
  38576. // check for shadow map type changes
  38577. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  38578. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  38579. // render depth map
  38580. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  38581. const light = lights[ i ];
  38582. const shadow = light.shadow;
  38583. if ( shadow === undefined ) {
  38584. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  38585. continue;
  38586. }
  38587. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  38588. _shadowMapSize.copy( shadow.mapSize );
  38589. const shadowFrameExtents = shadow.getFrameExtents();
  38590. _shadowMapSize.multiply( shadowFrameExtents );
  38591. _viewportSize.copy( shadow.mapSize );
  38592. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  38593. if ( _shadowMapSize.x > _maxTextureSize ) {
  38594. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  38595. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  38596. shadow.mapSize.x = _viewportSize.x;
  38597. }
  38598. if ( _shadowMapSize.y > _maxTextureSize ) {
  38599. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  38600. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  38601. shadow.mapSize.y = _viewportSize.y;
  38602. }
  38603. }
  38604. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  38605. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  38606. if ( shadow.map !== null ) {
  38607. shadow.map.dispose();
  38608. }
  38609. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  38610. shadow.map.texture.name = light.name + '.shadowMap';
  38611. shadow.camera.updateProjectionMatrix();
  38612. }
  38613. renderer.setRenderTarget( shadow.map );
  38614. renderer.clear();
  38615. const viewportCount = shadow.getViewportCount();
  38616. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  38617. const viewport = shadow.getViewport( vp );
  38618. _viewport.set(
  38619. _viewportSize.x * viewport.x,
  38620. _viewportSize.y * viewport.y,
  38621. _viewportSize.x * viewport.z,
  38622. _viewportSize.y * viewport.w
  38623. );
  38624. _state.viewport( _viewport );
  38625. shadow.updateMatrices( light, vp );
  38626. _frustum = shadow.getFrustum();
  38627. renderObject( scene, camera, shadow.camera, light, this.type );
  38628. }
  38629. // do blur pass for VSM
  38630. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  38631. VSMPass( shadow, camera );
  38632. }
  38633. shadow.needsUpdate = false;
  38634. }
  38635. _previousType = this.type;
  38636. scope.needsUpdate = false;
  38637. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  38638. };
  38639. function VSMPass( shadow, camera ) {
  38640. const geometry = objects.update( fullScreenMesh );
  38641. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  38642. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  38643. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  38644. shadowMaterialVertical.needsUpdate = true;
  38645. shadowMaterialHorizontal.needsUpdate = true;
  38646. }
  38647. if ( shadow.mapPass === null ) {
  38648. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  38649. }
  38650. // vertical pass
  38651. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  38652. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  38653. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  38654. renderer.setRenderTarget( shadow.mapPass );
  38655. renderer.clear();
  38656. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  38657. // horizontal pass
  38658. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  38659. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  38660. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  38661. renderer.setRenderTarget( shadow.map );
  38662. renderer.clear();
  38663. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  38664. }
  38665. function getDepthMaterial( object, material, light, type ) {
  38666. let result = null;
  38667. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  38668. if ( customMaterial !== undefined ) {
  38669. result = customMaterial;
  38670. } else {
  38671. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  38672. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  38673. ( material.displacementMap && material.displacementScale !== 0 ) ||
  38674. ( material.alphaMap && material.alphaTest > 0 ) ||
  38675. ( material.map && material.alphaTest > 0 ) ) {
  38676. // in this case we need a unique material instance reflecting the
  38677. // appropriate state
  38678. const keyA = result.uuid, keyB = material.uuid;
  38679. let materialsForVariant = _materialCache[ keyA ];
  38680. if ( materialsForVariant === undefined ) {
  38681. materialsForVariant = {};
  38682. _materialCache[ keyA ] = materialsForVariant;
  38683. }
  38684. let cachedMaterial = materialsForVariant[ keyB ];
  38685. if ( cachedMaterial === undefined ) {
  38686. cachedMaterial = result.clone();
  38687. materialsForVariant[ keyB ] = cachedMaterial;
  38688. material.addEventListener( 'dispose', onMaterialDispose );
  38689. }
  38690. result = cachedMaterial;
  38691. }
  38692. }
  38693. result.visible = material.visible;
  38694. result.wireframe = material.wireframe;
  38695. if ( type === VSMShadowMap ) {
  38696. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  38697. } else {
  38698. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  38699. }
  38700. result.alphaMap = material.alphaMap;
  38701. result.alphaTest = material.alphaTest;
  38702. result.map = material.map;
  38703. result.clipShadows = material.clipShadows;
  38704. result.clippingPlanes = material.clippingPlanes;
  38705. result.clipIntersection = material.clipIntersection;
  38706. result.displacementMap = material.displacementMap;
  38707. result.displacementScale = material.displacementScale;
  38708. result.displacementBias = material.displacementBias;
  38709. result.wireframeLinewidth = material.wireframeLinewidth;
  38710. result.linewidth = material.linewidth;
  38711. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  38712. const materialProperties = renderer.properties.get( result );
  38713. materialProperties.light = light;
  38714. }
  38715. return result;
  38716. }
  38717. function renderObject( object, camera, shadowCamera, light, type ) {
  38718. if ( object.visible === false ) return;
  38719. const visible = object.layers.test( camera.layers );
  38720. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  38721. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  38722. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  38723. const geometry = objects.update( object );
  38724. const material = object.material;
  38725. if ( Array.isArray( material ) ) {
  38726. const groups = geometry.groups;
  38727. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  38728. const group = groups[ k ];
  38729. const groupMaterial = material[ group.materialIndex ];
  38730. if ( groupMaterial && groupMaterial.visible ) {
  38731. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  38732. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  38733. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  38734. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  38735. }
  38736. }
  38737. } else if ( material.visible ) {
  38738. const depthMaterial = getDepthMaterial( object, material, light, type );
  38739. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  38740. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  38741. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  38742. }
  38743. }
  38744. }
  38745. const children = object.children;
  38746. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38747. renderObject( children[ i ], camera, shadowCamera, light, type );
  38748. }
  38749. }
  38750. function onMaterialDispose( event ) {
  38751. const material = event.target;
  38752. material.removeEventListener( 'dispose', onMaterialDispose );
  38753. // make sure to remove the unique distance/depth materials used for shadow map rendering
  38754. for ( const id in _materialCache ) {
  38755. const cache = _materialCache[ id ];
  38756. const uuid = event.target.uuid;
  38757. if ( uuid in cache ) {
  38758. const shadowMaterial = cache[ uuid ];
  38759. shadowMaterial.dispose();
  38760. delete cache[ uuid ];
  38761. }
  38762. }
  38763. }
  38764. }
  38765. const reversedFuncs = {
  38766. [ NeverDepth ]: AlwaysDepth,
  38767. [ LessDepth ]: GreaterDepth,
  38768. [ EqualDepth ]: NotEqualDepth,
  38769. [ LessEqualDepth ]: GreaterEqualDepth,
  38770. [ AlwaysDepth ]: NeverDepth,
  38771. [ GreaterDepth ]: LessDepth,
  38772. [ NotEqualDepth ]: EqualDepth,
  38773. [ GreaterEqualDepth ]: LessEqualDepth,
  38774. };
  38775. function WebGLState( gl, extensions ) {
  38776. function ColorBuffer() {
  38777. let locked = false;
  38778. const color = new Vector4();
  38779. let currentColorMask = null;
  38780. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  38781. return {
  38782. setMask: function ( colorMask ) {
  38783. if ( currentColorMask !== colorMask && ! locked ) {
  38784. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  38785. currentColorMask = colorMask;
  38786. }
  38787. },
  38788. setLocked: function ( lock ) {
  38789. locked = lock;
  38790. },
  38791. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  38792. if ( premultipliedAlpha === true ) {
  38793. r *= a; g *= a; b *= a;
  38794. }
  38795. color.set( r, g, b, a );
  38796. if ( currentColorClear.equals( color ) === false ) {
  38797. gl.clearColor( r, g, b, a );
  38798. currentColorClear.copy( color );
  38799. }
  38800. },
  38801. reset: function () {
  38802. locked = false;
  38803. currentColorMask = null;
  38804. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  38805. }
  38806. };
  38807. }
  38808. function DepthBuffer() {
  38809. let locked = false;
  38810. let reversed = false;
  38811. let currentDepthMask = null;
  38812. let currentDepthFunc = null;
  38813. let currentDepthClear = null;
  38814. return {
  38815. setReversed: function ( value ) {
  38816. if ( reversed !== value ) {
  38817. const ext = extensions.get( 'EXT_clip_control' );
  38818. if ( reversed ) {
  38819. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  38820. } else {
  38821. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  38822. }
  38823. const oldDepth = currentDepthClear;
  38824. currentDepthClear = null;
  38825. this.setClear( oldDepth );
  38826. }
  38827. reversed = value;
  38828. },
  38829. getReversed: function () {
  38830. return reversed;
  38831. },
  38832. setTest: function ( depthTest ) {
  38833. if ( depthTest ) {
  38834. enable( gl.DEPTH_TEST );
  38835. } else {
  38836. disable( gl.DEPTH_TEST );
  38837. }
  38838. },
  38839. setMask: function ( depthMask ) {
  38840. if ( currentDepthMask !== depthMask && ! locked ) {
  38841. gl.depthMask( depthMask );
  38842. currentDepthMask = depthMask;
  38843. }
  38844. },
  38845. setFunc: function ( depthFunc ) {
  38846. if ( reversed ) depthFunc = reversedFuncs[ depthFunc ];
  38847. if ( currentDepthFunc !== depthFunc ) {
  38848. switch ( depthFunc ) {
  38849. case NeverDepth:
  38850. gl.depthFunc( gl.NEVER );
  38851. break;
  38852. case AlwaysDepth:
  38853. gl.depthFunc( gl.ALWAYS );
  38854. break;
  38855. case LessDepth:
  38856. gl.depthFunc( gl.LESS );
  38857. break;
  38858. case LessEqualDepth:
  38859. gl.depthFunc( gl.LEQUAL );
  38860. break;
  38861. case EqualDepth:
  38862. gl.depthFunc( gl.EQUAL );
  38863. break;
  38864. case GreaterEqualDepth:
  38865. gl.depthFunc( gl.GEQUAL );
  38866. break;
  38867. case GreaterDepth:
  38868. gl.depthFunc( gl.GREATER );
  38869. break;
  38870. case NotEqualDepth:
  38871. gl.depthFunc( gl.NOTEQUAL );
  38872. break;
  38873. default:
  38874. gl.depthFunc( gl.LEQUAL );
  38875. }
  38876. currentDepthFunc = depthFunc;
  38877. }
  38878. },
  38879. setLocked: function ( lock ) {
  38880. locked = lock;
  38881. },
  38882. setClear: function ( depth ) {
  38883. if ( currentDepthClear !== depth ) {
  38884. if ( reversed ) {
  38885. depth = 1 - depth;
  38886. }
  38887. gl.clearDepth( depth );
  38888. currentDepthClear = depth;
  38889. }
  38890. },
  38891. reset: function () {
  38892. locked = false;
  38893. currentDepthMask = null;
  38894. currentDepthFunc = null;
  38895. currentDepthClear = null;
  38896. reversed = false;
  38897. }
  38898. };
  38899. }
  38900. function StencilBuffer() {
  38901. let locked = false;
  38902. let currentStencilMask = null;
  38903. let currentStencilFunc = null;
  38904. let currentStencilRef = null;
  38905. let currentStencilFuncMask = null;
  38906. let currentStencilFail = null;
  38907. let currentStencilZFail = null;
  38908. let currentStencilZPass = null;
  38909. let currentStencilClear = null;
  38910. return {
  38911. setTest: function ( stencilTest ) {
  38912. if ( ! locked ) {
  38913. if ( stencilTest ) {
  38914. enable( gl.STENCIL_TEST );
  38915. } else {
  38916. disable( gl.STENCIL_TEST );
  38917. }
  38918. }
  38919. },
  38920. setMask: function ( stencilMask ) {
  38921. if ( currentStencilMask !== stencilMask && ! locked ) {
  38922. gl.stencilMask( stencilMask );
  38923. currentStencilMask = stencilMask;
  38924. }
  38925. },
  38926. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  38927. if ( currentStencilFunc !== stencilFunc ||
  38928. currentStencilRef !== stencilRef ||
  38929. currentStencilFuncMask !== stencilMask ) {
  38930. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  38931. currentStencilFunc = stencilFunc;
  38932. currentStencilRef = stencilRef;
  38933. currentStencilFuncMask = stencilMask;
  38934. }
  38935. },
  38936. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  38937. if ( currentStencilFail !== stencilFail ||
  38938. currentStencilZFail !== stencilZFail ||
  38939. currentStencilZPass !== stencilZPass ) {
  38940. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  38941. currentStencilFail = stencilFail;
  38942. currentStencilZFail = stencilZFail;
  38943. currentStencilZPass = stencilZPass;
  38944. }
  38945. },
  38946. setLocked: function ( lock ) {
  38947. locked = lock;
  38948. },
  38949. setClear: function ( stencil ) {
  38950. if ( currentStencilClear !== stencil ) {
  38951. gl.clearStencil( stencil );
  38952. currentStencilClear = stencil;
  38953. }
  38954. },
  38955. reset: function () {
  38956. locked = false;
  38957. currentStencilMask = null;
  38958. currentStencilFunc = null;
  38959. currentStencilRef = null;
  38960. currentStencilFuncMask = null;
  38961. currentStencilFail = null;
  38962. currentStencilZFail = null;
  38963. currentStencilZPass = null;
  38964. currentStencilClear = null;
  38965. }
  38966. };
  38967. }
  38968. //
  38969. const colorBuffer = new ColorBuffer();
  38970. const depthBuffer = new DepthBuffer();
  38971. const stencilBuffer = new StencilBuffer();
  38972. const uboBindings = new WeakMap();
  38973. const uboProgramMap = new WeakMap();
  38974. let enabledCapabilities = {};
  38975. let currentBoundFramebuffers = {};
  38976. let currentDrawbuffers = new WeakMap();
  38977. let defaultDrawbuffers = [];
  38978. let currentProgram = null;
  38979. let currentBlendingEnabled = false;
  38980. let currentBlending = null;
  38981. let currentBlendEquation = null;
  38982. let currentBlendSrc = null;
  38983. let currentBlendDst = null;
  38984. let currentBlendEquationAlpha = null;
  38985. let currentBlendSrcAlpha = null;
  38986. let currentBlendDstAlpha = null;
  38987. let currentBlendColor = new Color( 0, 0, 0 );
  38988. let currentBlendAlpha = 0;
  38989. let currentPremultipledAlpha = false;
  38990. let currentFlipSided = null;
  38991. let currentCullFace = null;
  38992. let currentLineWidth = null;
  38993. let currentPolygonOffsetFactor = null;
  38994. let currentPolygonOffsetUnits = null;
  38995. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  38996. let lineWidthAvailable = false;
  38997. let version = 0;
  38998. const glVersion = gl.getParameter( gl.VERSION );
  38999. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  39000. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  39001. lineWidthAvailable = ( version >= 1.0 );
  39002. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  39003. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  39004. lineWidthAvailable = ( version >= 2.0 );
  39005. }
  39006. let currentTextureSlot = null;
  39007. let currentBoundTextures = {};
  39008. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  39009. const viewportParam = gl.getParameter( gl.VIEWPORT );
  39010. const currentScissor = new Vector4().fromArray( scissorParam );
  39011. const currentViewport = new Vector4().fromArray( viewportParam );
  39012. function createTexture( type, target, count, dimensions ) {
  39013. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  39014. const texture = gl.createTexture();
  39015. gl.bindTexture( type, texture );
  39016. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  39017. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  39018. for ( let i = 0; i < count; i ++ ) {
  39019. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  39020. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  39021. } else {
  39022. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  39023. }
  39024. }
  39025. return texture;
  39026. }
  39027. const emptyTextures = {};
  39028. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  39029. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  39030. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  39031. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  39032. // init
  39033. colorBuffer.setClear( 0, 0, 0, 1 );
  39034. depthBuffer.setClear( 1 );
  39035. stencilBuffer.setClear( 0 );
  39036. enable( gl.DEPTH_TEST );
  39037. depthBuffer.setFunc( LessEqualDepth );
  39038. setFlipSided( false );
  39039. setCullFace( CullFaceBack );
  39040. enable( gl.CULL_FACE );
  39041. setBlending( NoBlending );
  39042. //
  39043. function enable( id ) {
  39044. if ( enabledCapabilities[ id ] !== true ) {
  39045. gl.enable( id );
  39046. enabledCapabilities[ id ] = true;
  39047. }
  39048. }
  39049. function disable( id ) {
  39050. if ( enabledCapabilities[ id ] !== false ) {
  39051. gl.disable( id );
  39052. enabledCapabilities[ id ] = false;
  39053. }
  39054. }
  39055. function bindFramebuffer( target, framebuffer ) {
  39056. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39057. gl.bindFramebuffer( target, framebuffer );
  39058. currentBoundFramebuffers[ target ] = framebuffer;
  39059. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39060. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39061. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39062. }
  39063. if ( target === gl.FRAMEBUFFER ) {
  39064. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39065. }
  39066. return true;
  39067. }
  39068. return false;
  39069. }
  39070. function drawBuffers( renderTarget, framebuffer ) {
  39071. let drawBuffers = defaultDrawbuffers;
  39072. let needsUpdate = false;
  39073. if ( renderTarget ) {
  39074. drawBuffers = currentDrawbuffers.get( framebuffer );
  39075. if ( drawBuffers === undefined ) {
  39076. drawBuffers = [];
  39077. currentDrawbuffers.set( framebuffer, drawBuffers );
  39078. }
  39079. const textures = renderTarget.textures;
  39080. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39081. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39082. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39083. }
  39084. drawBuffers.length = textures.length;
  39085. needsUpdate = true;
  39086. }
  39087. } else {
  39088. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39089. drawBuffers[ 0 ] = gl.BACK;
  39090. needsUpdate = true;
  39091. }
  39092. }
  39093. if ( needsUpdate ) {
  39094. gl.drawBuffers( drawBuffers );
  39095. }
  39096. }
  39097. function useProgram( program ) {
  39098. if ( currentProgram !== program ) {
  39099. gl.useProgram( program );
  39100. currentProgram = program;
  39101. return true;
  39102. }
  39103. return false;
  39104. }
  39105. const equationToGL = {
  39106. [ AddEquation ]: gl.FUNC_ADD,
  39107. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  39108. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  39109. };
  39110. equationToGL[ MinEquation ] = gl.MIN;
  39111. equationToGL[ MaxEquation ] = gl.MAX;
  39112. const factorToGL = {
  39113. [ ZeroFactor ]: gl.ZERO,
  39114. [ OneFactor ]: gl.ONE,
  39115. [ SrcColorFactor ]: gl.SRC_COLOR,
  39116. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39117. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39118. [ DstColorFactor ]: gl.DST_COLOR,
  39119. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39120. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39121. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39122. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39123. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  39124. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  39125. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  39126. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  39127. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  39128. };
  39129. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  39130. if ( blending === NoBlending ) {
  39131. if ( currentBlendingEnabled === true ) {
  39132. disable( gl.BLEND );
  39133. currentBlendingEnabled = false;
  39134. }
  39135. return;
  39136. }
  39137. if ( currentBlendingEnabled === false ) {
  39138. enable( gl.BLEND );
  39139. currentBlendingEnabled = true;
  39140. }
  39141. if ( blending !== CustomBlending ) {
  39142. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  39143. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  39144. gl.blendEquation( gl.FUNC_ADD );
  39145. currentBlendEquation = AddEquation;
  39146. currentBlendEquationAlpha = AddEquation;
  39147. }
  39148. if ( premultipliedAlpha ) {
  39149. switch ( blending ) {
  39150. case NormalBlending:
  39151. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39152. break;
  39153. case AdditiveBlending:
  39154. gl.blendFunc( gl.ONE, gl.ONE );
  39155. break;
  39156. case SubtractiveBlending:
  39157. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39158. break;
  39159. case MultiplyBlending:
  39160. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39161. break;
  39162. default:
  39163. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39164. break;
  39165. }
  39166. } else {
  39167. switch ( blending ) {
  39168. case NormalBlending:
  39169. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39170. break;
  39171. case AdditiveBlending:
  39172. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  39173. break;
  39174. case SubtractiveBlending:
  39175. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39176. break;
  39177. case MultiplyBlending:
  39178. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  39179. break;
  39180. default:
  39181. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39182. break;
  39183. }
  39184. }
  39185. currentBlendSrc = null;
  39186. currentBlendDst = null;
  39187. currentBlendSrcAlpha = null;
  39188. currentBlendDstAlpha = null;
  39189. currentBlendColor.set( 0, 0, 0 );
  39190. currentBlendAlpha = 0;
  39191. currentBlending = blending;
  39192. currentPremultipledAlpha = premultipliedAlpha;
  39193. }
  39194. return;
  39195. }
  39196. // custom blending
  39197. blendEquationAlpha = blendEquationAlpha || blendEquation;
  39198. blendSrcAlpha = blendSrcAlpha || blendSrc;
  39199. blendDstAlpha = blendDstAlpha || blendDst;
  39200. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  39201. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  39202. currentBlendEquation = blendEquation;
  39203. currentBlendEquationAlpha = blendEquationAlpha;
  39204. }
  39205. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  39206. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  39207. currentBlendSrc = blendSrc;
  39208. currentBlendDst = blendDst;
  39209. currentBlendSrcAlpha = blendSrcAlpha;
  39210. currentBlendDstAlpha = blendDstAlpha;
  39211. }
  39212. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  39213. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  39214. currentBlendColor.copy( blendColor );
  39215. currentBlendAlpha = blendAlpha;
  39216. }
  39217. currentBlending = blending;
  39218. currentPremultipledAlpha = false;
  39219. }
  39220. function setMaterial( material, frontFaceCW ) {
  39221. material.side === DoubleSide
  39222. ? disable( gl.CULL_FACE )
  39223. : enable( gl.CULL_FACE );
  39224. let flipSided = ( material.side === BackSide );
  39225. if ( frontFaceCW ) flipSided = ! flipSided;
  39226. setFlipSided( flipSided );
  39227. ( material.blending === NormalBlending && material.transparent === false )
  39228. ? setBlending( NoBlending )
  39229. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  39230. depthBuffer.setFunc( material.depthFunc );
  39231. depthBuffer.setTest( material.depthTest );
  39232. depthBuffer.setMask( material.depthWrite );
  39233. colorBuffer.setMask( material.colorWrite );
  39234. const stencilWrite = material.stencilWrite;
  39235. stencilBuffer.setTest( stencilWrite );
  39236. if ( stencilWrite ) {
  39237. stencilBuffer.setMask( material.stencilWriteMask );
  39238. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39239. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39240. }
  39241. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39242. material.alphaToCoverage === true
  39243. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39244. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39245. }
  39246. //
  39247. function setFlipSided( flipSided ) {
  39248. if ( currentFlipSided !== flipSided ) {
  39249. if ( flipSided ) {
  39250. gl.frontFace( gl.CW );
  39251. } else {
  39252. gl.frontFace( gl.CCW );
  39253. }
  39254. currentFlipSided = flipSided;
  39255. }
  39256. }
  39257. function setCullFace( cullFace ) {
  39258. if ( cullFace !== CullFaceNone ) {
  39259. enable( gl.CULL_FACE );
  39260. if ( cullFace !== currentCullFace ) {
  39261. if ( cullFace === CullFaceBack ) {
  39262. gl.cullFace( gl.BACK );
  39263. } else if ( cullFace === CullFaceFront ) {
  39264. gl.cullFace( gl.FRONT );
  39265. } else {
  39266. gl.cullFace( gl.FRONT_AND_BACK );
  39267. }
  39268. }
  39269. } else {
  39270. disable( gl.CULL_FACE );
  39271. }
  39272. currentCullFace = cullFace;
  39273. }
  39274. function setLineWidth( width ) {
  39275. if ( width !== currentLineWidth ) {
  39276. if ( lineWidthAvailable ) gl.lineWidth( width );
  39277. currentLineWidth = width;
  39278. }
  39279. }
  39280. function setPolygonOffset( polygonOffset, factor, units ) {
  39281. if ( polygonOffset ) {
  39282. enable( gl.POLYGON_OFFSET_FILL );
  39283. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  39284. gl.polygonOffset( factor, units );
  39285. currentPolygonOffsetFactor = factor;
  39286. currentPolygonOffsetUnits = units;
  39287. }
  39288. } else {
  39289. disable( gl.POLYGON_OFFSET_FILL );
  39290. }
  39291. }
  39292. function setScissorTest( scissorTest ) {
  39293. if ( scissorTest ) {
  39294. enable( gl.SCISSOR_TEST );
  39295. } else {
  39296. disable( gl.SCISSOR_TEST );
  39297. }
  39298. }
  39299. // texture
  39300. function activeTexture( webglSlot ) {
  39301. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39302. if ( currentTextureSlot !== webglSlot ) {
  39303. gl.activeTexture( webglSlot );
  39304. currentTextureSlot = webglSlot;
  39305. }
  39306. }
  39307. function bindTexture( webglType, webglTexture, webglSlot ) {
  39308. if ( webglSlot === undefined ) {
  39309. if ( currentTextureSlot === null ) {
  39310. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39311. } else {
  39312. webglSlot = currentTextureSlot;
  39313. }
  39314. }
  39315. let boundTexture = currentBoundTextures[ webglSlot ];
  39316. if ( boundTexture === undefined ) {
  39317. boundTexture = { type: undefined, texture: undefined };
  39318. currentBoundTextures[ webglSlot ] = boundTexture;
  39319. }
  39320. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39321. if ( currentTextureSlot !== webglSlot ) {
  39322. gl.activeTexture( webglSlot );
  39323. currentTextureSlot = webglSlot;
  39324. }
  39325. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  39326. boundTexture.type = webglType;
  39327. boundTexture.texture = webglTexture;
  39328. }
  39329. }
  39330. function unbindTexture() {
  39331. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  39332. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  39333. gl.bindTexture( boundTexture.type, null );
  39334. boundTexture.type = undefined;
  39335. boundTexture.texture = undefined;
  39336. }
  39337. }
  39338. function compressedTexImage2D() {
  39339. try {
  39340. gl.compressedTexImage2D( ...arguments );
  39341. } catch ( error ) {
  39342. console.error( 'THREE.WebGLState:', error );
  39343. }
  39344. }
  39345. function compressedTexImage3D() {
  39346. try {
  39347. gl.compressedTexImage3D( ...arguments );
  39348. } catch ( error ) {
  39349. console.error( 'THREE.WebGLState:', error );
  39350. }
  39351. }
  39352. function texSubImage2D() {
  39353. try {
  39354. gl.texSubImage2D( ...arguments );
  39355. } catch ( error ) {
  39356. console.error( 'THREE.WebGLState:', error );
  39357. }
  39358. }
  39359. function texSubImage3D() {
  39360. try {
  39361. gl.texSubImage3D( ...arguments );
  39362. } catch ( error ) {
  39363. console.error( 'THREE.WebGLState:', error );
  39364. }
  39365. }
  39366. function compressedTexSubImage2D() {
  39367. try {
  39368. gl.compressedTexSubImage2D( ...arguments );
  39369. } catch ( error ) {
  39370. console.error( 'THREE.WebGLState:', error );
  39371. }
  39372. }
  39373. function compressedTexSubImage3D() {
  39374. try {
  39375. gl.compressedTexSubImage3D( ...arguments );
  39376. } catch ( error ) {
  39377. console.error( 'THREE.WebGLState:', error );
  39378. }
  39379. }
  39380. function texStorage2D() {
  39381. try {
  39382. gl.texStorage2D( ...arguments );
  39383. } catch ( error ) {
  39384. console.error( 'THREE.WebGLState:', error );
  39385. }
  39386. }
  39387. function texStorage3D() {
  39388. try {
  39389. gl.texStorage3D( ...arguments );
  39390. } catch ( error ) {
  39391. console.error( 'THREE.WebGLState:', error );
  39392. }
  39393. }
  39394. function texImage2D() {
  39395. try {
  39396. gl.texImage2D( ...arguments );
  39397. } catch ( error ) {
  39398. console.error( 'THREE.WebGLState:', error );
  39399. }
  39400. }
  39401. function texImage3D() {
  39402. try {
  39403. gl.texImage3D( ...arguments );
  39404. } catch ( error ) {
  39405. console.error( 'THREE.WebGLState:', error );
  39406. }
  39407. }
  39408. //
  39409. function scissor( scissor ) {
  39410. if ( currentScissor.equals( scissor ) === false ) {
  39411. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  39412. currentScissor.copy( scissor );
  39413. }
  39414. }
  39415. function viewport( viewport ) {
  39416. if ( currentViewport.equals( viewport ) === false ) {
  39417. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  39418. currentViewport.copy( viewport );
  39419. }
  39420. }
  39421. function updateUBOMapping( uniformsGroup, program ) {
  39422. let mapping = uboProgramMap.get( program );
  39423. if ( mapping === undefined ) {
  39424. mapping = new WeakMap();
  39425. uboProgramMap.set( program, mapping );
  39426. }
  39427. let blockIndex = mapping.get( uniformsGroup );
  39428. if ( blockIndex === undefined ) {
  39429. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  39430. mapping.set( uniformsGroup, blockIndex );
  39431. }
  39432. }
  39433. function uniformBlockBinding( uniformsGroup, program ) {
  39434. const mapping = uboProgramMap.get( program );
  39435. const blockIndex = mapping.get( uniformsGroup );
  39436. if ( uboBindings.get( program ) !== blockIndex ) {
  39437. // bind shader specific block index to global block point
  39438. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  39439. uboBindings.set( program, blockIndex );
  39440. }
  39441. }
  39442. //
  39443. function reset() {
  39444. // reset state
  39445. gl.disable( gl.BLEND );
  39446. gl.disable( gl.CULL_FACE );
  39447. gl.disable( gl.DEPTH_TEST );
  39448. gl.disable( gl.POLYGON_OFFSET_FILL );
  39449. gl.disable( gl.SCISSOR_TEST );
  39450. gl.disable( gl.STENCIL_TEST );
  39451. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39452. gl.blendEquation( gl.FUNC_ADD );
  39453. gl.blendFunc( gl.ONE, gl.ZERO );
  39454. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  39455. gl.blendColor( 0, 0, 0, 0 );
  39456. gl.colorMask( true, true, true, true );
  39457. gl.clearColor( 0, 0, 0, 0 );
  39458. gl.depthMask( true );
  39459. gl.depthFunc( gl.LESS );
  39460. depthBuffer.setReversed( false );
  39461. gl.clearDepth( 1 );
  39462. gl.stencilMask( 0xffffffff );
  39463. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  39464. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  39465. gl.clearStencil( 0 );
  39466. gl.cullFace( gl.BACK );
  39467. gl.frontFace( gl.CCW );
  39468. gl.polygonOffset( 0, 0 );
  39469. gl.activeTexture( gl.TEXTURE0 );
  39470. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39471. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  39472. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  39473. gl.useProgram( null );
  39474. gl.lineWidth( 1 );
  39475. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  39476. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  39477. // reset internals
  39478. enabledCapabilities = {};
  39479. currentTextureSlot = null;
  39480. currentBoundTextures = {};
  39481. currentBoundFramebuffers = {};
  39482. currentDrawbuffers = new WeakMap();
  39483. defaultDrawbuffers = [];
  39484. currentProgram = null;
  39485. currentBlendingEnabled = false;
  39486. currentBlending = null;
  39487. currentBlendEquation = null;
  39488. currentBlendSrc = null;
  39489. currentBlendDst = null;
  39490. currentBlendEquationAlpha = null;
  39491. currentBlendSrcAlpha = null;
  39492. currentBlendDstAlpha = null;
  39493. currentBlendColor = new Color( 0, 0, 0 );
  39494. currentBlendAlpha = 0;
  39495. currentPremultipledAlpha = false;
  39496. currentFlipSided = null;
  39497. currentCullFace = null;
  39498. currentLineWidth = null;
  39499. currentPolygonOffsetFactor = null;
  39500. currentPolygonOffsetUnits = null;
  39501. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  39502. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  39503. colorBuffer.reset();
  39504. depthBuffer.reset();
  39505. stencilBuffer.reset();
  39506. }
  39507. return {
  39508. buffers: {
  39509. color: colorBuffer,
  39510. depth: depthBuffer,
  39511. stencil: stencilBuffer
  39512. },
  39513. enable: enable,
  39514. disable: disable,
  39515. bindFramebuffer: bindFramebuffer,
  39516. drawBuffers: drawBuffers,
  39517. useProgram: useProgram,
  39518. setBlending: setBlending,
  39519. setMaterial: setMaterial,
  39520. setFlipSided: setFlipSided,
  39521. setCullFace: setCullFace,
  39522. setLineWidth: setLineWidth,
  39523. setPolygonOffset: setPolygonOffset,
  39524. setScissorTest: setScissorTest,
  39525. activeTexture: activeTexture,
  39526. bindTexture: bindTexture,
  39527. unbindTexture: unbindTexture,
  39528. compressedTexImage2D: compressedTexImage2D,
  39529. compressedTexImage3D: compressedTexImage3D,
  39530. texImage2D: texImage2D,
  39531. texImage3D: texImage3D,
  39532. updateUBOMapping: updateUBOMapping,
  39533. uniformBlockBinding: uniformBlockBinding,
  39534. texStorage2D: texStorage2D,
  39535. texStorage3D: texStorage3D,
  39536. texSubImage2D: texSubImage2D,
  39537. texSubImage3D: texSubImage3D,
  39538. compressedTexSubImage2D: compressedTexSubImage2D,
  39539. compressedTexSubImage3D: compressedTexSubImage3D,
  39540. scissor: scissor,
  39541. viewport: viewport,
  39542. reset: reset
  39543. };
  39544. }
  39545. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  39546. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  39547. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  39548. const _imageDimensions = new Vector2();
  39549. const _videoTextures = new WeakMap();
  39550. let _canvas;
  39551. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  39552. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  39553. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  39554. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  39555. let useOffscreenCanvas = false;
  39556. try {
  39557. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  39558. // eslint-disable-next-line compat/compat
  39559. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  39560. } catch ( err ) {
  39561. // Ignore any errors
  39562. }
  39563. function createCanvas( width, height ) {
  39564. // Use OffscreenCanvas when available. Specially needed in web workers
  39565. return useOffscreenCanvas ?
  39566. // eslint-disable-next-line compat/compat
  39567. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  39568. }
  39569. function resizeImage( image, needsNewCanvas, maxSize ) {
  39570. let scale = 1;
  39571. const dimensions = getDimensions( image );
  39572. // handle case if texture exceeds max size
  39573. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  39574. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  39575. }
  39576. // only perform resize if necessary
  39577. if ( scale < 1 ) {
  39578. // only perform resize for certain image types
  39579. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  39580. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  39581. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  39582. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  39583. const width = Math.floor( scale * dimensions.width );
  39584. const height = Math.floor( scale * dimensions.height );
  39585. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  39586. // cube textures can't reuse the same canvas
  39587. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  39588. canvas.width = width;
  39589. canvas.height = height;
  39590. const context = canvas.getContext( '2d' );
  39591. context.drawImage( image, 0, 0, width, height );
  39592. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  39593. return canvas;
  39594. } else {
  39595. if ( 'data' in image ) {
  39596. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  39597. }
  39598. return image;
  39599. }
  39600. }
  39601. return image;
  39602. }
  39603. function textureNeedsGenerateMipmaps( texture ) {
  39604. return texture.generateMipmaps;
  39605. }
  39606. function generateMipmap( target ) {
  39607. _gl.generateMipmap( target );
  39608. }
  39609. function getTargetType( texture ) {
  39610. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  39611. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  39612. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  39613. return _gl.TEXTURE_2D;
  39614. }
  39615. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  39616. if ( internalFormatName !== null ) {
  39617. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  39618. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  39619. }
  39620. let internalFormat = glFormat;
  39621. if ( glFormat === _gl.RED ) {
  39622. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  39623. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  39624. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  39625. }
  39626. if ( glFormat === _gl.RED_INTEGER ) {
  39627. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  39628. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  39629. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  39630. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  39631. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  39632. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  39633. }
  39634. if ( glFormat === _gl.RG ) {
  39635. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  39636. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  39637. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  39638. }
  39639. if ( glFormat === _gl.RG_INTEGER ) {
  39640. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  39641. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  39642. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  39643. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  39644. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  39645. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  39646. }
  39647. if ( glFormat === _gl.RGB_INTEGER ) {
  39648. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  39649. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  39650. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  39651. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  39652. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  39653. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  39654. }
  39655. if ( glFormat === _gl.RGBA_INTEGER ) {
  39656. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  39657. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  39658. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  39659. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  39660. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  39661. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  39662. }
  39663. if ( glFormat === _gl.RGB ) {
  39664. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  39665. }
  39666. if ( glFormat === _gl.RGBA ) {
  39667. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  39668. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  39669. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  39670. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  39671. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  39672. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  39673. }
  39674. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  39675. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  39676. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  39677. extensions.get( 'EXT_color_buffer_float' );
  39678. }
  39679. return internalFormat;
  39680. }
  39681. function getInternalDepthFormat( useStencil, depthType ) {
  39682. let glInternalFormat;
  39683. if ( useStencil ) {
  39684. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  39685. glInternalFormat = _gl.DEPTH24_STENCIL8;
  39686. } else if ( depthType === FloatType ) {
  39687. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  39688. } else if ( depthType === UnsignedShortType ) {
  39689. glInternalFormat = _gl.DEPTH24_STENCIL8;
  39690. console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  39691. }
  39692. } else {
  39693. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  39694. glInternalFormat = _gl.DEPTH_COMPONENT24;
  39695. } else if ( depthType === FloatType ) {
  39696. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  39697. } else if ( depthType === UnsignedShortType ) {
  39698. glInternalFormat = _gl.DEPTH_COMPONENT16;
  39699. }
  39700. }
  39701. return glInternalFormat;
  39702. }
  39703. function getMipLevels( texture, image ) {
  39704. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  39705. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  39706. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  39707. // user-defined mipmaps
  39708. return texture.mipmaps.length;
  39709. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  39710. return image.mipmaps.length;
  39711. } else {
  39712. // texture without mipmaps (only base level)
  39713. return 1;
  39714. }
  39715. }
  39716. //
  39717. function onTextureDispose( event ) {
  39718. const texture = event.target;
  39719. texture.removeEventListener( 'dispose', onTextureDispose );
  39720. deallocateTexture( texture );
  39721. if ( texture.isVideoTexture ) {
  39722. _videoTextures.delete( texture );
  39723. }
  39724. }
  39725. function onRenderTargetDispose( event ) {
  39726. const renderTarget = event.target;
  39727. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  39728. deallocateRenderTarget( renderTarget );
  39729. }
  39730. //
  39731. function deallocateTexture( texture ) {
  39732. const textureProperties = properties.get( texture );
  39733. if ( textureProperties.__webglInit === undefined ) return;
  39734. // check if it's necessary to remove the WebGLTexture object
  39735. const source = texture.source;
  39736. const webglTextures = _sources.get( source );
  39737. if ( webglTextures ) {
  39738. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  39739. webglTexture.usedTimes --;
  39740. // the WebGLTexture object is not used anymore, remove it
  39741. if ( webglTexture.usedTimes === 0 ) {
  39742. deleteTexture( texture );
  39743. }
  39744. // remove the weak map entry if no WebGLTexture uses the source anymore
  39745. if ( Object.keys( webglTextures ).length === 0 ) {
  39746. _sources.delete( source );
  39747. }
  39748. }
  39749. properties.remove( texture );
  39750. }
  39751. function deleteTexture( texture ) {
  39752. const textureProperties = properties.get( texture );
  39753. _gl.deleteTexture( textureProperties.__webglTexture );
  39754. const source = texture.source;
  39755. const webglTextures = _sources.get( source );
  39756. delete webglTextures[ textureProperties.__cacheKey ];
  39757. info.memory.textures --;
  39758. }
  39759. function deallocateRenderTarget( renderTarget ) {
  39760. const renderTargetProperties = properties.get( renderTarget );
  39761. if ( renderTarget.depthTexture ) {
  39762. renderTarget.depthTexture.dispose();
  39763. properties.remove( renderTarget.depthTexture );
  39764. }
  39765. if ( renderTarget.isWebGLCubeRenderTarget ) {
  39766. for ( let i = 0; i < 6; i ++ ) {
  39767. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  39768. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  39769. } else {
  39770. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  39771. }
  39772. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  39773. }
  39774. } else {
  39775. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  39776. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  39777. } else {
  39778. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  39779. }
  39780. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  39781. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  39782. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  39783. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  39784. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  39785. }
  39786. }
  39787. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  39788. }
  39789. const textures = renderTarget.textures;
  39790. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39791. const attachmentProperties = properties.get( textures[ i ] );
  39792. if ( attachmentProperties.__webglTexture ) {
  39793. _gl.deleteTexture( attachmentProperties.__webglTexture );
  39794. info.memory.textures --;
  39795. }
  39796. properties.remove( textures[ i ] );
  39797. }
  39798. properties.remove( renderTarget );
  39799. }
  39800. //
  39801. let textureUnits = 0;
  39802. function resetTextureUnits() {
  39803. textureUnits = 0;
  39804. }
  39805. function allocateTextureUnit() {
  39806. const textureUnit = textureUnits;
  39807. if ( textureUnit >= capabilities.maxTextures ) {
  39808. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  39809. }
  39810. textureUnits += 1;
  39811. return textureUnit;
  39812. }
  39813. function getTextureCacheKey( texture ) {
  39814. const array = [];
  39815. array.push( texture.wrapS );
  39816. array.push( texture.wrapT );
  39817. array.push( texture.wrapR || 0 );
  39818. array.push( texture.magFilter );
  39819. array.push( texture.minFilter );
  39820. array.push( texture.anisotropy );
  39821. array.push( texture.internalFormat );
  39822. array.push( texture.format );
  39823. array.push( texture.type );
  39824. array.push( texture.generateMipmaps );
  39825. array.push( texture.premultiplyAlpha );
  39826. array.push( texture.flipY );
  39827. array.push( texture.unpackAlignment );
  39828. array.push( texture.colorSpace );
  39829. return array.join();
  39830. }
  39831. //
  39832. function setTexture2D( texture, slot ) {
  39833. const textureProperties = properties.get( texture );
  39834. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  39835. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  39836. const image = texture.image;
  39837. if ( image === null ) {
  39838. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  39839. } else if ( image.complete === false ) {
  39840. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  39841. } else {
  39842. uploadTexture( textureProperties, texture, slot );
  39843. return;
  39844. }
  39845. }
  39846. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  39847. }
  39848. function setTexture2DArray( texture, slot ) {
  39849. const textureProperties = properties.get( texture );
  39850. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  39851. uploadTexture( textureProperties, texture, slot );
  39852. return;
  39853. }
  39854. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  39855. }
  39856. function setTexture3D( texture, slot ) {
  39857. const textureProperties = properties.get( texture );
  39858. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  39859. uploadTexture( textureProperties, texture, slot );
  39860. return;
  39861. }
  39862. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  39863. }
  39864. function setTextureCube( texture, slot ) {
  39865. const textureProperties = properties.get( texture );
  39866. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  39867. uploadCubeTexture( textureProperties, texture, slot );
  39868. return;
  39869. }
  39870. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  39871. }
  39872. const wrappingToGL = {
  39873. [ RepeatWrapping ]: _gl.REPEAT,
  39874. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  39875. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  39876. };
  39877. const filterToGL = {
  39878. [ NearestFilter ]: _gl.NEAREST,
  39879. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  39880. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  39881. [ LinearFilter ]: _gl.LINEAR,
  39882. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  39883. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  39884. };
  39885. const compareToGL = {
  39886. [ NeverCompare ]: _gl.NEVER,
  39887. [ AlwaysCompare ]: _gl.ALWAYS,
  39888. [ LessCompare ]: _gl.LESS,
  39889. [ LessEqualCompare ]: _gl.LEQUAL,
  39890. [ EqualCompare ]: _gl.EQUAL,
  39891. [ GreaterEqualCompare ]: _gl.GEQUAL,
  39892. [ GreaterCompare ]: _gl.GREATER,
  39893. [ NotEqualCompare ]: _gl.NOTEQUAL
  39894. };
  39895. function setTextureParameters( textureType, texture ) {
  39896. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  39897. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  39898. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  39899. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  39900. }
  39901. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  39902. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  39903. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  39904. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  39905. }
  39906. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  39907. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  39908. if ( texture.compareFunction ) {
  39909. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  39910. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  39911. }
  39912. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  39913. if ( texture.magFilter === NearestFilter ) return;
  39914. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  39915. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  39916. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  39917. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  39918. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  39919. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  39920. }
  39921. }
  39922. }
  39923. function initTexture( textureProperties, texture ) {
  39924. let forceUpload = false;
  39925. if ( textureProperties.__webglInit === undefined ) {
  39926. textureProperties.__webglInit = true;
  39927. texture.addEventListener( 'dispose', onTextureDispose );
  39928. }
  39929. // create Source <-> WebGLTextures mapping if necessary
  39930. const source = texture.source;
  39931. let webglTextures = _sources.get( source );
  39932. if ( webglTextures === undefined ) {
  39933. webglTextures = {};
  39934. _sources.set( source, webglTextures );
  39935. }
  39936. // check if there is already a WebGLTexture object for the given texture parameters
  39937. const textureCacheKey = getTextureCacheKey( texture );
  39938. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  39939. // if not, create a new instance of WebGLTexture
  39940. if ( webglTextures[ textureCacheKey ] === undefined ) {
  39941. // create new entry
  39942. webglTextures[ textureCacheKey ] = {
  39943. texture: _gl.createTexture(),
  39944. usedTimes: 0
  39945. };
  39946. info.memory.textures ++;
  39947. // when a new instance of WebGLTexture was created, a texture upload is required
  39948. // even if the image contents are identical
  39949. forceUpload = true;
  39950. }
  39951. webglTextures[ textureCacheKey ].usedTimes ++;
  39952. // every time the texture cache key changes, it's necessary to check if an instance of
  39953. // WebGLTexture can be deleted in order to avoid a memory leak.
  39954. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  39955. if ( webglTexture !== undefined ) {
  39956. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  39957. if ( webglTexture.usedTimes === 0 ) {
  39958. deleteTexture( texture );
  39959. }
  39960. }
  39961. // store references to cache key and WebGLTexture object
  39962. textureProperties.__cacheKey = textureCacheKey;
  39963. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  39964. }
  39965. return forceUpload;
  39966. }
  39967. function uploadTexture( textureProperties, texture, slot ) {
  39968. let textureType = _gl.TEXTURE_2D;
  39969. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  39970. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  39971. const forceUpload = initTexture( textureProperties, texture );
  39972. const source = texture.source;
  39973. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  39974. const sourceProperties = properties.get( source );
  39975. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  39976. state.activeTexture( _gl.TEXTURE0 + slot );
  39977. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  39978. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  39979. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  39980. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  39981. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  39982. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  39983. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  39984. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  39985. image = verifyColorSpace( texture, image );
  39986. const glFormat = utils.convert( texture.format, texture.colorSpace );
  39987. const glType = utils.convert( texture.type );
  39988. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  39989. setTextureParameters( textureType, texture );
  39990. let mipmap;
  39991. const mipmaps = texture.mipmaps;
  39992. const useTexStorage = ( texture.isVideoTexture !== true );
  39993. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  39994. const dataReady = source.dataReady;
  39995. const levels = getMipLevels( texture, image );
  39996. if ( texture.isDepthTexture ) {
  39997. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  39998. //
  39999. if ( allocateMemory ) {
  40000. if ( useTexStorage ) {
  40001. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  40002. } else {
  40003. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  40004. }
  40005. }
  40006. } else if ( texture.isDataTexture ) {
  40007. // use manually created mipmaps if available
  40008. // if there are no manual mipmaps
  40009. // set 0 level mipmap and then use GL to generate other mipmap levels
  40010. if ( mipmaps.length > 0 ) {
  40011. if ( useTexStorage && allocateMemory ) {
  40012. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  40013. }
  40014. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  40015. mipmap = mipmaps[ i ];
  40016. if ( useTexStorage ) {
  40017. if ( dataReady ) {
  40018. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  40019. }
  40020. } else {
  40021. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  40022. }
  40023. }
  40024. texture.generateMipmaps = false;
  40025. } else {
  40026. if ( useTexStorage ) {
  40027. if ( allocateMemory ) {
  40028. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  40029. }
  40030. if ( dataReady ) {
  40031. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  40032. }
  40033. } else {
  40034. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  40035. }
  40036. }
  40037. } else if ( texture.isCompressedTexture ) {
  40038. if ( texture.isCompressedArrayTexture ) {
  40039. if ( useTexStorage && allocateMemory ) {
  40040. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  40041. }
  40042. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  40043. mipmap = mipmaps[ i ];
  40044. if ( texture.format !== RGBAFormat ) {
  40045. if ( glFormat !== null ) {
  40046. if ( useTexStorage ) {
  40047. if ( dataReady ) {
  40048. if ( texture.layerUpdates.size > 0 ) {
  40049. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  40050. for ( const layerIndex of texture.layerUpdates ) {
  40051. const layerData = mipmap.data.subarray(
  40052. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  40053. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  40054. );
  40055. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  40056. }
  40057. texture.clearLayerUpdates();
  40058. } else {
  40059. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  40060. }
  40061. }
  40062. } else {
  40063. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  40064. }
  40065. } else {
  40066. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  40067. }
  40068. } else {
  40069. if ( useTexStorage ) {
  40070. if ( dataReady ) {
  40071. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  40072. }
  40073. } else {
  40074. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  40075. }
  40076. }
  40077. }
  40078. } else {
  40079. if ( useTexStorage && allocateMemory ) {
  40080. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  40081. }
  40082. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  40083. mipmap = mipmaps[ i ];
  40084. if ( texture.format !== RGBAFormat ) {
  40085. if ( glFormat !== null ) {
  40086. if ( useTexStorage ) {
  40087. if ( dataReady ) {
  40088. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  40089. }
  40090. } else {
  40091. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  40092. }
  40093. } else {
  40094. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  40095. }
  40096. } else {
  40097. if ( useTexStorage ) {
  40098. if ( dataReady ) {
  40099. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  40100. }
  40101. } else {
  40102. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  40103. }
  40104. }
  40105. }
  40106. }
  40107. } else if ( texture.isDataArrayTexture ) {
  40108. if ( useTexStorage ) {
  40109. if ( allocateMemory ) {
  40110. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  40111. }
  40112. if ( dataReady ) {
  40113. if ( texture.layerUpdates.size > 0 ) {
  40114. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  40115. for ( const layerIndex of texture.layerUpdates ) {
  40116. const layerData = image.data.subarray(
  40117. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  40118. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  40119. );
  40120. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  40121. }
  40122. texture.clearLayerUpdates();
  40123. } else {
  40124. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40125. }
  40126. }
  40127. } else {
  40128. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  40129. }
  40130. } else if ( texture.isData3DTexture ) {
  40131. if ( useTexStorage ) {
  40132. if ( allocateMemory ) {
  40133. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  40134. }
  40135. if ( dataReady ) {
  40136. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40137. }
  40138. } else {
  40139. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  40140. }
  40141. } else if ( texture.isFramebufferTexture ) {
  40142. if ( allocateMemory ) {
  40143. if ( useTexStorage ) {
  40144. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  40145. } else {
  40146. let width = image.width, height = image.height;
  40147. for ( let i = 0; i < levels; i ++ ) {
  40148. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  40149. width >>= 1;
  40150. height >>= 1;
  40151. }
  40152. }
  40153. }
  40154. } else {
  40155. // regular Texture (image, video, canvas)
  40156. // use manually created mipmaps if available
  40157. // if there are no manual mipmaps
  40158. // set 0 level mipmap and then use GL to generate other mipmap levels
  40159. if ( mipmaps.length > 0 ) {
  40160. if ( useTexStorage && allocateMemory ) {
  40161. const dimensions = getDimensions( mipmaps[ 0 ] );
  40162. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  40163. }
  40164. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  40165. mipmap = mipmaps[ i ];
  40166. if ( useTexStorage ) {
  40167. if ( dataReady ) {
  40168. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  40169. }
  40170. } else {
  40171. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  40172. }
  40173. }
  40174. texture.generateMipmaps = false;
  40175. } else {
  40176. if ( useTexStorage ) {
  40177. if ( allocateMemory ) {
  40178. const dimensions = getDimensions( image );
  40179. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  40180. }
  40181. if ( dataReady ) {
  40182. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  40183. }
  40184. } else {
  40185. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  40186. }
  40187. }
  40188. }
  40189. if ( textureNeedsGenerateMipmaps( texture ) ) {
  40190. generateMipmap( textureType );
  40191. }
  40192. sourceProperties.__version = source.version;
  40193. if ( texture.onUpdate ) texture.onUpdate( texture );
  40194. }
  40195. textureProperties.__version = texture.version;
  40196. }
  40197. function uploadCubeTexture( textureProperties, texture, slot ) {
  40198. if ( texture.image.length !== 6 ) return;
  40199. const forceUpload = initTexture( textureProperties, texture );
  40200. const source = texture.source;
  40201. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  40202. const sourceProperties = properties.get( source );
  40203. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  40204. state.activeTexture( _gl.TEXTURE0 + slot );
  40205. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  40206. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  40207. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  40208. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  40209. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  40210. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  40211. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  40212. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  40213. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  40214. const cubeImage = [];
  40215. for ( let i = 0; i < 6; i ++ ) {
  40216. if ( ! isCompressed && ! isDataTexture ) {
  40217. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  40218. } else {
  40219. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  40220. }
  40221. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  40222. }
  40223. const image = cubeImage[ 0 ],
  40224. glFormat = utils.convert( texture.format, texture.colorSpace ),
  40225. glType = utils.convert( texture.type ),
  40226. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  40227. const useTexStorage = ( texture.isVideoTexture !== true );
  40228. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  40229. const dataReady = source.dataReady;
  40230. let levels = getMipLevels( texture, image );
  40231. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  40232. let mipmaps;
  40233. if ( isCompressed ) {
  40234. if ( useTexStorage && allocateMemory ) {
  40235. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  40236. }
  40237. for ( let i = 0; i < 6; i ++ ) {
  40238. mipmaps = cubeImage[ i ].mipmaps;
  40239. for ( let j = 0; j < mipmaps.length; j ++ ) {
  40240. const mipmap = mipmaps[ j ];
  40241. if ( texture.format !== RGBAFormat ) {
  40242. if ( glFormat !== null ) {
  40243. if ( useTexStorage ) {
  40244. if ( dataReady ) {
  40245. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  40246. }
  40247. } else {
  40248. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  40249. }
  40250. } else {
  40251. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  40252. }
  40253. } else {
  40254. if ( useTexStorage ) {
  40255. if ( dataReady ) {
  40256. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  40257. }
  40258. } else {
  40259. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  40260. }
  40261. }
  40262. }
  40263. }
  40264. } else {
  40265. mipmaps = texture.mipmaps;
  40266. if ( useTexStorage && allocateMemory ) {
  40267. // TODO: Uniformly handle mipmap definitions
  40268. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  40269. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  40270. if ( mipmaps.length > 0 ) levels ++;
  40271. const dimensions = getDimensions( cubeImage[ 0 ] );
  40272. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  40273. }
  40274. for ( let i = 0; i < 6; i ++ ) {
  40275. if ( isDataTexture ) {
  40276. if ( useTexStorage ) {
  40277. if ( dataReady ) {
  40278. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  40279. }
  40280. } else {
  40281. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  40282. }
  40283. for ( let j = 0; j < mipmaps.length; j ++ ) {
  40284. const mipmap = mipmaps[ j ];
  40285. const mipmapImage = mipmap.image[ i ].image;
  40286. if ( useTexStorage ) {
  40287. if ( dataReady ) {
  40288. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  40289. }
  40290. } else {
  40291. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  40292. }
  40293. }
  40294. } else {
  40295. if ( useTexStorage ) {
  40296. if ( dataReady ) {
  40297. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  40298. }
  40299. } else {
  40300. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  40301. }
  40302. for ( let j = 0; j < mipmaps.length; j ++ ) {
  40303. const mipmap = mipmaps[ j ];
  40304. if ( useTexStorage ) {
  40305. if ( dataReady ) {
  40306. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  40307. }
  40308. } else {
  40309. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  40310. }
  40311. }
  40312. }
  40313. }
  40314. }
  40315. if ( textureNeedsGenerateMipmaps( texture ) ) {
  40316. // We assume images for cube map have the same size.
  40317. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  40318. }
  40319. sourceProperties.__version = source.version;
  40320. if ( texture.onUpdate ) texture.onUpdate( texture );
  40321. }
  40322. textureProperties.__version = texture.version;
  40323. }
  40324. // Render targets
  40325. // Setup storage for target texture and bind it to correct framebuffer
  40326. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  40327. const glFormat = utils.convert( texture.format, texture.colorSpace );
  40328. const glType = utils.convert( texture.type );
  40329. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  40330. const renderTargetProperties = properties.get( renderTarget );
  40331. const textureProperties = properties.get( texture );
  40332. textureProperties.__renderTarget = renderTarget;
  40333. if ( ! renderTargetProperties.__hasExternalTextures ) {
  40334. const width = Math.max( 1, renderTarget.width >> level );
  40335. const height = Math.max( 1, renderTarget.height >> level );
  40336. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  40337. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  40338. } else {
  40339. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  40340. }
  40341. }
  40342. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  40343. if ( useMultisampledRTT( renderTarget ) ) {
  40344. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  40345. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  40346. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  40347. }
  40348. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  40349. }
  40350. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  40351. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  40352. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  40353. if ( renderTarget.depthBuffer ) {
  40354. // retrieve the depth attachment types
  40355. const depthTexture = renderTarget.depthTexture;
  40356. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  40357. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  40358. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  40359. // set up the attachment
  40360. const samples = getRenderTargetSamples( renderTarget );
  40361. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  40362. if ( isUseMultisampledRTT ) {
  40363. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  40364. } else if ( isMultisample ) {
  40365. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  40366. } else {
  40367. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  40368. }
  40369. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  40370. } else {
  40371. const textures = renderTarget.textures;
  40372. for ( let i = 0; i < textures.length; i ++ ) {
  40373. const texture = textures[ i ];
  40374. const glFormat = utils.convert( texture.format, texture.colorSpace );
  40375. const glType = utils.convert( texture.type );
  40376. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  40377. const samples = getRenderTargetSamples( renderTarget );
  40378. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  40379. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  40380. } else if ( useMultisampledRTT( renderTarget ) ) {
  40381. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  40382. } else {
  40383. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  40384. }
  40385. }
  40386. }
  40387. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  40388. }
  40389. // Setup resources for a Depth Texture for a FBO (needs an extension)
  40390. function setupDepthTexture( framebuffer, renderTarget ) {
  40391. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  40392. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  40393. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  40394. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  40395. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  40396. }
  40397. const textureProperties = properties.get( renderTarget.depthTexture );
  40398. textureProperties.__renderTarget = renderTarget;
  40399. // upload an empty depth texture with framebuffer size
  40400. if ( ! textureProperties.__webglTexture ||
  40401. renderTarget.depthTexture.image.width !== renderTarget.width ||
  40402. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  40403. renderTarget.depthTexture.image.width = renderTarget.width;
  40404. renderTarget.depthTexture.image.height = renderTarget.height;
  40405. renderTarget.depthTexture.needsUpdate = true;
  40406. }
  40407. setTexture2D( renderTarget.depthTexture, 0 );
  40408. const webglDepthTexture = textureProperties.__webglTexture;
  40409. const samples = getRenderTargetSamples( renderTarget );
  40410. if ( renderTarget.depthTexture.format === DepthFormat ) {
  40411. if ( useMultisampledRTT( renderTarget ) ) {
  40412. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  40413. } else {
  40414. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  40415. }
  40416. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  40417. if ( useMultisampledRTT( renderTarget ) ) {
  40418. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  40419. } else {
  40420. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  40421. }
  40422. } else {
  40423. throw new Error( 'Unknown depthTexture format' );
  40424. }
  40425. }
  40426. // Setup GL resources for a non-texture depth buffer
  40427. function setupDepthRenderbuffer( renderTarget ) {
  40428. const renderTargetProperties = properties.get( renderTarget );
  40429. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  40430. // if the bound depth texture has changed
  40431. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  40432. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  40433. const depthTexture = renderTarget.depthTexture;
  40434. if ( renderTargetProperties.__depthDisposeCallback ) {
  40435. renderTargetProperties.__depthDisposeCallback();
  40436. }
  40437. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  40438. if ( depthTexture ) {
  40439. const disposeEvent = () => {
  40440. delete renderTargetProperties.__boundDepthTexture;
  40441. delete renderTargetProperties.__depthDisposeCallback;
  40442. depthTexture.removeEventListener( 'dispose', disposeEvent );
  40443. };
  40444. depthTexture.addEventListener( 'dispose', disposeEvent );
  40445. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  40446. }
  40447. renderTargetProperties.__boundDepthTexture = depthTexture;
  40448. }
  40449. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  40450. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  40451. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  40452. } else {
  40453. if ( isCube ) {
  40454. renderTargetProperties.__webglDepthbuffer = [];
  40455. for ( let i = 0; i < 6; i ++ ) {
  40456. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  40457. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  40458. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  40459. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  40460. } else {
  40461. // attach buffer if it's been created already
  40462. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  40463. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  40464. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  40465. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  40466. }
  40467. }
  40468. } else {
  40469. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  40470. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  40471. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  40472. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  40473. } else {
  40474. // attach buffer if it's been created already
  40475. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  40476. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  40477. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  40478. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  40479. }
  40480. }
  40481. }
  40482. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  40483. }
  40484. // rebind framebuffer with external textures
  40485. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  40486. const renderTargetProperties = properties.get( renderTarget );
  40487. if ( colorTexture !== undefined ) {
  40488. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  40489. }
  40490. if ( depthTexture !== undefined ) {
  40491. setupDepthRenderbuffer( renderTarget );
  40492. }
  40493. }
  40494. // Set up GL resources for the render target
  40495. function setupRenderTarget( renderTarget ) {
  40496. const texture = renderTarget.texture;
  40497. const renderTargetProperties = properties.get( renderTarget );
  40498. const textureProperties = properties.get( texture );
  40499. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  40500. const textures = renderTarget.textures;
  40501. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  40502. const isMultipleRenderTargets = ( textures.length > 1 );
  40503. if ( ! isMultipleRenderTargets ) {
  40504. if ( textureProperties.__webglTexture === undefined ) {
  40505. textureProperties.__webglTexture = _gl.createTexture();
  40506. }
  40507. textureProperties.__version = texture.version;
  40508. info.memory.textures ++;
  40509. }
  40510. // Setup framebuffer
  40511. if ( isCube ) {
  40512. renderTargetProperties.__webglFramebuffer = [];
  40513. for ( let i = 0; i < 6; i ++ ) {
  40514. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  40515. renderTargetProperties.__webglFramebuffer[ i ] = [];
  40516. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  40517. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  40518. }
  40519. } else {
  40520. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  40521. }
  40522. }
  40523. } else {
  40524. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  40525. renderTargetProperties.__webglFramebuffer = [];
  40526. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  40527. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  40528. }
  40529. } else {
  40530. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  40531. }
  40532. if ( isMultipleRenderTargets ) {
  40533. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  40534. const attachmentProperties = properties.get( textures[ i ] );
  40535. if ( attachmentProperties.__webglTexture === undefined ) {
  40536. attachmentProperties.__webglTexture = _gl.createTexture();
  40537. info.memory.textures ++;
  40538. }
  40539. }
  40540. }
  40541. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  40542. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  40543. renderTargetProperties.__webglColorRenderbuffer = [];
  40544. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  40545. for ( let i = 0; i < textures.length; i ++ ) {
  40546. const texture = textures[ i ];
  40547. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  40548. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  40549. const glFormat = utils.convert( texture.format, texture.colorSpace );
  40550. const glType = utils.convert( texture.type );
  40551. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  40552. const samples = getRenderTargetSamples( renderTarget );
  40553. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  40554. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  40555. }
  40556. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  40557. if ( renderTarget.depthBuffer ) {
  40558. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  40559. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  40560. }
  40561. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  40562. }
  40563. }
  40564. // Setup color buffer
  40565. if ( isCube ) {
  40566. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  40567. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  40568. for ( let i = 0; i < 6; i ++ ) {
  40569. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  40570. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  40571. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  40572. }
  40573. } else {
  40574. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  40575. }
  40576. }
  40577. if ( textureNeedsGenerateMipmaps( texture ) ) {
  40578. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  40579. }
  40580. state.unbindTexture();
  40581. } else if ( isMultipleRenderTargets ) {
  40582. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  40583. const attachment = textures[ i ];
  40584. const attachmentProperties = properties.get( attachment );
  40585. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  40586. setTextureParameters( _gl.TEXTURE_2D, attachment );
  40587. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  40588. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  40589. generateMipmap( _gl.TEXTURE_2D );
  40590. }
  40591. }
  40592. state.unbindTexture();
  40593. } else {
  40594. let glTextureType = _gl.TEXTURE_2D;
  40595. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  40596. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  40597. }
  40598. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  40599. setTextureParameters( glTextureType, texture );
  40600. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  40601. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  40602. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  40603. }
  40604. } else {
  40605. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  40606. }
  40607. if ( textureNeedsGenerateMipmaps( texture ) ) {
  40608. generateMipmap( glTextureType );
  40609. }
  40610. state.unbindTexture();
  40611. }
  40612. // Setup depth and stencil buffers
  40613. if ( renderTarget.depthBuffer ) {
  40614. setupDepthRenderbuffer( renderTarget );
  40615. }
  40616. }
  40617. function updateRenderTargetMipmap( renderTarget ) {
  40618. const textures = renderTarget.textures;
  40619. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  40620. const texture = textures[ i ];
  40621. if ( textureNeedsGenerateMipmaps( texture ) ) {
  40622. const targetType = getTargetType( renderTarget );
  40623. const webglTexture = properties.get( texture ).__webglTexture;
  40624. state.bindTexture( targetType, webglTexture );
  40625. generateMipmap( targetType );
  40626. state.unbindTexture();
  40627. }
  40628. }
  40629. }
  40630. const invalidationArrayRead = [];
  40631. const invalidationArrayDraw = [];
  40632. function updateMultisampleRenderTarget( renderTarget ) {
  40633. if ( renderTarget.samples > 0 ) {
  40634. if ( useMultisampledRTT( renderTarget ) === false ) {
  40635. const textures = renderTarget.textures;
  40636. const width = renderTarget.width;
  40637. const height = renderTarget.height;
  40638. let mask = _gl.COLOR_BUFFER_BIT;
  40639. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  40640. const renderTargetProperties = properties.get( renderTarget );
  40641. const isMultipleRenderTargets = ( textures.length > 1 );
  40642. // If MRT we need to remove FBO attachments
  40643. if ( isMultipleRenderTargets ) {
  40644. for ( let i = 0; i < textures.length; i ++ ) {
  40645. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  40646. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  40647. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  40648. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  40649. }
  40650. }
  40651. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  40652. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  40653. for ( let i = 0; i < textures.length; i ++ ) {
  40654. if ( renderTarget.resolveDepthBuffer ) {
  40655. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  40656. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  40657. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  40658. }
  40659. if ( isMultipleRenderTargets ) {
  40660. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  40661. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  40662. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  40663. }
  40664. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  40665. if ( supportsInvalidateFramebuffer === true ) {
  40666. invalidationArrayRead.length = 0;
  40667. invalidationArrayDraw.length = 0;
  40668. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  40669. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  40670. invalidationArrayRead.push( depthStyle );
  40671. invalidationArrayDraw.push( depthStyle );
  40672. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  40673. }
  40674. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  40675. }
  40676. }
  40677. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  40678. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  40679. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  40680. if ( isMultipleRenderTargets ) {
  40681. for ( let i = 0; i < textures.length; i ++ ) {
  40682. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  40683. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  40684. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  40685. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  40686. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  40687. }
  40688. }
  40689. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  40690. } else {
  40691. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  40692. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  40693. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  40694. }
  40695. }
  40696. }
  40697. }
  40698. function getRenderTargetSamples( renderTarget ) {
  40699. return Math.min( capabilities.maxSamples, renderTarget.samples );
  40700. }
  40701. function useMultisampledRTT( renderTarget ) {
  40702. const renderTargetProperties = properties.get( renderTarget );
  40703. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  40704. }
  40705. function updateVideoTexture( texture ) {
  40706. const frame = info.render.frame;
  40707. // Check the last frame we updated the VideoTexture
  40708. if ( _videoTextures.get( texture ) !== frame ) {
  40709. _videoTextures.set( texture, frame );
  40710. texture.update();
  40711. }
  40712. }
  40713. function verifyColorSpace( texture, image ) {
  40714. const colorSpace = texture.colorSpace;
  40715. const format = texture.format;
  40716. const type = texture.type;
  40717. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  40718. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  40719. // sRGB
  40720. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  40721. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  40722. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  40723. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  40724. }
  40725. } else {
  40726. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  40727. }
  40728. }
  40729. return image;
  40730. }
  40731. function getDimensions( image ) {
  40732. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  40733. // if intrinsic data are not available, fallback to width/height
  40734. _imageDimensions.width = image.naturalWidth || image.width;
  40735. _imageDimensions.height = image.naturalHeight || image.height;
  40736. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  40737. _imageDimensions.width = image.displayWidth;
  40738. _imageDimensions.height = image.displayHeight;
  40739. } else {
  40740. _imageDimensions.width = image.width;
  40741. _imageDimensions.height = image.height;
  40742. }
  40743. return _imageDimensions;
  40744. }
  40745. //
  40746. this.allocateTextureUnit = allocateTextureUnit;
  40747. this.resetTextureUnits = resetTextureUnits;
  40748. this.setTexture2D = setTexture2D;
  40749. this.setTexture2DArray = setTexture2DArray;
  40750. this.setTexture3D = setTexture3D;
  40751. this.setTextureCube = setTextureCube;
  40752. this.rebindTextures = rebindTextures;
  40753. this.setupRenderTarget = setupRenderTarget;
  40754. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  40755. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  40756. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  40757. this.setupFrameBufferTexture = setupFrameBufferTexture;
  40758. this.useMultisampledRTT = useMultisampledRTT;
  40759. }
  40760. function WebGLUtils( gl, extensions ) {
  40761. function convert( p, colorSpace = NoColorSpace ) {
  40762. let extension;
  40763. const transfer = ColorManagement.getTransfer( colorSpace );
  40764. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  40765. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  40766. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  40767. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  40768. if ( p === ByteType ) return gl.BYTE;
  40769. if ( p === ShortType ) return gl.SHORT;
  40770. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  40771. if ( p === IntType ) return gl.INT;
  40772. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  40773. if ( p === FloatType ) return gl.FLOAT;
  40774. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  40775. if ( p === AlphaFormat ) return gl.ALPHA;
  40776. if ( p === RGBFormat ) return gl.RGB;
  40777. if ( p === RGBAFormat ) return gl.RGBA;
  40778. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  40779. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  40780. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  40781. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  40782. // WebGL2 formats.
  40783. if ( p === RedFormat ) return gl.RED;
  40784. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  40785. if ( p === RGFormat ) return gl.RG;
  40786. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  40787. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  40788. // S3TC
  40789. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  40790. if ( transfer === SRGBTransfer ) {
  40791. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  40792. if ( extension !== null ) {
  40793. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  40794. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  40795. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  40796. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  40797. } else {
  40798. return null;
  40799. }
  40800. } else {
  40801. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  40802. if ( extension !== null ) {
  40803. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  40804. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40805. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40806. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40807. } else {
  40808. return null;
  40809. }
  40810. }
  40811. }
  40812. // PVRTC
  40813. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  40814. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  40815. if ( extension !== null ) {
  40816. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  40817. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  40818. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  40819. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  40820. } else {
  40821. return null;
  40822. }
  40823. }
  40824. // ETC
  40825. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  40826. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  40827. if ( extension !== null ) {
  40828. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  40829. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  40830. } else {
  40831. return null;
  40832. }
  40833. }
  40834. // ASTC
  40835. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  40836. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  40837. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  40838. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  40839. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  40840. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  40841. if ( extension !== null ) {
  40842. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  40843. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  40844. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  40845. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  40846. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  40847. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  40848. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  40849. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  40850. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  40851. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  40852. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  40853. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  40854. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  40855. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  40856. } else {
  40857. return null;
  40858. }
  40859. }
  40860. // BPTC
  40861. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  40862. extension = extensions.get( 'EXT_texture_compression_bptc' );
  40863. if ( extension !== null ) {
  40864. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  40865. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  40866. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  40867. } else {
  40868. return null;
  40869. }
  40870. }
  40871. // RGTC
  40872. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  40873. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  40874. if ( extension !== null ) {
  40875. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  40876. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  40877. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  40878. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  40879. } else {
  40880. return null;
  40881. }
  40882. }
  40883. //
  40884. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  40885. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  40886. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  40887. }
  40888. return { convert: convert };
  40889. }
  40890. const _occlusion_vertex = `
  40891. void main() {
  40892. gl_Position = vec4( position, 1.0 );
  40893. }`;
  40894. const _occlusion_fragment = `
  40895. uniform sampler2DArray depthColor;
  40896. uniform float depthWidth;
  40897. uniform float depthHeight;
  40898. void main() {
  40899. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  40900. if ( coord.x >= 1.0 ) {
  40901. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  40902. } else {
  40903. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  40904. }
  40905. }`;
  40906. class WebXRDepthSensing {
  40907. constructor() {
  40908. this.texture = null;
  40909. this.mesh = null;
  40910. this.depthNear = 0;
  40911. this.depthFar = 0;
  40912. }
  40913. init( renderer, depthData, renderState ) {
  40914. if ( this.texture === null ) {
  40915. const texture = new Texture();
  40916. const texProps = renderer.properties.get( texture );
  40917. texProps.__webglTexture = depthData.texture;
  40918. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  40919. this.depthNear = depthData.depthNear;
  40920. this.depthFar = depthData.depthFar;
  40921. }
  40922. this.texture = texture;
  40923. }
  40924. }
  40925. getMesh( cameraXR ) {
  40926. if ( this.texture !== null ) {
  40927. if ( this.mesh === null ) {
  40928. const viewport = cameraXR.cameras[ 0 ].viewport;
  40929. const material = new ShaderMaterial( {
  40930. vertexShader: _occlusion_vertex,
  40931. fragmentShader: _occlusion_fragment,
  40932. uniforms: {
  40933. depthColor: { value: this.texture },
  40934. depthWidth: { value: viewport.z },
  40935. depthHeight: { value: viewport.w }
  40936. }
  40937. } );
  40938. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  40939. }
  40940. }
  40941. return this.mesh;
  40942. }
  40943. reset() {
  40944. this.texture = null;
  40945. this.mesh = null;
  40946. }
  40947. getDepthTexture() {
  40948. return this.texture;
  40949. }
  40950. }
  40951. class WebXRManager extends EventDispatcher {
  40952. constructor( renderer, gl ) {
  40953. super();
  40954. const scope = this;
  40955. let session = null;
  40956. let framebufferScaleFactor = 1.0;
  40957. let referenceSpace = null;
  40958. let referenceSpaceType = 'local-floor';
  40959. // Set default foveation to maximum.
  40960. let foveation = 1.0;
  40961. let customReferenceSpace = null;
  40962. let pose = null;
  40963. let glBinding = null;
  40964. let glProjLayer = null;
  40965. let glBaseLayer = null;
  40966. let xrFrame = null;
  40967. const depthSensing = new WebXRDepthSensing();
  40968. const attributes = gl.getContextAttributes();
  40969. let initialRenderTarget = null;
  40970. let newRenderTarget = null;
  40971. const controllers = [];
  40972. const controllerInputSources = [];
  40973. const currentSize = new Vector2();
  40974. let currentPixelRatio = null;
  40975. //
  40976. const cameraL = new PerspectiveCamera();
  40977. cameraL.viewport = new Vector4();
  40978. const cameraR = new PerspectiveCamera();
  40979. cameraR.viewport = new Vector4();
  40980. const cameras = [ cameraL, cameraR ];
  40981. const cameraXR = new ArrayCamera();
  40982. let _currentDepthNear = null;
  40983. let _currentDepthFar = null;
  40984. //
  40985. this.cameraAutoUpdate = true;
  40986. this.enabled = false;
  40987. this.isPresenting = false;
  40988. this.getController = function ( index ) {
  40989. let controller = controllers[ index ];
  40990. if ( controller === undefined ) {
  40991. controller = new WebXRController();
  40992. controllers[ index ] = controller;
  40993. }
  40994. return controller.getTargetRaySpace();
  40995. };
  40996. this.getControllerGrip = function ( index ) {
  40997. let controller = controllers[ index ];
  40998. if ( controller === undefined ) {
  40999. controller = new WebXRController();
  41000. controllers[ index ] = controller;
  41001. }
  41002. return controller.getGripSpace();
  41003. };
  41004. this.getHand = function ( index ) {
  41005. let controller = controllers[ index ];
  41006. if ( controller === undefined ) {
  41007. controller = new WebXRController();
  41008. controllers[ index ] = controller;
  41009. }
  41010. return controller.getHandSpace();
  41011. };
  41012. //
  41013. function onSessionEvent( event ) {
  41014. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  41015. if ( controllerIndex === -1 ) {
  41016. return;
  41017. }
  41018. const controller = controllers[ controllerIndex ];
  41019. if ( controller !== undefined ) {
  41020. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  41021. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  41022. }
  41023. }
  41024. function onSessionEnd() {
  41025. session.removeEventListener( 'select', onSessionEvent );
  41026. session.removeEventListener( 'selectstart', onSessionEvent );
  41027. session.removeEventListener( 'selectend', onSessionEvent );
  41028. session.removeEventListener( 'squeeze', onSessionEvent );
  41029. session.removeEventListener( 'squeezestart', onSessionEvent );
  41030. session.removeEventListener( 'squeezeend', onSessionEvent );
  41031. session.removeEventListener( 'end', onSessionEnd );
  41032. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  41033. for ( let i = 0; i < controllers.length; i ++ ) {
  41034. const inputSource = controllerInputSources[ i ];
  41035. if ( inputSource === null ) continue;
  41036. controllerInputSources[ i ] = null;
  41037. controllers[ i ].disconnect( inputSource );
  41038. }
  41039. _currentDepthNear = null;
  41040. _currentDepthFar = null;
  41041. depthSensing.reset();
  41042. // restore framebuffer/rendering state
  41043. renderer.setRenderTarget( initialRenderTarget );
  41044. glBaseLayer = null;
  41045. glProjLayer = null;
  41046. glBinding = null;
  41047. session = null;
  41048. newRenderTarget = null;
  41049. //
  41050. animation.stop();
  41051. scope.isPresenting = false;
  41052. renderer.setPixelRatio( currentPixelRatio );
  41053. renderer.setSize( currentSize.width, currentSize.height, false );
  41054. scope.dispatchEvent( { type: 'sessionend' } );
  41055. }
  41056. this.setFramebufferScaleFactor = function ( value ) {
  41057. framebufferScaleFactor = value;
  41058. if ( scope.isPresenting === true ) {
  41059. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  41060. }
  41061. };
  41062. this.setReferenceSpaceType = function ( value ) {
  41063. referenceSpaceType = value;
  41064. if ( scope.isPresenting === true ) {
  41065. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  41066. }
  41067. };
  41068. this.getReferenceSpace = function () {
  41069. return customReferenceSpace || referenceSpace;
  41070. };
  41071. this.setReferenceSpace = function ( space ) {
  41072. customReferenceSpace = space;
  41073. };
  41074. this.getBaseLayer = function () {
  41075. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  41076. };
  41077. this.getBinding = function () {
  41078. return glBinding;
  41079. };
  41080. this.getFrame = function () {
  41081. return xrFrame;
  41082. };
  41083. this.getSession = function () {
  41084. return session;
  41085. };
  41086. this.setSession = async function ( value ) {
  41087. session = value;
  41088. if ( session !== null ) {
  41089. initialRenderTarget = renderer.getRenderTarget();
  41090. session.addEventListener( 'select', onSessionEvent );
  41091. session.addEventListener( 'selectstart', onSessionEvent );
  41092. session.addEventListener( 'selectend', onSessionEvent );
  41093. session.addEventListener( 'squeeze', onSessionEvent );
  41094. session.addEventListener( 'squeezestart', onSessionEvent );
  41095. session.addEventListener( 'squeezeend', onSessionEvent );
  41096. session.addEventListener( 'end', onSessionEnd );
  41097. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  41098. if ( attributes.xrCompatible !== true ) {
  41099. await gl.makeXRCompatible();
  41100. }
  41101. currentPixelRatio = renderer.getPixelRatio();
  41102. renderer.getSize( currentSize );
  41103. // Check that the browser implements the necessary APIs to use an
  41104. // XRProjectionLayer rather than an XRWebGLLayer
  41105. const useLayers = typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype;
  41106. if ( ! useLayers ) {
  41107. const layerInit = {
  41108. antialias: attributes.antialias,
  41109. alpha: true,
  41110. depth: attributes.depth,
  41111. stencil: attributes.stencil,
  41112. framebufferScaleFactor: framebufferScaleFactor
  41113. };
  41114. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  41115. session.updateRenderState( { baseLayer: glBaseLayer } );
  41116. renderer.setPixelRatio( 1 );
  41117. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  41118. newRenderTarget = new WebGLRenderTarget(
  41119. glBaseLayer.framebufferWidth,
  41120. glBaseLayer.framebufferHeight,
  41121. {
  41122. format: RGBAFormat,
  41123. type: UnsignedByteType,
  41124. colorSpace: renderer.outputColorSpace,
  41125. stencilBuffer: attributes.stencil,
  41126. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  41127. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  41128. }
  41129. );
  41130. } else {
  41131. let depthFormat = null;
  41132. let depthType = null;
  41133. let glDepthFormat = null;
  41134. if ( attributes.depth ) {
  41135. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  41136. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  41137. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  41138. }
  41139. const projectionlayerInit = {
  41140. colorFormat: gl.RGBA8,
  41141. depthFormat: glDepthFormat,
  41142. scaleFactor: framebufferScaleFactor
  41143. };
  41144. glBinding = new XRWebGLBinding( session, gl );
  41145. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  41146. session.updateRenderState( { layers: [ glProjLayer ] } );
  41147. renderer.setPixelRatio( 1 );
  41148. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  41149. newRenderTarget = new WebGLRenderTarget(
  41150. glProjLayer.textureWidth,
  41151. glProjLayer.textureHeight,
  41152. {
  41153. format: RGBAFormat,
  41154. type: UnsignedByteType,
  41155. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  41156. stencilBuffer: attributes.stencil,
  41157. colorSpace: renderer.outputColorSpace,
  41158. samples: attributes.antialias ? 4 : 0,
  41159. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  41160. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  41161. } );
  41162. }
  41163. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  41164. this.setFoveation( foveation );
  41165. customReferenceSpace = null;
  41166. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  41167. animation.setContext( session );
  41168. animation.start();
  41169. scope.isPresenting = true;
  41170. scope.dispatchEvent( { type: 'sessionstart' } );
  41171. }
  41172. };
  41173. this.getEnvironmentBlendMode = function () {
  41174. if ( session !== null ) {
  41175. return session.environmentBlendMode;
  41176. }
  41177. };
  41178. this.getDepthTexture = function () {
  41179. return depthSensing.getDepthTexture();
  41180. };
  41181. function onInputSourcesChange( event ) {
  41182. // Notify disconnected
  41183. for ( let i = 0; i < event.removed.length; i ++ ) {
  41184. const inputSource = event.removed[ i ];
  41185. const index = controllerInputSources.indexOf( inputSource );
  41186. if ( index >= 0 ) {
  41187. controllerInputSources[ index ] = null;
  41188. controllers[ index ].disconnect( inputSource );
  41189. }
  41190. }
  41191. // Notify connected
  41192. for ( let i = 0; i < event.added.length; i ++ ) {
  41193. const inputSource = event.added[ i ];
  41194. let controllerIndex = controllerInputSources.indexOf( inputSource );
  41195. if ( controllerIndex === -1 ) {
  41196. // Assign input source a controller that currently has no input source
  41197. for ( let i = 0; i < controllers.length; i ++ ) {
  41198. if ( i >= controllerInputSources.length ) {
  41199. controllerInputSources.push( inputSource );
  41200. controllerIndex = i;
  41201. break;
  41202. } else if ( controllerInputSources[ i ] === null ) {
  41203. controllerInputSources[ i ] = inputSource;
  41204. controllerIndex = i;
  41205. break;
  41206. }
  41207. }
  41208. // If all controllers do currently receive input we ignore new ones
  41209. if ( controllerIndex === -1 ) break;
  41210. }
  41211. const controller = controllers[ controllerIndex ];
  41212. if ( controller ) {
  41213. controller.connect( inputSource );
  41214. }
  41215. }
  41216. }
  41217. //
  41218. const cameraLPos = new Vector3();
  41219. const cameraRPos = new Vector3();
  41220. /**
  41221. * Assumes 2 cameras that are parallel and share an X-axis, and that
  41222. * the cameras' projection and world matrices have already been set.
  41223. * And that near and far planes are identical for both cameras.
  41224. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  41225. *
  41226. * @param {ArrayCamera} camera - The camera to update.
  41227. * @param {PerspectiveCamera} cameraL - The left camera.
  41228. * @param {PerspectiveCamera} cameraR - The right camera.
  41229. */
  41230. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  41231. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  41232. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  41233. const ipd = cameraLPos.distanceTo( cameraRPos );
  41234. const projL = cameraL.projectionMatrix.elements;
  41235. const projR = cameraR.projectionMatrix.elements;
  41236. // VR systems will have identical far and near planes, and
  41237. // most likely identical top and bottom frustum extents.
  41238. // Use the left camera for these values.
  41239. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  41240. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  41241. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  41242. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  41243. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  41244. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  41245. const left = near * leftFov;
  41246. const right = near * rightFov;
  41247. // Calculate the new camera's position offset from the
  41248. // left camera. xOffset should be roughly half `ipd`.
  41249. const zOffset = ipd / ( - leftFov + rightFov );
  41250. const xOffset = zOffset * - leftFov;
  41251. // TODO: Better way to apply this offset?
  41252. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  41253. camera.translateX( xOffset );
  41254. camera.translateZ( zOffset );
  41255. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  41256. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  41257. // Check if the projection uses an infinite far plane.
  41258. if ( projL[ 10 ] === -1 ) {
  41259. // Use the projection matrix from the left eye.
  41260. // The camera offset is sufficient to include the view volumes
  41261. // of both eyes (assuming symmetric projections).
  41262. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  41263. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  41264. } else {
  41265. // Find the union of the frustum values of the cameras and scale
  41266. // the values so that the near plane's position does not change in world space,
  41267. // although must now be relative to the new union camera.
  41268. const near2 = near + zOffset;
  41269. const far2 = far + zOffset;
  41270. const left2 = left - xOffset;
  41271. const right2 = right + ( ipd - xOffset );
  41272. const top2 = topFov * far / far2 * near2;
  41273. const bottom2 = bottomFov * far / far2 * near2;
  41274. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  41275. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  41276. }
  41277. }
  41278. function updateCamera( camera, parent ) {
  41279. if ( parent === null ) {
  41280. camera.matrixWorld.copy( camera.matrix );
  41281. } else {
  41282. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  41283. }
  41284. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  41285. }
  41286. this.updateCamera = function ( camera ) {
  41287. if ( session === null ) return;
  41288. let depthNear = camera.near;
  41289. let depthFar = camera.far;
  41290. if ( depthSensing.texture !== null ) {
  41291. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  41292. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  41293. }
  41294. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  41295. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  41296. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  41297. // Note that the new renderState won't apply until the next frame. See #18320
  41298. session.updateRenderState( {
  41299. depthNear: cameraXR.near,
  41300. depthFar: cameraXR.far
  41301. } );
  41302. _currentDepthNear = cameraXR.near;
  41303. _currentDepthFar = cameraXR.far;
  41304. }
  41305. cameraL.layers.mask = camera.layers.mask | 0b010;
  41306. cameraR.layers.mask = camera.layers.mask | 0b100;
  41307. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  41308. const parent = camera.parent;
  41309. const cameras = cameraXR.cameras;
  41310. updateCamera( cameraXR, parent );
  41311. for ( let i = 0; i < cameras.length; i ++ ) {
  41312. updateCamera( cameras[ i ], parent );
  41313. }
  41314. // update projection matrix for proper view frustum culling
  41315. if ( cameras.length === 2 ) {
  41316. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  41317. } else {
  41318. // assume single camera setup (AR)
  41319. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  41320. }
  41321. // update user camera and its children
  41322. updateUserCamera( camera, cameraXR, parent );
  41323. };
  41324. function updateUserCamera( camera, cameraXR, parent ) {
  41325. if ( parent === null ) {
  41326. camera.matrix.copy( cameraXR.matrixWorld );
  41327. } else {
  41328. camera.matrix.copy( parent.matrixWorld );
  41329. camera.matrix.invert();
  41330. camera.matrix.multiply( cameraXR.matrixWorld );
  41331. }
  41332. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  41333. camera.updateMatrixWorld( true );
  41334. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  41335. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  41336. if ( camera.isPerspectiveCamera ) {
  41337. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  41338. camera.zoom = 1;
  41339. }
  41340. }
  41341. this.getCamera = function () {
  41342. return cameraXR;
  41343. };
  41344. this.getFoveation = function () {
  41345. if ( glProjLayer === null && glBaseLayer === null ) {
  41346. return undefined;
  41347. }
  41348. return foveation;
  41349. };
  41350. this.setFoveation = function ( value ) {
  41351. // 0 = no foveation = full resolution
  41352. // 1 = maximum foveation = the edges render at lower resolution
  41353. foveation = value;
  41354. if ( glProjLayer !== null ) {
  41355. glProjLayer.fixedFoveation = value;
  41356. }
  41357. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  41358. glBaseLayer.fixedFoveation = value;
  41359. }
  41360. };
  41361. this.hasDepthSensing = function () {
  41362. return depthSensing.texture !== null;
  41363. };
  41364. this.getDepthSensingMesh = function () {
  41365. return depthSensing.getMesh( cameraXR );
  41366. };
  41367. // Animation Loop
  41368. let onAnimationFrameCallback = null;
  41369. function onAnimationFrame( time, frame ) {
  41370. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  41371. xrFrame = frame;
  41372. if ( pose !== null ) {
  41373. const views = pose.views;
  41374. if ( glBaseLayer !== null ) {
  41375. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  41376. renderer.setRenderTarget( newRenderTarget );
  41377. }
  41378. let cameraXRNeedsUpdate = false;
  41379. // check if it's necessary to rebuild cameraXR's camera list
  41380. if ( views.length !== cameraXR.cameras.length ) {
  41381. cameraXR.cameras.length = 0;
  41382. cameraXRNeedsUpdate = true;
  41383. }
  41384. for ( let i = 0; i < views.length; i ++ ) {
  41385. const view = views[ i ];
  41386. let viewport = null;
  41387. if ( glBaseLayer !== null ) {
  41388. viewport = glBaseLayer.getViewport( view );
  41389. } else {
  41390. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  41391. viewport = glSubImage.viewport;
  41392. // For side-by-side projection, we only produce a single texture for both eyes.
  41393. if ( i === 0 ) {
  41394. renderer.setRenderTargetTextures(
  41395. newRenderTarget,
  41396. glSubImage.colorTexture,
  41397. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  41398. renderer.setRenderTarget( newRenderTarget );
  41399. }
  41400. }
  41401. let camera = cameras[ i ];
  41402. if ( camera === undefined ) {
  41403. camera = new PerspectiveCamera();
  41404. camera.layers.enable( i );
  41405. camera.viewport = new Vector4();
  41406. cameras[ i ] = camera;
  41407. }
  41408. camera.matrix.fromArray( view.transform.matrix );
  41409. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  41410. camera.projectionMatrix.fromArray( view.projectionMatrix );
  41411. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  41412. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  41413. if ( i === 0 ) {
  41414. cameraXR.matrix.copy( camera.matrix );
  41415. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  41416. }
  41417. if ( cameraXRNeedsUpdate === true ) {
  41418. cameraXR.cameras.push( camera );
  41419. }
  41420. }
  41421. //
  41422. const enabledFeatures = session.enabledFeatures;
  41423. const gpuDepthSensingEnabled = enabledFeatures &&
  41424. enabledFeatures.includes( 'depth-sensing' ) &&
  41425. session.depthUsage == 'gpu-optimized';
  41426. if ( gpuDepthSensingEnabled && glBinding ) {
  41427. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  41428. if ( depthData && depthData.isValid && depthData.texture ) {
  41429. depthSensing.init( renderer, depthData, session.renderState );
  41430. }
  41431. }
  41432. }
  41433. //
  41434. for ( let i = 0; i < controllers.length; i ++ ) {
  41435. const inputSource = controllerInputSources[ i ];
  41436. const controller = controllers[ i ];
  41437. if ( inputSource !== null && controller !== undefined ) {
  41438. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  41439. }
  41440. }
  41441. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  41442. if ( frame.detectedPlanes ) {
  41443. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  41444. }
  41445. xrFrame = null;
  41446. }
  41447. const animation = new WebGLAnimation();
  41448. animation.setAnimationLoop( onAnimationFrame );
  41449. this.setAnimationLoop = function ( callback ) {
  41450. onAnimationFrameCallback = callback;
  41451. };
  41452. this.dispose = function () {};
  41453. }
  41454. }
  41455. const _e1 = /*@__PURE__*/ new Euler();
  41456. const _m1 = /*@__PURE__*/ new Matrix4();
  41457. function WebGLMaterials( renderer, properties ) {
  41458. function refreshTransformUniform( map, uniform ) {
  41459. if ( map.matrixAutoUpdate === true ) {
  41460. map.updateMatrix();
  41461. }
  41462. uniform.value.copy( map.matrix );
  41463. }
  41464. function refreshFogUniforms( uniforms, fog ) {
  41465. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  41466. if ( fog.isFog ) {
  41467. uniforms.fogNear.value = fog.near;
  41468. uniforms.fogFar.value = fog.far;
  41469. } else if ( fog.isFogExp2 ) {
  41470. uniforms.fogDensity.value = fog.density;
  41471. }
  41472. }
  41473. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  41474. if ( material.isMeshBasicMaterial ) {
  41475. refreshUniformsCommon( uniforms, material );
  41476. } else if ( material.isMeshLambertMaterial ) {
  41477. refreshUniformsCommon( uniforms, material );
  41478. } else if ( material.isMeshToonMaterial ) {
  41479. refreshUniformsCommon( uniforms, material );
  41480. refreshUniformsToon( uniforms, material );
  41481. } else if ( material.isMeshPhongMaterial ) {
  41482. refreshUniformsCommon( uniforms, material );
  41483. refreshUniformsPhong( uniforms, material );
  41484. } else if ( material.isMeshStandardMaterial ) {
  41485. refreshUniformsCommon( uniforms, material );
  41486. refreshUniformsStandard( uniforms, material );
  41487. if ( material.isMeshPhysicalMaterial ) {
  41488. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  41489. }
  41490. } else if ( material.isMeshMatcapMaterial ) {
  41491. refreshUniformsCommon( uniforms, material );
  41492. refreshUniformsMatcap( uniforms, material );
  41493. } else if ( material.isMeshDepthMaterial ) {
  41494. refreshUniformsCommon( uniforms, material );
  41495. } else if ( material.isMeshDistanceMaterial ) {
  41496. refreshUniformsCommon( uniforms, material );
  41497. refreshUniformsDistance( uniforms, material );
  41498. } else if ( material.isMeshNormalMaterial ) {
  41499. refreshUniformsCommon( uniforms, material );
  41500. } else if ( material.isLineBasicMaterial ) {
  41501. refreshUniformsLine( uniforms, material );
  41502. if ( material.isLineDashedMaterial ) {
  41503. refreshUniformsDash( uniforms, material );
  41504. }
  41505. } else if ( material.isPointsMaterial ) {
  41506. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  41507. } else if ( material.isSpriteMaterial ) {
  41508. refreshUniformsSprites( uniforms, material );
  41509. } else if ( material.isShadowMaterial ) {
  41510. uniforms.color.value.copy( material.color );
  41511. uniforms.opacity.value = material.opacity;
  41512. } else if ( material.isShaderMaterial ) {
  41513. material.uniformsNeedUpdate = false; // #15581
  41514. }
  41515. }
  41516. function refreshUniformsCommon( uniforms, material ) {
  41517. uniforms.opacity.value = material.opacity;
  41518. if ( material.color ) {
  41519. uniforms.diffuse.value.copy( material.color );
  41520. }
  41521. if ( material.emissive ) {
  41522. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  41523. }
  41524. if ( material.map ) {
  41525. uniforms.map.value = material.map;
  41526. refreshTransformUniform( material.map, uniforms.mapTransform );
  41527. }
  41528. if ( material.alphaMap ) {
  41529. uniforms.alphaMap.value = material.alphaMap;
  41530. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  41531. }
  41532. if ( material.bumpMap ) {
  41533. uniforms.bumpMap.value = material.bumpMap;
  41534. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  41535. uniforms.bumpScale.value = material.bumpScale;
  41536. if ( material.side === BackSide ) {
  41537. uniforms.bumpScale.value *= -1;
  41538. }
  41539. }
  41540. if ( material.normalMap ) {
  41541. uniforms.normalMap.value = material.normalMap;
  41542. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  41543. uniforms.normalScale.value.copy( material.normalScale );
  41544. if ( material.side === BackSide ) {
  41545. uniforms.normalScale.value.negate();
  41546. }
  41547. }
  41548. if ( material.displacementMap ) {
  41549. uniforms.displacementMap.value = material.displacementMap;
  41550. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  41551. uniforms.displacementScale.value = material.displacementScale;
  41552. uniforms.displacementBias.value = material.displacementBias;
  41553. }
  41554. if ( material.emissiveMap ) {
  41555. uniforms.emissiveMap.value = material.emissiveMap;
  41556. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  41557. }
  41558. if ( material.specularMap ) {
  41559. uniforms.specularMap.value = material.specularMap;
  41560. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  41561. }
  41562. if ( material.alphaTest > 0 ) {
  41563. uniforms.alphaTest.value = material.alphaTest;
  41564. }
  41565. const materialProperties = properties.get( material );
  41566. const envMap = materialProperties.envMap;
  41567. const envMapRotation = materialProperties.envMapRotation;
  41568. if ( envMap ) {
  41569. uniforms.envMap.value = envMap;
  41570. _e1.copy( envMapRotation );
  41571. // accommodate left-handed frame
  41572. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  41573. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  41574. // environment maps which are not cube render targets or PMREMs follow a different convention
  41575. _e1.y *= -1;
  41576. _e1.z *= -1;
  41577. }
  41578. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  41579. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  41580. uniforms.reflectivity.value = material.reflectivity;
  41581. uniforms.ior.value = material.ior;
  41582. uniforms.refractionRatio.value = material.refractionRatio;
  41583. }
  41584. if ( material.lightMap ) {
  41585. uniforms.lightMap.value = material.lightMap;
  41586. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  41587. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  41588. }
  41589. if ( material.aoMap ) {
  41590. uniforms.aoMap.value = material.aoMap;
  41591. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  41592. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  41593. }
  41594. }
  41595. function refreshUniformsLine( uniforms, material ) {
  41596. uniforms.diffuse.value.copy( material.color );
  41597. uniforms.opacity.value = material.opacity;
  41598. if ( material.map ) {
  41599. uniforms.map.value = material.map;
  41600. refreshTransformUniform( material.map, uniforms.mapTransform );
  41601. }
  41602. }
  41603. function refreshUniformsDash( uniforms, material ) {
  41604. uniforms.dashSize.value = material.dashSize;
  41605. uniforms.totalSize.value = material.dashSize + material.gapSize;
  41606. uniforms.scale.value = material.scale;
  41607. }
  41608. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  41609. uniforms.diffuse.value.copy( material.color );
  41610. uniforms.opacity.value = material.opacity;
  41611. uniforms.size.value = material.size * pixelRatio;
  41612. uniforms.scale.value = height * 0.5;
  41613. if ( material.map ) {
  41614. uniforms.map.value = material.map;
  41615. refreshTransformUniform( material.map, uniforms.uvTransform );
  41616. }
  41617. if ( material.alphaMap ) {
  41618. uniforms.alphaMap.value = material.alphaMap;
  41619. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  41620. }
  41621. if ( material.alphaTest > 0 ) {
  41622. uniforms.alphaTest.value = material.alphaTest;
  41623. }
  41624. }
  41625. function refreshUniformsSprites( uniforms, material ) {
  41626. uniforms.diffuse.value.copy( material.color );
  41627. uniforms.opacity.value = material.opacity;
  41628. uniforms.rotation.value = material.rotation;
  41629. if ( material.map ) {
  41630. uniforms.map.value = material.map;
  41631. refreshTransformUniform( material.map, uniforms.mapTransform );
  41632. }
  41633. if ( material.alphaMap ) {
  41634. uniforms.alphaMap.value = material.alphaMap;
  41635. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  41636. }
  41637. if ( material.alphaTest > 0 ) {
  41638. uniforms.alphaTest.value = material.alphaTest;
  41639. }
  41640. }
  41641. function refreshUniformsPhong( uniforms, material ) {
  41642. uniforms.specular.value.copy( material.specular );
  41643. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  41644. }
  41645. function refreshUniformsToon( uniforms, material ) {
  41646. if ( material.gradientMap ) {
  41647. uniforms.gradientMap.value = material.gradientMap;
  41648. }
  41649. }
  41650. function refreshUniformsStandard( uniforms, material ) {
  41651. uniforms.metalness.value = material.metalness;
  41652. if ( material.metalnessMap ) {
  41653. uniforms.metalnessMap.value = material.metalnessMap;
  41654. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  41655. }
  41656. uniforms.roughness.value = material.roughness;
  41657. if ( material.roughnessMap ) {
  41658. uniforms.roughnessMap.value = material.roughnessMap;
  41659. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  41660. }
  41661. if ( material.envMap ) {
  41662. //uniforms.envMap.value = material.envMap; // part of uniforms common
  41663. uniforms.envMapIntensity.value = material.envMapIntensity;
  41664. }
  41665. }
  41666. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  41667. uniforms.ior.value = material.ior; // also part of uniforms common
  41668. if ( material.sheen > 0 ) {
  41669. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  41670. uniforms.sheenRoughness.value = material.sheenRoughness;
  41671. if ( material.sheenColorMap ) {
  41672. uniforms.sheenColorMap.value = material.sheenColorMap;
  41673. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  41674. }
  41675. if ( material.sheenRoughnessMap ) {
  41676. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  41677. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  41678. }
  41679. }
  41680. if ( material.clearcoat > 0 ) {
  41681. uniforms.clearcoat.value = material.clearcoat;
  41682. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  41683. if ( material.clearcoatMap ) {
  41684. uniforms.clearcoatMap.value = material.clearcoatMap;
  41685. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  41686. }
  41687. if ( material.clearcoatRoughnessMap ) {
  41688. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  41689. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  41690. }
  41691. if ( material.clearcoatNormalMap ) {
  41692. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  41693. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  41694. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  41695. if ( material.side === BackSide ) {
  41696. uniforms.clearcoatNormalScale.value.negate();
  41697. }
  41698. }
  41699. }
  41700. if ( material.dispersion > 0 ) {
  41701. uniforms.dispersion.value = material.dispersion;
  41702. }
  41703. if ( material.iridescence > 0 ) {
  41704. uniforms.iridescence.value = material.iridescence;
  41705. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  41706. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  41707. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  41708. if ( material.iridescenceMap ) {
  41709. uniforms.iridescenceMap.value = material.iridescenceMap;
  41710. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  41711. }
  41712. if ( material.iridescenceThicknessMap ) {
  41713. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  41714. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  41715. }
  41716. }
  41717. if ( material.transmission > 0 ) {
  41718. uniforms.transmission.value = material.transmission;
  41719. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  41720. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  41721. if ( material.transmissionMap ) {
  41722. uniforms.transmissionMap.value = material.transmissionMap;
  41723. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  41724. }
  41725. uniforms.thickness.value = material.thickness;
  41726. if ( material.thicknessMap ) {
  41727. uniforms.thicknessMap.value = material.thicknessMap;
  41728. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  41729. }
  41730. uniforms.attenuationDistance.value = material.attenuationDistance;
  41731. uniforms.attenuationColor.value.copy( material.attenuationColor );
  41732. }
  41733. if ( material.anisotropy > 0 ) {
  41734. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  41735. if ( material.anisotropyMap ) {
  41736. uniforms.anisotropyMap.value = material.anisotropyMap;
  41737. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  41738. }
  41739. }
  41740. uniforms.specularIntensity.value = material.specularIntensity;
  41741. uniforms.specularColor.value.copy( material.specularColor );
  41742. if ( material.specularColorMap ) {
  41743. uniforms.specularColorMap.value = material.specularColorMap;
  41744. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  41745. }
  41746. if ( material.specularIntensityMap ) {
  41747. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  41748. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  41749. }
  41750. }
  41751. function refreshUniformsMatcap( uniforms, material ) {
  41752. if ( material.matcap ) {
  41753. uniforms.matcap.value = material.matcap;
  41754. }
  41755. }
  41756. function refreshUniformsDistance( uniforms, material ) {
  41757. const light = properties.get( material ).light;
  41758. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  41759. uniforms.nearDistance.value = light.shadow.camera.near;
  41760. uniforms.farDistance.value = light.shadow.camera.far;
  41761. }
  41762. return {
  41763. refreshFogUniforms: refreshFogUniforms,
  41764. refreshMaterialUniforms: refreshMaterialUniforms
  41765. };
  41766. }
  41767. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  41768. let buffers = {};
  41769. let updateList = {};
  41770. let allocatedBindingPoints = [];
  41771. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  41772. function bind( uniformsGroup, program ) {
  41773. const webglProgram = program.program;
  41774. state.uniformBlockBinding( uniformsGroup, webglProgram );
  41775. }
  41776. function update( uniformsGroup, program ) {
  41777. let buffer = buffers[ uniformsGroup.id ];
  41778. if ( buffer === undefined ) {
  41779. prepareUniformsGroup( uniformsGroup );
  41780. buffer = createBuffer( uniformsGroup );
  41781. buffers[ uniformsGroup.id ] = buffer;
  41782. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  41783. }
  41784. // ensure to update the binding points/block indices mapping for this program
  41785. const webglProgram = program.program;
  41786. state.updateUBOMapping( uniformsGroup, webglProgram );
  41787. // update UBO once per frame
  41788. const frame = info.render.frame;
  41789. if ( updateList[ uniformsGroup.id ] !== frame ) {
  41790. updateBufferData( uniformsGroup );
  41791. updateList[ uniformsGroup.id ] = frame;
  41792. }
  41793. }
  41794. function createBuffer( uniformsGroup ) {
  41795. // the setup of an UBO is independent of a particular shader program but global
  41796. const bindingPointIndex = allocateBindingPointIndex();
  41797. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  41798. const buffer = gl.createBuffer();
  41799. const size = uniformsGroup.__size;
  41800. const usage = uniformsGroup.usage;
  41801. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  41802. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  41803. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  41804. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  41805. return buffer;
  41806. }
  41807. function allocateBindingPointIndex() {
  41808. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  41809. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  41810. allocatedBindingPoints.push( i );
  41811. return i;
  41812. }
  41813. }
  41814. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  41815. return 0;
  41816. }
  41817. function updateBufferData( uniformsGroup ) {
  41818. const buffer = buffers[ uniformsGroup.id ];
  41819. const uniforms = uniformsGroup.uniforms;
  41820. const cache = uniformsGroup.__cache;
  41821. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  41822. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  41823. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  41824. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  41825. const uniform = uniformArray[ j ];
  41826. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  41827. const offset = uniform.__offset;
  41828. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  41829. let arrayOffset = 0;
  41830. for ( let k = 0; k < values.length; k ++ ) {
  41831. const value = values[ k ];
  41832. const info = getUniformSize( value );
  41833. // TODO add integer and struct support
  41834. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  41835. uniform.__data[ 0 ] = value;
  41836. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  41837. } else if ( value.isMatrix3 ) {
  41838. // manually converting 3x3 to 3x4
  41839. uniform.__data[ 0 ] = value.elements[ 0 ];
  41840. uniform.__data[ 1 ] = value.elements[ 1 ];
  41841. uniform.__data[ 2 ] = value.elements[ 2 ];
  41842. uniform.__data[ 3 ] = 0;
  41843. uniform.__data[ 4 ] = value.elements[ 3 ];
  41844. uniform.__data[ 5 ] = value.elements[ 4 ];
  41845. uniform.__data[ 6 ] = value.elements[ 5 ];
  41846. uniform.__data[ 7 ] = 0;
  41847. uniform.__data[ 8 ] = value.elements[ 6 ];
  41848. uniform.__data[ 9 ] = value.elements[ 7 ];
  41849. uniform.__data[ 10 ] = value.elements[ 8 ];
  41850. uniform.__data[ 11 ] = 0;
  41851. } else {
  41852. value.toArray( uniform.__data, arrayOffset );
  41853. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  41854. }
  41855. }
  41856. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  41857. }
  41858. }
  41859. }
  41860. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  41861. }
  41862. function hasUniformChanged( uniform, index, indexArray, cache ) {
  41863. const value = uniform.value;
  41864. const indexString = index + '_' + indexArray;
  41865. if ( cache[ indexString ] === undefined ) {
  41866. // cache entry does not exist so far
  41867. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  41868. cache[ indexString ] = value;
  41869. } else {
  41870. cache[ indexString ] = value.clone();
  41871. }
  41872. return true;
  41873. } else {
  41874. const cachedObject = cache[ indexString ];
  41875. // compare current value with cached entry
  41876. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  41877. if ( cachedObject !== value ) {
  41878. cache[ indexString ] = value;
  41879. return true;
  41880. }
  41881. } else {
  41882. if ( cachedObject.equals( value ) === false ) {
  41883. cachedObject.copy( value );
  41884. return true;
  41885. }
  41886. }
  41887. }
  41888. return false;
  41889. }
  41890. function prepareUniformsGroup( uniformsGroup ) {
  41891. // determine total buffer size according to the STD140 layout
  41892. // Hint: STD140 is the only supported layout in WebGL 2
  41893. const uniforms = uniformsGroup.uniforms;
  41894. let offset = 0; // global buffer offset in bytes
  41895. const chunkSize = 16; // size of a chunk in bytes
  41896. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  41897. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  41898. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  41899. const uniform = uniformArray[ j ];
  41900. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  41901. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  41902. const value = values[ k ];
  41903. const info = getUniformSize( value );
  41904. const chunkOffset = offset % chunkSize; // offset in the current chunk
  41905. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  41906. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  41907. offset += chunkPadding;
  41908. // Check for chunk overflow
  41909. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  41910. // Add padding and adjust offset
  41911. offset += ( chunkSize - chunkStart );
  41912. }
  41913. // the following two properties will be used for partial buffer updates
  41914. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  41915. uniform.__offset = offset;
  41916. // Update the global offset
  41917. offset += info.storage;
  41918. }
  41919. }
  41920. }
  41921. // ensure correct final padding
  41922. const chunkOffset = offset % chunkSize;
  41923. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  41924. //
  41925. uniformsGroup.__size = offset;
  41926. uniformsGroup.__cache = {};
  41927. return this;
  41928. }
  41929. function getUniformSize( value ) {
  41930. const info = {
  41931. boundary: 0, // bytes
  41932. storage: 0 // bytes
  41933. };
  41934. // determine sizes according to STD140
  41935. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  41936. // float/int/bool
  41937. info.boundary = 4;
  41938. info.storage = 4;
  41939. } else if ( value.isVector2 ) {
  41940. // vec2
  41941. info.boundary = 8;
  41942. info.storage = 8;
  41943. } else if ( value.isVector3 || value.isColor ) {
  41944. // vec3
  41945. info.boundary = 16;
  41946. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  41947. } else if ( value.isVector4 ) {
  41948. // vec4
  41949. info.boundary = 16;
  41950. info.storage = 16;
  41951. } else if ( value.isMatrix3 ) {
  41952. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  41953. info.boundary = 48;
  41954. info.storage = 48;
  41955. } else if ( value.isMatrix4 ) {
  41956. // mat4
  41957. info.boundary = 64;
  41958. info.storage = 64;
  41959. } else if ( value.isTexture ) {
  41960. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  41961. } else {
  41962. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  41963. }
  41964. return info;
  41965. }
  41966. function onUniformsGroupsDispose( event ) {
  41967. const uniformsGroup = event.target;
  41968. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  41969. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  41970. allocatedBindingPoints.splice( index, 1 );
  41971. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  41972. delete buffers[ uniformsGroup.id ];
  41973. delete updateList[ uniformsGroup.id ];
  41974. }
  41975. function dispose() {
  41976. for ( const id in buffers ) {
  41977. gl.deleteBuffer( buffers[ id ] );
  41978. }
  41979. allocatedBindingPoints = [];
  41980. buffers = {};
  41981. updateList = {};
  41982. }
  41983. return {
  41984. bind: bind,
  41985. update: update,
  41986. dispose: dispose
  41987. };
  41988. }
  41989. class WebGLRenderer {
  41990. constructor( parameters = {} ) {
  41991. const {
  41992. canvas = createCanvasElement(),
  41993. context = null,
  41994. depth = true,
  41995. stencil = false,
  41996. alpha = false,
  41997. antialias = false,
  41998. premultipliedAlpha = true,
  41999. preserveDrawingBuffer = false,
  42000. powerPreference = 'default',
  42001. failIfMajorPerformanceCaveat = false,
  42002. reverseDepthBuffer = false,
  42003. } = parameters;
  42004. this.isWebGLRenderer = true;
  42005. let _alpha;
  42006. if ( context !== null ) {
  42007. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  42008. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  42009. }
  42010. _alpha = context.getContextAttributes().alpha;
  42011. } else {
  42012. _alpha = alpha;
  42013. }
  42014. const uintClearColor = new Uint32Array( 4 );
  42015. const intClearColor = new Int32Array( 4 );
  42016. let currentRenderList = null;
  42017. let currentRenderState = null;
  42018. // render() can be called from within a callback triggered by another render.
  42019. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  42020. const renderListStack = [];
  42021. const renderStateStack = [];
  42022. // public properties
  42023. this.domElement = canvas;
  42024. // Debug configuration container
  42025. this.debug = {
  42026. /**
  42027. * Enables error checking and reporting when shader programs are being compiled
  42028. * @type {boolean}
  42029. */
  42030. checkShaderErrors: true,
  42031. /**
  42032. * Callback for custom error reporting.
  42033. * @type {?Function}
  42034. */
  42035. onShaderError: null
  42036. };
  42037. // clearing
  42038. this.autoClear = true;
  42039. this.autoClearColor = true;
  42040. this.autoClearDepth = true;
  42041. this.autoClearStencil = true;
  42042. // scene graph
  42043. this.sortObjects = true;
  42044. // user-defined clipping
  42045. this.clippingPlanes = [];
  42046. this.localClippingEnabled = false;
  42047. // physically based shading
  42048. this._outputColorSpace = SRGBColorSpace;
  42049. // tone mapping
  42050. this.toneMapping = NoToneMapping;
  42051. this.toneMappingExposure = 1.0;
  42052. // internal properties
  42053. const _this = this;
  42054. let _isContextLost = false;
  42055. // internal state cache
  42056. let _currentActiveCubeFace = 0;
  42057. let _currentActiveMipmapLevel = 0;
  42058. let _currentRenderTarget = null;
  42059. let _currentMaterialId = -1;
  42060. let _currentCamera = null;
  42061. const _currentViewport = new Vector4();
  42062. const _currentScissor = new Vector4();
  42063. let _currentScissorTest = null;
  42064. const _currentClearColor = new Color( 0x000000 );
  42065. let _currentClearAlpha = 0;
  42066. //
  42067. let _width = canvas.width;
  42068. let _height = canvas.height;
  42069. let _pixelRatio = 1;
  42070. let _opaqueSort = null;
  42071. let _transparentSort = null;
  42072. const _viewport = new Vector4( 0, 0, _width, _height );
  42073. const _scissor = new Vector4( 0, 0, _width, _height );
  42074. let _scissorTest = false;
  42075. // frustum
  42076. const _frustum = new Frustum();
  42077. // clipping
  42078. let _clippingEnabled = false;
  42079. let _localClippingEnabled = false;
  42080. // transmission render target scale
  42081. this.transmissionResolutionScale = 1.0;
  42082. // camera matrices cache
  42083. const _currentProjectionMatrix = new Matrix4();
  42084. const _projScreenMatrix = new Matrix4();
  42085. const _vector3 = new Vector3();
  42086. const _vector4 = new Vector4();
  42087. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  42088. let _renderBackground = false;
  42089. function getTargetPixelRatio() {
  42090. return _currentRenderTarget === null ? _pixelRatio : 1;
  42091. }
  42092. // initialize
  42093. let _gl = context;
  42094. function getContext( contextName, contextAttributes ) {
  42095. return canvas.getContext( contextName, contextAttributes );
  42096. }
  42097. try {
  42098. const contextAttributes = {
  42099. alpha: true,
  42100. depth,
  42101. stencil,
  42102. antialias,
  42103. premultipliedAlpha,
  42104. preserveDrawingBuffer,
  42105. powerPreference,
  42106. failIfMajorPerformanceCaveat,
  42107. };
  42108. // OffscreenCanvas does not have setAttribute, see #22811
  42109. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  42110. // event listeners must be registered before WebGL context is created, see #12753
  42111. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  42112. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  42113. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  42114. if ( _gl === null ) {
  42115. const contextName = 'webgl2';
  42116. _gl = getContext( contextName, contextAttributes );
  42117. if ( _gl === null ) {
  42118. if ( getContext( contextName ) ) {
  42119. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  42120. } else {
  42121. throw new Error( 'Error creating WebGL context.' );
  42122. }
  42123. }
  42124. }
  42125. } catch ( error ) {
  42126. console.error( 'THREE.WebGLRenderer: ' + error.message );
  42127. throw error;
  42128. }
  42129. let extensions, capabilities, state, info;
  42130. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  42131. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  42132. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  42133. let utils, bindingStates, uniformsGroups;
  42134. function initGLContext() {
  42135. extensions = new WebGLExtensions( _gl );
  42136. extensions.init();
  42137. utils = new WebGLUtils( _gl, extensions );
  42138. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  42139. state = new WebGLState( _gl, extensions );
  42140. if ( capabilities.reverseDepthBuffer && reverseDepthBuffer ) {
  42141. state.buffers.depth.setReversed( true );
  42142. }
  42143. info = new WebGLInfo( _gl );
  42144. properties = new WebGLProperties();
  42145. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  42146. cubemaps = new WebGLCubeMaps( _this );
  42147. cubeuvmaps = new WebGLCubeUVMaps( _this );
  42148. attributes = new WebGLAttributes( _gl );
  42149. bindingStates = new WebGLBindingStates( _gl, attributes );
  42150. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  42151. objects = new WebGLObjects( _gl, geometries, attributes, info );
  42152. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  42153. clipping = new WebGLClipping( properties );
  42154. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  42155. materials = new WebGLMaterials( _this, properties );
  42156. renderLists = new WebGLRenderLists();
  42157. renderStates = new WebGLRenderStates( extensions );
  42158. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  42159. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  42160. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  42161. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  42162. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  42163. info.programs = programCache.programs;
  42164. _this.capabilities = capabilities;
  42165. _this.extensions = extensions;
  42166. _this.properties = properties;
  42167. _this.renderLists = renderLists;
  42168. _this.shadowMap = shadowMap;
  42169. _this.state = state;
  42170. _this.info = info;
  42171. }
  42172. initGLContext();
  42173. // xr
  42174. const xr = new WebXRManager( _this, _gl );
  42175. this.xr = xr;
  42176. // API
  42177. this.getContext = function () {
  42178. return _gl;
  42179. };
  42180. this.getContextAttributes = function () {
  42181. return _gl.getContextAttributes();
  42182. };
  42183. this.forceContextLoss = function () {
  42184. const extension = extensions.get( 'WEBGL_lose_context' );
  42185. if ( extension ) extension.loseContext();
  42186. };
  42187. this.forceContextRestore = function () {
  42188. const extension = extensions.get( 'WEBGL_lose_context' );
  42189. if ( extension ) extension.restoreContext();
  42190. };
  42191. this.getPixelRatio = function () {
  42192. return _pixelRatio;
  42193. };
  42194. this.setPixelRatio = function ( value ) {
  42195. if ( value === undefined ) return;
  42196. _pixelRatio = value;
  42197. this.setSize( _width, _height, false );
  42198. };
  42199. this.getSize = function ( target ) {
  42200. return target.set( _width, _height );
  42201. };
  42202. this.setSize = function ( width, height, updateStyle = true ) {
  42203. if ( xr.isPresenting ) {
  42204. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  42205. return;
  42206. }
  42207. _width = width;
  42208. _height = height;
  42209. canvas.width = Math.floor( width * _pixelRatio );
  42210. canvas.height = Math.floor( height * _pixelRatio );
  42211. if ( updateStyle === true ) {
  42212. canvas.style.width = width + 'px';
  42213. canvas.style.height = height + 'px';
  42214. }
  42215. this.setViewport( 0, 0, width, height );
  42216. };
  42217. this.getDrawingBufferSize = function ( target ) {
  42218. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  42219. };
  42220. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  42221. _width = width;
  42222. _height = height;
  42223. _pixelRatio = pixelRatio;
  42224. canvas.width = Math.floor( width * pixelRatio );
  42225. canvas.height = Math.floor( height * pixelRatio );
  42226. this.setViewport( 0, 0, width, height );
  42227. };
  42228. this.getCurrentViewport = function ( target ) {
  42229. return target.copy( _currentViewport );
  42230. };
  42231. this.getViewport = function ( target ) {
  42232. return target.copy( _viewport );
  42233. };
  42234. this.setViewport = function ( x, y, width, height ) {
  42235. if ( x.isVector4 ) {
  42236. _viewport.set( x.x, x.y, x.z, x.w );
  42237. } else {
  42238. _viewport.set( x, y, width, height );
  42239. }
  42240. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  42241. };
  42242. this.getScissor = function ( target ) {
  42243. return target.copy( _scissor );
  42244. };
  42245. this.setScissor = function ( x, y, width, height ) {
  42246. if ( x.isVector4 ) {
  42247. _scissor.set( x.x, x.y, x.z, x.w );
  42248. } else {
  42249. _scissor.set( x, y, width, height );
  42250. }
  42251. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  42252. };
  42253. this.getScissorTest = function () {
  42254. return _scissorTest;
  42255. };
  42256. this.setScissorTest = function ( boolean ) {
  42257. state.setScissorTest( _scissorTest = boolean );
  42258. };
  42259. this.setOpaqueSort = function ( method ) {
  42260. _opaqueSort = method;
  42261. };
  42262. this.setTransparentSort = function ( method ) {
  42263. _transparentSort = method;
  42264. };
  42265. // Clearing
  42266. this.getClearColor = function ( target ) {
  42267. return target.copy( background.getClearColor() );
  42268. };
  42269. this.setClearColor = function () {
  42270. background.setClearColor( ...arguments );
  42271. };
  42272. this.getClearAlpha = function () {
  42273. return background.getClearAlpha();
  42274. };
  42275. this.setClearAlpha = function () {
  42276. background.setClearAlpha( ...arguments );
  42277. };
  42278. this.clear = function ( color = true, depth = true, stencil = true ) {
  42279. let bits = 0;
  42280. if ( color ) {
  42281. // check if we're trying to clear an integer target
  42282. let isIntegerFormat = false;
  42283. if ( _currentRenderTarget !== null ) {
  42284. const targetFormat = _currentRenderTarget.texture.format;
  42285. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  42286. targetFormat === RGIntegerFormat ||
  42287. targetFormat === RedIntegerFormat;
  42288. }
  42289. // use the appropriate clear functions to clear the target if it's a signed
  42290. // or unsigned integer target
  42291. if ( isIntegerFormat ) {
  42292. const targetType = _currentRenderTarget.texture.type;
  42293. const isUnsignedType = targetType === UnsignedByteType ||
  42294. targetType === UnsignedIntType ||
  42295. targetType === UnsignedShortType ||
  42296. targetType === UnsignedInt248Type ||
  42297. targetType === UnsignedShort4444Type ||
  42298. targetType === UnsignedShort5551Type;
  42299. const clearColor = background.getClearColor();
  42300. const a = background.getClearAlpha();
  42301. const r = clearColor.r;
  42302. const g = clearColor.g;
  42303. const b = clearColor.b;
  42304. if ( isUnsignedType ) {
  42305. uintClearColor[ 0 ] = r;
  42306. uintClearColor[ 1 ] = g;
  42307. uintClearColor[ 2 ] = b;
  42308. uintClearColor[ 3 ] = a;
  42309. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  42310. } else {
  42311. intClearColor[ 0 ] = r;
  42312. intClearColor[ 1 ] = g;
  42313. intClearColor[ 2 ] = b;
  42314. intClearColor[ 3 ] = a;
  42315. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  42316. }
  42317. } else {
  42318. bits |= _gl.COLOR_BUFFER_BIT;
  42319. }
  42320. }
  42321. if ( depth ) {
  42322. bits |= _gl.DEPTH_BUFFER_BIT;
  42323. }
  42324. if ( stencil ) {
  42325. bits |= _gl.STENCIL_BUFFER_BIT;
  42326. this.state.buffers.stencil.setMask( 0xffffffff );
  42327. }
  42328. _gl.clear( bits );
  42329. };
  42330. this.clearColor = function () {
  42331. this.clear( true, false, false );
  42332. };
  42333. this.clearDepth = function () {
  42334. this.clear( false, true, false );
  42335. };
  42336. this.clearStencil = function () {
  42337. this.clear( false, false, true );
  42338. };
  42339. //
  42340. this.dispose = function () {
  42341. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  42342. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  42343. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  42344. background.dispose();
  42345. renderLists.dispose();
  42346. renderStates.dispose();
  42347. properties.dispose();
  42348. cubemaps.dispose();
  42349. cubeuvmaps.dispose();
  42350. objects.dispose();
  42351. bindingStates.dispose();
  42352. uniformsGroups.dispose();
  42353. programCache.dispose();
  42354. xr.dispose();
  42355. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  42356. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  42357. animation.stop();
  42358. };
  42359. // Events
  42360. function onContextLost( event ) {
  42361. event.preventDefault();
  42362. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  42363. _isContextLost = true;
  42364. }
  42365. function onContextRestore( /* event */ ) {
  42366. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  42367. _isContextLost = false;
  42368. const infoAutoReset = info.autoReset;
  42369. const shadowMapEnabled = shadowMap.enabled;
  42370. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  42371. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  42372. const shadowMapType = shadowMap.type;
  42373. initGLContext();
  42374. info.autoReset = infoAutoReset;
  42375. shadowMap.enabled = shadowMapEnabled;
  42376. shadowMap.autoUpdate = shadowMapAutoUpdate;
  42377. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  42378. shadowMap.type = shadowMapType;
  42379. }
  42380. function onContextCreationError( event ) {
  42381. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  42382. }
  42383. function onMaterialDispose( event ) {
  42384. const material = event.target;
  42385. material.removeEventListener( 'dispose', onMaterialDispose );
  42386. deallocateMaterial( material );
  42387. }
  42388. // Buffer deallocation
  42389. function deallocateMaterial( material ) {
  42390. releaseMaterialProgramReferences( material );
  42391. properties.remove( material );
  42392. }
  42393. function releaseMaterialProgramReferences( material ) {
  42394. const programs = properties.get( material ).programs;
  42395. if ( programs !== undefined ) {
  42396. programs.forEach( function ( program ) {
  42397. programCache.releaseProgram( program );
  42398. } );
  42399. if ( material.isShaderMaterial ) {
  42400. programCache.releaseShaderCache( material );
  42401. }
  42402. }
  42403. }
  42404. // Buffer rendering
  42405. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  42406. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  42407. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  42408. const program = setProgram( camera, scene, geometry, material, object );
  42409. state.setMaterial( material, frontFaceCW );
  42410. //
  42411. let index = geometry.index;
  42412. let rangeFactor = 1;
  42413. if ( material.wireframe === true ) {
  42414. index = geometries.getWireframeAttribute( geometry );
  42415. if ( index === undefined ) return;
  42416. rangeFactor = 2;
  42417. }
  42418. //
  42419. const drawRange = geometry.drawRange;
  42420. const position = geometry.attributes.position;
  42421. let drawStart = drawRange.start * rangeFactor;
  42422. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  42423. if ( group !== null ) {
  42424. drawStart = Math.max( drawStart, group.start * rangeFactor );
  42425. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  42426. }
  42427. if ( index !== null ) {
  42428. drawStart = Math.max( drawStart, 0 );
  42429. drawEnd = Math.min( drawEnd, index.count );
  42430. } else if ( position !== undefined && position !== null ) {
  42431. drawStart = Math.max( drawStart, 0 );
  42432. drawEnd = Math.min( drawEnd, position.count );
  42433. }
  42434. const drawCount = drawEnd - drawStart;
  42435. if ( drawCount < 0 || drawCount === Infinity ) return;
  42436. //
  42437. bindingStates.setup( object, material, program, geometry, index );
  42438. let attribute;
  42439. let renderer = bufferRenderer;
  42440. if ( index !== null ) {
  42441. attribute = attributes.get( index );
  42442. renderer = indexedBufferRenderer;
  42443. renderer.setIndex( attribute );
  42444. }
  42445. //
  42446. if ( object.isMesh ) {
  42447. if ( material.wireframe === true ) {
  42448. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  42449. renderer.setMode( _gl.LINES );
  42450. } else {
  42451. renderer.setMode( _gl.TRIANGLES );
  42452. }
  42453. } else if ( object.isLine ) {
  42454. let lineWidth = material.linewidth;
  42455. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  42456. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  42457. if ( object.isLineSegments ) {
  42458. renderer.setMode( _gl.LINES );
  42459. } else if ( object.isLineLoop ) {
  42460. renderer.setMode( _gl.LINE_LOOP );
  42461. } else {
  42462. renderer.setMode( _gl.LINE_STRIP );
  42463. }
  42464. } else if ( object.isPoints ) {
  42465. renderer.setMode( _gl.POINTS );
  42466. } else if ( object.isSprite ) {
  42467. renderer.setMode( _gl.TRIANGLES );
  42468. }
  42469. if ( object.isBatchedMesh ) {
  42470. if ( object._multiDrawInstances !== null ) {
  42471. // @deprecated, r174
  42472. warnOnce( 'THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  42473. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  42474. } else {
  42475. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  42476. const starts = object._multiDrawStarts;
  42477. const counts = object._multiDrawCounts;
  42478. const drawCount = object._multiDrawCount;
  42479. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  42480. const uniforms = properties.get( material ).currentProgram.getUniforms();
  42481. for ( let i = 0; i < drawCount; i ++ ) {
  42482. uniforms.setValue( _gl, '_gl_DrawID', i );
  42483. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  42484. }
  42485. } else {
  42486. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  42487. }
  42488. }
  42489. } else if ( object.isInstancedMesh ) {
  42490. renderer.renderInstances( drawStart, drawCount, object.count );
  42491. } else if ( geometry.isInstancedBufferGeometry ) {
  42492. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  42493. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  42494. renderer.renderInstances( drawStart, drawCount, instanceCount );
  42495. } else {
  42496. renderer.render( drawStart, drawCount );
  42497. }
  42498. };
  42499. // Compile
  42500. function prepareMaterial( material, scene, object ) {
  42501. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  42502. material.side = BackSide;
  42503. material.needsUpdate = true;
  42504. getProgram( material, scene, object );
  42505. material.side = FrontSide;
  42506. material.needsUpdate = true;
  42507. getProgram( material, scene, object );
  42508. material.side = DoubleSide;
  42509. } else {
  42510. getProgram( material, scene, object );
  42511. }
  42512. }
  42513. this.compile = function ( scene, camera, targetScene = null ) {
  42514. if ( targetScene === null ) targetScene = scene;
  42515. currentRenderState = renderStates.get( targetScene );
  42516. currentRenderState.init( camera );
  42517. renderStateStack.push( currentRenderState );
  42518. // gather lights from both the target scene and the new object that will be added to the scene.
  42519. targetScene.traverseVisible( function ( object ) {
  42520. if ( object.isLight && object.layers.test( camera.layers ) ) {
  42521. currentRenderState.pushLight( object );
  42522. if ( object.castShadow ) {
  42523. currentRenderState.pushShadow( object );
  42524. }
  42525. }
  42526. } );
  42527. if ( scene !== targetScene ) {
  42528. scene.traverseVisible( function ( object ) {
  42529. if ( object.isLight && object.layers.test( camera.layers ) ) {
  42530. currentRenderState.pushLight( object );
  42531. if ( object.castShadow ) {
  42532. currentRenderState.pushShadow( object );
  42533. }
  42534. }
  42535. } );
  42536. }
  42537. currentRenderState.setupLights();
  42538. // Only initialize materials in the new scene, not the targetScene.
  42539. const materials = new Set();
  42540. scene.traverse( function ( object ) {
  42541. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  42542. return;
  42543. }
  42544. const material = object.material;
  42545. if ( material ) {
  42546. if ( Array.isArray( material ) ) {
  42547. for ( let i = 0; i < material.length; i ++ ) {
  42548. const material2 = material[ i ];
  42549. prepareMaterial( material2, targetScene, object );
  42550. materials.add( material2 );
  42551. }
  42552. } else {
  42553. prepareMaterial( material, targetScene, object );
  42554. materials.add( material );
  42555. }
  42556. }
  42557. } );
  42558. currentRenderState = renderStateStack.pop();
  42559. return materials;
  42560. };
  42561. // compileAsync
  42562. this.compileAsync = function ( scene, camera, targetScene = null ) {
  42563. const materials = this.compile( scene, camera, targetScene );
  42564. // Wait for all the materials in the new object to indicate that they're
  42565. // ready to be used before resolving the promise.
  42566. return new Promise( ( resolve ) => {
  42567. function checkMaterialsReady() {
  42568. materials.forEach( function ( material ) {
  42569. const materialProperties = properties.get( material );
  42570. const program = materialProperties.currentProgram;
  42571. if ( program.isReady() ) {
  42572. // remove any programs that report they're ready to use from the list
  42573. materials.delete( material );
  42574. }
  42575. } );
  42576. // once the list of compiling materials is empty, call the callback
  42577. if ( materials.size === 0 ) {
  42578. resolve( scene );
  42579. return;
  42580. }
  42581. // if some materials are still not ready, wait a bit and check again
  42582. setTimeout( checkMaterialsReady, 10 );
  42583. }
  42584. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  42585. // If we can check the compilation status of the materials without
  42586. // blocking then do so right away.
  42587. checkMaterialsReady();
  42588. } else {
  42589. // Otherwise start by waiting a bit to give the materials we just
  42590. // initialized a chance to finish.
  42591. setTimeout( checkMaterialsReady, 10 );
  42592. }
  42593. } );
  42594. };
  42595. // Animation Loop
  42596. let onAnimationFrameCallback = null;
  42597. function onAnimationFrame( time ) {
  42598. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  42599. }
  42600. function onXRSessionStart() {
  42601. animation.stop();
  42602. }
  42603. function onXRSessionEnd() {
  42604. animation.start();
  42605. }
  42606. const animation = new WebGLAnimation();
  42607. animation.setAnimationLoop( onAnimationFrame );
  42608. if ( typeof self !== 'undefined' ) animation.setContext( self );
  42609. this.setAnimationLoop = function ( callback ) {
  42610. onAnimationFrameCallback = callback;
  42611. xr.setAnimationLoop( callback );
  42612. ( callback === null ) ? animation.stop() : animation.start();
  42613. };
  42614. xr.addEventListener( 'sessionstart', onXRSessionStart );
  42615. xr.addEventListener( 'sessionend', onXRSessionEnd );
  42616. // Rendering
  42617. this.render = function ( scene, camera ) {
  42618. if ( camera !== undefined && camera.isCamera !== true ) {
  42619. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  42620. return;
  42621. }
  42622. if ( _isContextLost === true ) return;
  42623. // update scene graph
  42624. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  42625. // update camera matrices and frustum
  42626. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  42627. if ( xr.enabled === true && xr.isPresenting === true ) {
  42628. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  42629. camera = xr.getCamera(); // use XR camera for rendering
  42630. }
  42631. //
  42632. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  42633. currentRenderState = renderStates.get( scene, renderStateStack.length );
  42634. currentRenderState.init( camera );
  42635. renderStateStack.push( currentRenderState );
  42636. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  42637. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  42638. _localClippingEnabled = this.localClippingEnabled;
  42639. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  42640. currentRenderList = renderLists.get( scene, renderListStack.length );
  42641. currentRenderList.init();
  42642. renderListStack.push( currentRenderList );
  42643. if ( xr.enabled === true && xr.isPresenting === true ) {
  42644. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  42645. if ( depthSensingMesh !== null ) {
  42646. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  42647. }
  42648. }
  42649. projectObject( scene, camera, 0, _this.sortObjects );
  42650. currentRenderList.finish();
  42651. if ( _this.sortObjects === true ) {
  42652. currentRenderList.sort( _opaqueSort, _transparentSort );
  42653. }
  42654. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  42655. if ( _renderBackground ) {
  42656. background.addToRenderList( currentRenderList, scene );
  42657. }
  42658. //
  42659. this.info.render.frame ++;
  42660. if ( _clippingEnabled === true ) clipping.beginShadows();
  42661. const shadowsArray = currentRenderState.state.shadowsArray;
  42662. shadowMap.render( shadowsArray, scene, camera );
  42663. if ( _clippingEnabled === true ) clipping.endShadows();
  42664. //
  42665. if ( this.info.autoReset === true ) this.info.reset();
  42666. // render scene
  42667. const opaqueObjects = currentRenderList.opaque;
  42668. const transmissiveObjects = currentRenderList.transmissive;
  42669. currentRenderState.setupLights();
  42670. if ( camera.isArrayCamera ) {
  42671. const cameras = camera.cameras;
  42672. if ( transmissiveObjects.length > 0 ) {
  42673. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  42674. const camera2 = cameras[ i ];
  42675. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  42676. }
  42677. }
  42678. if ( _renderBackground ) background.render( scene );
  42679. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  42680. const camera2 = cameras[ i ];
  42681. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  42682. }
  42683. } else {
  42684. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  42685. if ( _renderBackground ) background.render( scene );
  42686. renderScene( currentRenderList, scene, camera );
  42687. }
  42688. //
  42689. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  42690. // resolve multisample renderbuffers to a single-sample texture if necessary
  42691. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  42692. // Generate mipmap if we're using any kind of mipmap filtering
  42693. textures.updateRenderTargetMipmap( _currentRenderTarget );
  42694. }
  42695. //
  42696. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  42697. // _gl.finish();
  42698. bindingStates.resetDefaultState();
  42699. _currentMaterialId = -1;
  42700. _currentCamera = null;
  42701. renderStateStack.pop();
  42702. if ( renderStateStack.length > 0 ) {
  42703. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  42704. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  42705. } else {
  42706. currentRenderState = null;
  42707. }
  42708. renderListStack.pop();
  42709. if ( renderListStack.length > 0 ) {
  42710. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  42711. } else {
  42712. currentRenderList = null;
  42713. }
  42714. };
  42715. function projectObject( object, camera, groupOrder, sortObjects ) {
  42716. if ( object.visible === false ) return;
  42717. const visible = object.layers.test( camera.layers );
  42718. if ( visible ) {
  42719. if ( object.isGroup ) {
  42720. groupOrder = object.renderOrder;
  42721. } else if ( object.isLOD ) {
  42722. if ( object.autoUpdate === true ) object.update( camera );
  42723. } else if ( object.isLight ) {
  42724. currentRenderState.pushLight( object );
  42725. if ( object.castShadow ) {
  42726. currentRenderState.pushShadow( object );
  42727. }
  42728. } else if ( object.isSprite ) {
  42729. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  42730. if ( sortObjects ) {
  42731. _vector4.setFromMatrixPosition( object.matrixWorld )
  42732. .applyMatrix4( _projScreenMatrix );
  42733. }
  42734. const geometry = objects.update( object );
  42735. const material = object.material;
  42736. if ( material.visible ) {
  42737. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  42738. }
  42739. }
  42740. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  42741. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  42742. const geometry = objects.update( object );
  42743. const material = object.material;
  42744. if ( sortObjects ) {
  42745. if ( object.boundingSphere !== undefined ) {
  42746. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  42747. _vector4.copy( object.boundingSphere.center );
  42748. } else {
  42749. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  42750. _vector4.copy( geometry.boundingSphere.center );
  42751. }
  42752. _vector4
  42753. .applyMatrix4( object.matrixWorld )
  42754. .applyMatrix4( _projScreenMatrix );
  42755. }
  42756. if ( Array.isArray( material ) ) {
  42757. const groups = geometry.groups;
  42758. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  42759. const group = groups[ i ];
  42760. const groupMaterial = material[ group.materialIndex ];
  42761. if ( groupMaterial && groupMaterial.visible ) {
  42762. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  42763. }
  42764. }
  42765. } else if ( material.visible ) {
  42766. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  42767. }
  42768. }
  42769. }
  42770. }
  42771. const children = object.children;
  42772. for ( let i = 0, l = children.length; i < l; i ++ ) {
  42773. projectObject( children[ i ], camera, groupOrder, sortObjects );
  42774. }
  42775. }
  42776. function renderScene( currentRenderList, scene, camera, viewport ) {
  42777. const opaqueObjects = currentRenderList.opaque;
  42778. const transmissiveObjects = currentRenderList.transmissive;
  42779. const transparentObjects = currentRenderList.transparent;
  42780. currentRenderState.setupLightsView( camera );
  42781. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  42782. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  42783. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  42784. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  42785. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  42786. // Ensure depth buffer writing is enabled so it can be cleared on next render
  42787. state.buffers.depth.setTest( true );
  42788. state.buffers.depth.setMask( true );
  42789. state.buffers.color.setMask( true );
  42790. state.setPolygonOffset( false );
  42791. }
  42792. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  42793. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  42794. if ( overrideMaterial !== null ) {
  42795. return;
  42796. }
  42797. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  42798. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  42799. generateMipmaps: true,
  42800. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  42801. minFilter: LinearMipmapLinearFilter,
  42802. samples: 4,
  42803. stencilBuffer: stencil,
  42804. resolveDepthBuffer: false,
  42805. resolveStencilBuffer: false,
  42806. colorSpace: ColorManagement.workingColorSpace,
  42807. } );
  42808. // debug
  42809. /*
  42810. const geometry = new PlaneGeometry();
  42811. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  42812. const mesh = new Mesh( geometry, material );
  42813. scene.add( mesh );
  42814. */
  42815. }
  42816. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  42817. const activeViewport = camera.viewport || _currentViewport;
  42818. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  42819. //
  42820. const currentRenderTarget = _this.getRenderTarget();
  42821. _this.setRenderTarget( transmissionRenderTarget );
  42822. _this.getClearColor( _currentClearColor );
  42823. _currentClearAlpha = _this.getClearAlpha();
  42824. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  42825. _this.clear();
  42826. if ( _renderBackground ) background.render( scene );
  42827. // Turn off the features which can affect the frag color for opaque objects pass.
  42828. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  42829. const currentToneMapping = _this.toneMapping;
  42830. _this.toneMapping = NoToneMapping;
  42831. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  42832. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  42833. const currentCameraViewport = camera.viewport;
  42834. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  42835. currentRenderState.setupLightsView( camera );
  42836. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  42837. renderObjects( opaqueObjects, scene, camera );
  42838. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  42839. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  42840. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  42841. let renderTargetNeedsUpdate = false;
  42842. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  42843. const renderItem = transmissiveObjects[ i ];
  42844. const object = renderItem.object;
  42845. const geometry = renderItem.geometry;
  42846. const material = renderItem.material;
  42847. const group = renderItem.group;
  42848. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  42849. const currentSide = material.side;
  42850. material.side = BackSide;
  42851. material.needsUpdate = true;
  42852. renderObject( object, scene, camera, geometry, material, group );
  42853. material.side = currentSide;
  42854. material.needsUpdate = true;
  42855. renderTargetNeedsUpdate = true;
  42856. }
  42857. }
  42858. if ( renderTargetNeedsUpdate === true ) {
  42859. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  42860. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  42861. }
  42862. }
  42863. _this.setRenderTarget( currentRenderTarget );
  42864. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  42865. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  42866. _this.toneMapping = currentToneMapping;
  42867. }
  42868. function renderObjects( renderList, scene, camera ) {
  42869. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  42870. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  42871. const renderItem = renderList[ i ];
  42872. const object = renderItem.object;
  42873. const geometry = renderItem.geometry;
  42874. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  42875. const group = renderItem.group;
  42876. if ( object.layers.test( camera.layers ) ) {
  42877. renderObject( object, scene, camera, geometry, material, group );
  42878. }
  42879. }
  42880. }
  42881. function renderObject( object, scene, camera, geometry, material, group ) {
  42882. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  42883. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  42884. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  42885. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  42886. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  42887. material.side = BackSide;
  42888. material.needsUpdate = true;
  42889. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  42890. material.side = FrontSide;
  42891. material.needsUpdate = true;
  42892. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  42893. material.side = DoubleSide;
  42894. } else {
  42895. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  42896. }
  42897. object.onAfterRender( _this, scene, camera, geometry, material, group );
  42898. }
  42899. function getProgram( material, scene, object ) {
  42900. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  42901. const materialProperties = properties.get( material );
  42902. const lights = currentRenderState.state.lights;
  42903. const shadowsArray = currentRenderState.state.shadowsArray;
  42904. const lightsStateVersion = lights.state.version;
  42905. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  42906. const programCacheKey = programCache.getProgramCacheKey( parameters );
  42907. let programs = materialProperties.programs;
  42908. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  42909. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  42910. materialProperties.fog = scene.fog;
  42911. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  42912. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  42913. if ( programs === undefined ) {
  42914. // new material
  42915. material.addEventListener( 'dispose', onMaterialDispose );
  42916. programs = new Map();
  42917. materialProperties.programs = programs;
  42918. }
  42919. let program = programs.get( programCacheKey );
  42920. if ( program !== undefined ) {
  42921. // early out if program and light state is identical
  42922. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  42923. updateCommonMaterialProperties( material, parameters );
  42924. return program;
  42925. }
  42926. } else {
  42927. parameters.uniforms = programCache.getUniforms( material );
  42928. material.onBeforeCompile( parameters, _this );
  42929. program = programCache.acquireProgram( parameters, programCacheKey );
  42930. programs.set( programCacheKey, program );
  42931. materialProperties.uniforms = parameters.uniforms;
  42932. }
  42933. const uniforms = materialProperties.uniforms;
  42934. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  42935. uniforms.clippingPlanes = clipping.uniform;
  42936. }
  42937. updateCommonMaterialProperties( material, parameters );
  42938. // store the light setup it was created for
  42939. materialProperties.needsLights = materialNeedsLights( material );
  42940. materialProperties.lightsStateVersion = lightsStateVersion;
  42941. if ( materialProperties.needsLights ) {
  42942. // wire up the material to this renderer's lighting state
  42943. uniforms.ambientLightColor.value = lights.state.ambient;
  42944. uniforms.lightProbe.value = lights.state.probe;
  42945. uniforms.directionalLights.value = lights.state.directional;
  42946. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  42947. uniforms.spotLights.value = lights.state.spot;
  42948. uniforms.spotLightShadows.value = lights.state.spotShadow;
  42949. uniforms.rectAreaLights.value = lights.state.rectArea;
  42950. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  42951. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  42952. uniforms.pointLights.value = lights.state.point;
  42953. uniforms.pointLightShadows.value = lights.state.pointShadow;
  42954. uniforms.hemisphereLights.value = lights.state.hemi;
  42955. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  42956. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  42957. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  42958. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  42959. uniforms.spotLightMap.value = lights.state.spotLightMap;
  42960. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  42961. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  42962. // TODO (abelnation): add area lights shadow info to uniforms
  42963. }
  42964. materialProperties.currentProgram = program;
  42965. materialProperties.uniformsList = null;
  42966. return program;
  42967. }
  42968. function getUniformList( materialProperties ) {
  42969. if ( materialProperties.uniformsList === null ) {
  42970. const progUniforms = materialProperties.currentProgram.getUniforms();
  42971. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  42972. }
  42973. return materialProperties.uniformsList;
  42974. }
  42975. function updateCommonMaterialProperties( material, parameters ) {
  42976. const materialProperties = properties.get( material );
  42977. materialProperties.outputColorSpace = parameters.outputColorSpace;
  42978. materialProperties.batching = parameters.batching;
  42979. materialProperties.batchingColor = parameters.batchingColor;
  42980. materialProperties.instancing = parameters.instancing;
  42981. materialProperties.instancingColor = parameters.instancingColor;
  42982. materialProperties.instancingMorph = parameters.instancingMorph;
  42983. materialProperties.skinning = parameters.skinning;
  42984. materialProperties.morphTargets = parameters.morphTargets;
  42985. materialProperties.morphNormals = parameters.morphNormals;
  42986. materialProperties.morphColors = parameters.morphColors;
  42987. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  42988. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  42989. materialProperties.numIntersection = parameters.numClipIntersection;
  42990. materialProperties.vertexAlphas = parameters.vertexAlphas;
  42991. materialProperties.vertexTangents = parameters.vertexTangents;
  42992. materialProperties.toneMapping = parameters.toneMapping;
  42993. }
  42994. function setProgram( camera, scene, geometry, material, object ) {
  42995. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  42996. textures.resetTextureUnits();
  42997. const fog = scene.fog;
  42998. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  42999. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  43000. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  43001. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  43002. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  43003. const morphTargets = !! geometry.morphAttributes.position;
  43004. const morphNormals = !! geometry.morphAttributes.normal;
  43005. const morphColors = !! geometry.morphAttributes.color;
  43006. let toneMapping = NoToneMapping;
  43007. if ( material.toneMapped ) {
  43008. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  43009. toneMapping = _this.toneMapping;
  43010. }
  43011. }
  43012. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  43013. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  43014. const materialProperties = properties.get( material );
  43015. const lights = currentRenderState.state.lights;
  43016. if ( _clippingEnabled === true ) {
  43017. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  43018. const useCache =
  43019. camera === _currentCamera &&
  43020. material.id === _currentMaterialId;
  43021. // we might want to call this function with some ClippingGroup
  43022. // object instead of the material, once it becomes feasible
  43023. // (#8465, #8379)
  43024. clipping.setState( material, camera, useCache );
  43025. }
  43026. }
  43027. //
  43028. let needsProgramChange = false;
  43029. if ( material.version === materialProperties.__version ) {
  43030. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  43031. needsProgramChange = true;
  43032. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  43033. needsProgramChange = true;
  43034. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  43035. needsProgramChange = true;
  43036. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  43037. needsProgramChange = true;
  43038. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  43039. needsProgramChange = true;
  43040. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  43041. needsProgramChange = true;
  43042. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  43043. needsProgramChange = true;
  43044. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  43045. needsProgramChange = true;
  43046. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  43047. needsProgramChange = true;
  43048. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  43049. needsProgramChange = true;
  43050. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  43051. needsProgramChange = true;
  43052. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  43053. needsProgramChange = true;
  43054. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  43055. needsProgramChange = true;
  43056. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  43057. needsProgramChange = true;
  43058. } else if ( materialProperties.envMap !== envMap ) {
  43059. needsProgramChange = true;
  43060. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  43061. needsProgramChange = true;
  43062. } else if ( materialProperties.numClippingPlanes !== undefined &&
  43063. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  43064. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  43065. needsProgramChange = true;
  43066. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  43067. needsProgramChange = true;
  43068. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  43069. needsProgramChange = true;
  43070. } else if ( materialProperties.morphTargets !== morphTargets ) {
  43071. needsProgramChange = true;
  43072. } else if ( materialProperties.morphNormals !== morphNormals ) {
  43073. needsProgramChange = true;
  43074. } else if ( materialProperties.morphColors !== morphColors ) {
  43075. needsProgramChange = true;
  43076. } else if ( materialProperties.toneMapping !== toneMapping ) {
  43077. needsProgramChange = true;
  43078. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  43079. needsProgramChange = true;
  43080. }
  43081. } else {
  43082. needsProgramChange = true;
  43083. materialProperties.__version = material.version;
  43084. }
  43085. //
  43086. let program = materialProperties.currentProgram;
  43087. if ( needsProgramChange === true ) {
  43088. program = getProgram( material, scene, object );
  43089. }
  43090. let refreshProgram = false;
  43091. let refreshMaterial = false;
  43092. let refreshLights = false;
  43093. const p_uniforms = program.getUniforms(),
  43094. m_uniforms = materialProperties.uniforms;
  43095. if ( state.useProgram( program.program ) ) {
  43096. refreshProgram = true;
  43097. refreshMaterial = true;
  43098. refreshLights = true;
  43099. }
  43100. if ( material.id !== _currentMaterialId ) {
  43101. _currentMaterialId = material.id;
  43102. refreshMaterial = true;
  43103. }
  43104. if ( refreshProgram || _currentCamera !== camera ) {
  43105. // common camera uniforms
  43106. const reverseDepthBuffer = state.buffers.depth.getReversed();
  43107. if ( reverseDepthBuffer ) {
  43108. _currentProjectionMatrix.copy( camera.projectionMatrix );
  43109. toNormalizedProjectionMatrix( _currentProjectionMatrix );
  43110. toReversedProjectionMatrix( _currentProjectionMatrix );
  43111. p_uniforms.setValue( _gl, 'projectionMatrix', _currentProjectionMatrix );
  43112. } else {
  43113. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  43114. }
  43115. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  43116. const uCamPos = p_uniforms.map.cameraPosition;
  43117. if ( uCamPos !== undefined ) {
  43118. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  43119. }
  43120. if ( capabilities.logarithmicDepthBuffer ) {
  43121. p_uniforms.setValue( _gl, 'logDepthBufFC',
  43122. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  43123. }
  43124. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  43125. if ( material.isMeshPhongMaterial ||
  43126. material.isMeshToonMaterial ||
  43127. material.isMeshLambertMaterial ||
  43128. material.isMeshBasicMaterial ||
  43129. material.isMeshStandardMaterial ||
  43130. material.isShaderMaterial ) {
  43131. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  43132. }
  43133. if ( _currentCamera !== camera ) {
  43134. _currentCamera = camera;
  43135. // lighting uniforms depend on the camera so enforce an update
  43136. // now, in case this material supports lights - or later, when
  43137. // the next material that does gets activated:
  43138. refreshMaterial = true; // set to true on material change
  43139. refreshLights = true; // remains set until update done
  43140. }
  43141. }
  43142. // skinning and morph target uniforms must be set even if material didn't change
  43143. // auto-setting of texture unit for bone and morph texture must go before other textures
  43144. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  43145. if ( object.isSkinnedMesh ) {
  43146. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  43147. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  43148. const skeleton = object.skeleton;
  43149. if ( skeleton ) {
  43150. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  43151. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  43152. }
  43153. }
  43154. if ( object.isBatchedMesh ) {
  43155. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  43156. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  43157. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  43158. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  43159. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  43160. if ( object._colorsTexture !== null ) {
  43161. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  43162. }
  43163. }
  43164. const morphAttributes = geometry.morphAttributes;
  43165. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  43166. morphtargets.update( object, geometry, program );
  43167. }
  43168. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  43169. materialProperties.receiveShadow = object.receiveShadow;
  43170. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  43171. }
  43172. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  43173. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  43174. m_uniforms.envMap.value = envMap;
  43175. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  43176. }
  43177. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  43178. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  43179. }
  43180. if ( refreshMaterial ) {
  43181. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  43182. if ( materialProperties.needsLights ) {
  43183. // the current material requires lighting info
  43184. // note: all lighting uniforms are always set correctly
  43185. // they simply reference the renderer's state for their
  43186. // values
  43187. //
  43188. // use the current material's .needsUpdate flags to set
  43189. // the GL state when required
  43190. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  43191. }
  43192. // refresh uniforms common to several materials
  43193. if ( fog && material.fog === true ) {
  43194. materials.refreshFogUniforms( m_uniforms, fog );
  43195. }
  43196. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  43197. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  43198. }
  43199. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  43200. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  43201. material.uniformsNeedUpdate = false;
  43202. }
  43203. if ( material.isSpriteMaterial ) {
  43204. p_uniforms.setValue( _gl, 'center', object.center );
  43205. }
  43206. // common matrices
  43207. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  43208. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  43209. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  43210. // UBOs
  43211. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  43212. const groups = material.uniformsGroups;
  43213. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  43214. const group = groups[ i ];
  43215. uniformsGroups.update( group, program );
  43216. uniformsGroups.bind( group, program );
  43217. }
  43218. }
  43219. return program;
  43220. }
  43221. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  43222. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  43223. uniforms.ambientLightColor.needsUpdate = value;
  43224. uniforms.lightProbe.needsUpdate = value;
  43225. uniforms.directionalLights.needsUpdate = value;
  43226. uniforms.directionalLightShadows.needsUpdate = value;
  43227. uniforms.pointLights.needsUpdate = value;
  43228. uniforms.pointLightShadows.needsUpdate = value;
  43229. uniforms.spotLights.needsUpdate = value;
  43230. uniforms.spotLightShadows.needsUpdate = value;
  43231. uniforms.rectAreaLights.needsUpdate = value;
  43232. uniforms.hemisphereLights.needsUpdate = value;
  43233. }
  43234. function materialNeedsLights( material ) {
  43235. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  43236. material.isMeshStandardMaterial || material.isShadowMaterial ||
  43237. ( material.isShaderMaterial && material.lights === true );
  43238. }
  43239. this.getActiveCubeFace = function () {
  43240. return _currentActiveCubeFace;
  43241. };
  43242. this.getActiveMipmapLevel = function () {
  43243. return _currentActiveMipmapLevel;
  43244. };
  43245. this.getRenderTarget = function () {
  43246. return _currentRenderTarget;
  43247. };
  43248. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  43249. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  43250. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  43251. const renderTargetProperties = properties.get( renderTarget );
  43252. renderTargetProperties.__hasExternalTextures = true;
  43253. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  43254. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  43255. // The multisample_render_to_texture extension doesn't work properly if there
  43256. // are midframe flushes and an external depth buffer. Disable use of the extension.
  43257. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  43258. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  43259. renderTargetProperties.__useRenderToTexture = false;
  43260. }
  43261. }
  43262. };
  43263. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  43264. const renderTargetProperties = properties.get( renderTarget );
  43265. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  43266. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  43267. };
  43268. const _scratchFrameBuffer = _gl.createFramebuffer();
  43269. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  43270. _currentRenderTarget = renderTarget;
  43271. _currentActiveCubeFace = activeCubeFace;
  43272. _currentActiveMipmapLevel = activeMipmapLevel;
  43273. let useDefaultFramebuffer = true;
  43274. let framebuffer = null;
  43275. let isCube = false;
  43276. let isRenderTarget3D = false;
  43277. if ( renderTarget ) {
  43278. const renderTargetProperties = properties.get( renderTarget );
  43279. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  43280. // We need to make sure to rebind the framebuffer.
  43281. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  43282. useDefaultFramebuffer = false;
  43283. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  43284. textures.setupRenderTarget( renderTarget );
  43285. } else if ( renderTargetProperties.__hasExternalTextures ) {
  43286. // Color and depth texture must be rebound in order for the swapchain to update.
  43287. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  43288. } else if ( renderTarget.depthBuffer ) {
  43289. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  43290. const depthTexture = renderTarget.depthTexture;
  43291. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  43292. // check if the depth texture is compatible
  43293. if (
  43294. depthTexture !== null &&
  43295. properties.has( depthTexture ) &&
  43296. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  43297. ) {
  43298. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  43299. }
  43300. // Swap the depth buffer to the currently attached one
  43301. textures.setupDepthRenderbuffer( renderTarget );
  43302. }
  43303. }
  43304. const texture = renderTarget.texture;
  43305. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  43306. isRenderTarget3D = true;
  43307. }
  43308. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  43309. if ( renderTarget.isWebGLCubeRenderTarget ) {
  43310. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  43311. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  43312. } else {
  43313. framebuffer = __webglFramebuffer[ activeCubeFace ];
  43314. }
  43315. isCube = true;
  43316. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  43317. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  43318. } else {
  43319. if ( Array.isArray( __webglFramebuffer ) ) {
  43320. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  43321. } else {
  43322. framebuffer = __webglFramebuffer;
  43323. }
  43324. }
  43325. _currentViewport.copy( renderTarget.viewport );
  43326. _currentScissor.copy( renderTarget.scissor );
  43327. _currentScissorTest = renderTarget.scissorTest;
  43328. } else {
  43329. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  43330. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  43331. _currentScissorTest = _scissorTest;
  43332. }
  43333. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  43334. // being bound that are different sizes.
  43335. if ( activeMipmapLevel !== 0 ) {
  43336. framebuffer = _scratchFrameBuffer;
  43337. }
  43338. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  43339. if ( framebufferBound && useDefaultFramebuffer ) {
  43340. state.drawBuffers( renderTarget, framebuffer );
  43341. }
  43342. state.viewport( _currentViewport );
  43343. state.scissor( _currentScissor );
  43344. state.setScissorTest( _currentScissorTest );
  43345. if ( isCube ) {
  43346. const textureProperties = properties.get( renderTarget.texture );
  43347. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  43348. } else if ( isRenderTarget3D ) {
  43349. const textureProperties = properties.get( renderTarget.texture );
  43350. const layer = activeCubeFace;
  43351. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer );
  43352. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  43353. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  43354. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  43355. const textureProperties = properties.get( renderTarget.texture );
  43356. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  43357. }
  43358. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  43359. };
  43360. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  43361. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  43362. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  43363. return;
  43364. }
  43365. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  43366. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  43367. framebuffer = framebuffer[ activeCubeFaceIndex ];
  43368. }
  43369. if ( framebuffer ) {
  43370. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  43371. try {
  43372. const texture = renderTarget.texture;
  43373. const textureFormat = texture.format;
  43374. const textureType = texture.type;
  43375. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  43376. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  43377. return;
  43378. }
  43379. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  43380. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  43381. return;
  43382. }
  43383. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  43384. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  43385. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  43386. }
  43387. } finally {
  43388. // restore framebuffer of current render target if necessary
  43389. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  43390. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  43391. }
  43392. }
  43393. };
  43394. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  43395. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  43396. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  43397. }
  43398. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  43399. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  43400. framebuffer = framebuffer[ activeCubeFaceIndex ];
  43401. }
  43402. if ( framebuffer ) {
  43403. const texture = renderTarget.texture;
  43404. const textureFormat = texture.format;
  43405. const textureType = texture.type;
  43406. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  43407. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  43408. }
  43409. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  43410. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  43411. }
  43412. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  43413. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  43414. // set the active frame buffer to the one we want to read
  43415. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  43416. const glBuffer = _gl.createBuffer();
  43417. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  43418. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  43419. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  43420. // reset the frame buffer to the currently set buffer before waiting
  43421. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  43422. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  43423. // check if the commands have finished every 8 ms
  43424. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  43425. _gl.flush();
  43426. await probeAsync( _gl, sync, 4 );
  43427. // read the data and delete the buffer
  43428. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  43429. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  43430. _gl.deleteBuffer( glBuffer );
  43431. _gl.deleteSync( sync );
  43432. return buffer;
  43433. } else {
  43434. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  43435. }
  43436. }
  43437. };
  43438. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  43439. // support previous signature with position first
  43440. if ( texture.isTexture !== true ) {
  43441. // @deprecated, r165
  43442. warnOnce( 'WebGLRenderer: copyFramebufferToTexture function signature has changed.' );
  43443. position = arguments[ 0 ] || null;
  43444. texture = arguments[ 1 ];
  43445. }
  43446. const levelScale = Math.pow( 2, - level );
  43447. const width = Math.floor( texture.image.width * levelScale );
  43448. const height = Math.floor( texture.image.height * levelScale );
  43449. const x = position !== null ? position.x : 0;
  43450. const y = position !== null ? position.y : 0;
  43451. textures.setTexture2D( texture, 0 );
  43452. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  43453. state.unbindTexture();
  43454. };
  43455. const _srcFramebuffer = _gl.createFramebuffer();
  43456. const _dstFramebuffer = _gl.createFramebuffer();
  43457. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  43458. // support previous signature with dstPosition first
  43459. if ( srcTexture.isTexture !== true ) {
  43460. // @deprecated, r165
  43461. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed.' );
  43462. dstPosition = arguments[ 0 ] || null;
  43463. srcTexture = arguments[ 1 ];
  43464. dstTexture = arguments[ 2 ];
  43465. dstLevel = arguments[ 3 ] || 0;
  43466. srcRegion = null;
  43467. }
  43468. // support the previous signature with just a single dst mipmap level
  43469. if ( dstLevel === null ) {
  43470. if ( srcLevel !== 0 ) {
  43471. // @deprecated, r171
  43472. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  43473. dstLevel = srcLevel;
  43474. srcLevel = 0;
  43475. } else {
  43476. dstLevel = 0;
  43477. }
  43478. }
  43479. // gather the necessary dimensions to copy
  43480. let width, height, depth, minX, minY, minZ;
  43481. let dstX, dstY, dstZ;
  43482. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  43483. if ( srcRegion !== null ) {
  43484. width = srcRegion.max.x - srcRegion.min.x;
  43485. height = srcRegion.max.y - srcRegion.min.y;
  43486. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  43487. minX = srcRegion.min.x;
  43488. minY = srcRegion.min.y;
  43489. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  43490. } else {
  43491. const levelScale = Math.pow( 2, - srcLevel );
  43492. width = Math.floor( image.width * levelScale );
  43493. height = Math.floor( image.height * levelScale );
  43494. if ( srcTexture.isDataArrayTexture ) {
  43495. depth = image.depth;
  43496. } else if ( srcTexture.isData3DTexture ) {
  43497. depth = Math.floor( image.depth * levelScale );
  43498. } else {
  43499. depth = 1;
  43500. }
  43501. minX = 0;
  43502. minY = 0;
  43503. minZ = 0;
  43504. }
  43505. if ( dstPosition !== null ) {
  43506. dstX = dstPosition.x;
  43507. dstY = dstPosition.y;
  43508. dstZ = dstPosition.z;
  43509. } else {
  43510. dstX = 0;
  43511. dstY = 0;
  43512. dstZ = 0;
  43513. }
  43514. // Set up the destination target
  43515. const glFormat = utils.convert( dstTexture.format );
  43516. const glType = utils.convert( dstTexture.type );
  43517. let glTarget;
  43518. if ( dstTexture.isData3DTexture ) {
  43519. textures.setTexture3D( dstTexture, 0 );
  43520. glTarget = _gl.TEXTURE_3D;
  43521. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  43522. textures.setTexture2DArray( dstTexture, 0 );
  43523. glTarget = _gl.TEXTURE_2D_ARRAY;
  43524. } else {
  43525. textures.setTexture2D( dstTexture, 0 );
  43526. glTarget = _gl.TEXTURE_2D;
  43527. }
  43528. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  43529. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  43530. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  43531. // used for copying data from cpu
  43532. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  43533. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  43534. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  43535. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  43536. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  43537. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  43538. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  43539. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  43540. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  43541. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  43542. // set up the src texture
  43543. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  43544. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  43545. if ( srcTexture.isDepthTexture ) {
  43546. const srcTextureProperties = properties.get( srcTexture );
  43547. const dstTextureProperties = properties.get( dstTexture );
  43548. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  43549. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  43550. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  43551. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  43552. for ( let i = 0; i < depth; i ++ ) {
  43553. // if the source or destination are a 3d target then a layer needs to be bound
  43554. if ( isSrc3D ) {
  43555. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  43556. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  43557. }
  43558. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  43559. }
  43560. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  43561. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  43562. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  43563. // get the appropriate frame buffers
  43564. const srcTextureProperties = properties.get( srcTexture );
  43565. const dstTextureProperties = properties.get( dstTexture );
  43566. // bind the frame buffer targets
  43567. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  43568. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  43569. for ( let i = 0; i < depth; i ++ ) {
  43570. // assign the correct layers and mip maps to the frame buffers
  43571. if ( isSrc3D ) {
  43572. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  43573. } else {
  43574. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  43575. }
  43576. if ( isDst3D ) {
  43577. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  43578. } else {
  43579. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  43580. }
  43581. // copy the data using the fastest function that can achieve the copy
  43582. if ( srcLevel !== 0 ) {
  43583. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  43584. } else if ( isDst3D ) {
  43585. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  43586. } else {
  43587. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  43588. }
  43589. }
  43590. // unbind read, draw buffers
  43591. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  43592. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  43593. } else {
  43594. if ( isDst3D ) {
  43595. // copy data into the 3d texture
  43596. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  43597. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  43598. } else if ( dstTexture.isCompressedArrayTexture ) {
  43599. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  43600. } else {
  43601. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  43602. }
  43603. } else {
  43604. // copy data into the 2d texture
  43605. if ( srcTexture.isDataTexture ) {
  43606. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  43607. } else if ( srcTexture.isCompressedTexture ) {
  43608. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  43609. } else {
  43610. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  43611. }
  43612. }
  43613. }
  43614. // reset values
  43615. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  43616. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  43617. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  43618. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  43619. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  43620. // Generate mipmaps only when copying level 0
  43621. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  43622. _gl.generateMipmap( glTarget );
  43623. }
  43624. state.unbindTexture();
  43625. };
  43626. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  43627. // support previous signature with source box first
  43628. if ( srcTexture.isTexture !== true ) {
  43629. // @deprecated, r165
  43630. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function signature has changed.' );
  43631. srcRegion = arguments[ 0 ] || null;
  43632. dstPosition = arguments[ 1 ] || null;
  43633. srcTexture = arguments[ 2 ];
  43634. dstTexture = arguments[ 3 ];
  43635. level = arguments[ 4 ] || 0;
  43636. }
  43637. // @deprecated, r170
  43638. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.' );
  43639. return this.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  43640. };
  43641. this.initRenderTarget = function ( target ) {
  43642. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  43643. textures.setupRenderTarget( target );
  43644. }
  43645. };
  43646. this.initTexture = function ( texture ) {
  43647. if ( texture.isCubeTexture ) {
  43648. textures.setTextureCube( texture, 0 );
  43649. } else if ( texture.isData3DTexture ) {
  43650. textures.setTexture3D( texture, 0 );
  43651. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  43652. textures.setTexture2DArray( texture, 0 );
  43653. } else {
  43654. textures.setTexture2D( texture, 0 );
  43655. }
  43656. state.unbindTexture();
  43657. };
  43658. this.resetState = function () {
  43659. _currentActiveCubeFace = 0;
  43660. _currentActiveMipmapLevel = 0;
  43661. _currentRenderTarget = null;
  43662. state.reset();
  43663. bindingStates.reset();
  43664. };
  43665. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43666. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  43667. }
  43668. }
  43669. get coordinateSystem() {
  43670. return WebGLCoordinateSystem;
  43671. }
  43672. get outputColorSpace() {
  43673. return this._outputColorSpace;
  43674. }
  43675. set outputColorSpace( colorSpace ) {
  43676. this._outputColorSpace = colorSpace;
  43677. const gl = this.getContext();
  43678. gl.drawingBufferColorspace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  43679. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  43680. }
  43681. }
  43682. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  43683. exports.AddEquation = AddEquation;
  43684. exports.AddOperation = AddOperation;
  43685. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  43686. exports.AdditiveBlending = AdditiveBlending;
  43687. exports.AgXToneMapping = AgXToneMapping;
  43688. exports.AlphaFormat = AlphaFormat;
  43689. exports.AlwaysCompare = AlwaysCompare;
  43690. exports.AlwaysDepth = AlwaysDepth;
  43691. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  43692. exports.AmbientLight = AmbientLight;
  43693. exports.AnimationAction = AnimationAction;
  43694. exports.AnimationClip = AnimationClip;
  43695. exports.AnimationLoader = AnimationLoader;
  43696. exports.AnimationMixer = AnimationMixer;
  43697. exports.AnimationObjectGroup = AnimationObjectGroup;
  43698. exports.AnimationUtils = AnimationUtils;
  43699. exports.ArcCurve = ArcCurve;
  43700. exports.ArrayCamera = ArrayCamera;
  43701. exports.ArrowHelper = ArrowHelper;
  43702. exports.AttachedBindMode = AttachedBindMode;
  43703. exports.Audio = Audio;
  43704. exports.AudioAnalyser = AudioAnalyser;
  43705. exports.AudioContext = AudioContext;
  43706. exports.AudioListener = AudioListener;
  43707. exports.AudioLoader = AudioLoader;
  43708. exports.AxesHelper = AxesHelper;
  43709. exports.BackSide = BackSide;
  43710. exports.BasicDepthPacking = BasicDepthPacking;
  43711. exports.BasicShadowMap = BasicShadowMap;
  43712. exports.BatchedMesh = BatchedMesh;
  43713. exports.Bone = Bone;
  43714. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  43715. exports.Box2 = Box2;
  43716. exports.Box3 = Box3;
  43717. exports.Box3Helper = Box3Helper;
  43718. exports.BoxGeometry = BoxGeometry;
  43719. exports.BoxHelper = BoxHelper;
  43720. exports.BufferAttribute = BufferAttribute;
  43721. exports.BufferGeometry = BufferGeometry;
  43722. exports.BufferGeometryLoader = BufferGeometryLoader;
  43723. exports.ByteType = ByteType;
  43724. exports.Cache = Cache;
  43725. exports.Camera = Camera;
  43726. exports.CameraHelper = CameraHelper;
  43727. exports.CanvasTexture = CanvasTexture;
  43728. exports.CapsuleGeometry = CapsuleGeometry;
  43729. exports.CatmullRomCurve3 = CatmullRomCurve3;
  43730. exports.CineonToneMapping = CineonToneMapping;
  43731. exports.CircleGeometry = CircleGeometry;
  43732. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  43733. exports.Clock = Clock;
  43734. exports.Color = Color;
  43735. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  43736. exports.ColorManagement = ColorManagement;
  43737. exports.CompressedArrayTexture = CompressedArrayTexture;
  43738. exports.CompressedCubeTexture = CompressedCubeTexture;
  43739. exports.CompressedTexture = CompressedTexture;
  43740. exports.CompressedTextureLoader = CompressedTextureLoader;
  43741. exports.ConeGeometry = ConeGeometry;
  43742. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  43743. exports.ConstantColorFactor = ConstantColorFactor;
  43744. exports.Controls = Controls;
  43745. exports.CubeCamera = CubeCamera;
  43746. exports.CubeReflectionMapping = CubeReflectionMapping;
  43747. exports.CubeRefractionMapping = CubeRefractionMapping;
  43748. exports.CubeTexture = CubeTexture;
  43749. exports.CubeTextureLoader = CubeTextureLoader;
  43750. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  43751. exports.CubicBezierCurve = CubicBezierCurve;
  43752. exports.CubicBezierCurve3 = CubicBezierCurve3;
  43753. exports.CubicInterpolant = CubicInterpolant;
  43754. exports.CullFaceBack = CullFaceBack;
  43755. exports.CullFaceFront = CullFaceFront;
  43756. exports.CullFaceFrontBack = CullFaceFrontBack;
  43757. exports.CullFaceNone = CullFaceNone;
  43758. exports.Curve = Curve;
  43759. exports.CurvePath = CurvePath;
  43760. exports.CustomBlending = CustomBlending;
  43761. exports.CustomToneMapping = CustomToneMapping;
  43762. exports.CylinderGeometry = CylinderGeometry;
  43763. exports.Cylindrical = Cylindrical;
  43764. exports.Data3DTexture = Data3DTexture;
  43765. exports.DataArrayTexture = DataArrayTexture;
  43766. exports.DataTexture = DataTexture;
  43767. exports.DataTextureLoader = DataTextureLoader;
  43768. exports.DataUtils = DataUtils;
  43769. exports.DecrementStencilOp = DecrementStencilOp;
  43770. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  43771. exports.DefaultLoadingManager = DefaultLoadingManager;
  43772. exports.DepthFormat = DepthFormat;
  43773. exports.DepthStencilFormat = DepthStencilFormat;
  43774. exports.DepthTexture = DepthTexture;
  43775. exports.DetachedBindMode = DetachedBindMode;
  43776. exports.DirectionalLight = DirectionalLight;
  43777. exports.DirectionalLightHelper = DirectionalLightHelper;
  43778. exports.DiscreteInterpolant = DiscreteInterpolant;
  43779. exports.DodecahedronGeometry = DodecahedronGeometry;
  43780. exports.DoubleSide = DoubleSide;
  43781. exports.DstAlphaFactor = DstAlphaFactor;
  43782. exports.DstColorFactor = DstColorFactor;
  43783. exports.DynamicCopyUsage = DynamicCopyUsage;
  43784. exports.DynamicDrawUsage = DynamicDrawUsage;
  43785. exports.DynamicReadUsage = DynamicReadUsage;
  43786. exports.EdgesGeometry = EdgesGeometry;
  43787. exports.EllipseCurve = EllipseCurve;
  43788. exports.EqualCompare = EqualCompare;
  43789. exports.EqualDepth = EqualDepth;
  43790. exports.EqualStencilFunc = EqualStencilFunc;
  43791. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  43792. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  43793. exports.Euler = Euler;
  43794. exports.EventDispatcher = EventDispatcher;
  43795. exports.ExtrudeGeometry = ExtrudeGeometry;
  43796. exports.FileLoader = FileLoader;
  43797. exports.Float16BufferAttribute = Float16BufferAttribute;
  43798. exports.Float32BufferAttribute = Float32BufferAttribute;
  43799. exports.FloatType = FloatType;
  43800. exports.Fog = Fog;
  43801. exports.FogExp2 = FogExp2;
  43802. exports.FramebufferTexture = FramebufferTexture;
  43803. exports.FrontSide = FrontSide;
  43804. exports.Frustum = Frustum;
  43805. exports.GLBufferAttribute = GLBufferAttribute;
  43806. exports.GLSL1 = GLSL1;
  43807. exports.GLSL3 = GLSL3;
  43808. exports.GreaterCompare = GreaterCompare;
  43809. exports.GreaterDepth = GreaterDepth;
  43810. exports.GreaterEqualCompare = GreaterEqualCompare;
  43811. exports.GreaterEqualDepth = GreaterEqualDepth;
  43812. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  43813. exports.GreaterStencilFunc = GreaterStencilFunc;
  43814. exports.GridHelper = GridHelper;
  43815. exports.Group = Group;
  43816. exports.HalfFloatType = HalfFloatType;
  43817. exports.HemisphereLight = HemisphereLight;
  43818. exports.HemisphereLightHelper = HemisphereLightHelper;
  43819. exports.IcosahedronGeometry = IcosahedronGeometry;
  43820. exports.ImageBitmapLoader = ImageBitmapLoader;
  43821. exports.ImageLoader = ImageLoader;
  43822. exports.ImageUtils = ImageUtils;
  43823. exports.IncrementStencilOp = IncrementStencilOp;
  43824. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  43825. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  43826. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  43827. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  43828. exports.InstancedMesh = InstancedMesh;
  43829. exports.Int16BufferAttribute = Int16BufferAttribute;
  43830. exports.Int32BufferAttribute = Int32BufferAttribute;
  43831. exports.Int8BufferAttribute = Int8BufferAttribute;
  43832. exports.IntType = IntType;
  43833. exports.InterleavedBuffer = InterleavedBuffer;
  43834. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  43835. exports.Interpolant = Interpolant;
  43836. exports.InterpolateDiscrete = InterpolateDiscrete;
  43837. exports.InterpolateLinear = InterpolateLinear;
  43838. exports.InterpolateSmooth = InterpolateSmooth;
  43839. exports.InvertStencilOp = InvertStencilOp;
  43840. exports.KeepStencilOp = KeepStencilOp;
  43841. exports.KeyframeTrack = KeyframeTrack;
  43842. exports.LOD = LOD;
  43843. exports.LatheGeometry = LatheGeometry;
  43844. exports.Layers = Layers;
  43845. exports.LessCompare = LessCompare;
  43846. exports.LessDepth = LessDepth;
  43847. exports.LessEqualCompare = LessEqualCompare;
  43848. exports.LessEqualDepth = LessEqualDepth;
  43849. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  43850. exports.LessStencilFunc = LessStencilFunc;
  43851. exports.Light = Light;
  43852. exports.LightProbe = LightProbe;
  43853. exports.Line = Line;
  43854. exports.Line3 = Line3;
  43855. exports.LineBasicMaterial = LineBasicMaterial;
  43856. exports.LineCurve = LineCurve;
  43857. exports.LineCurve3 = LineCurve3;
  43858. exports.LineDashedMaterial = LineDashedMaterial;
  43859. exports.LineLoop = LineLoop;
  43860. exports.LineSegments = LineSegments;
  43861. exports.LinearFilter = LinearFilter;
  43862. exports.LinearInterpolant = LinearInterpolant;
  43863. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  43864. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  43865. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  43866. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  43867. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  43868. exports.LinearToneMapping = LinearToneMapping;
  43869. exports.LinearTransfer = LinearTransfer;
  43870. exports.Loader = Loader;
  43871. exports.LoaderUtils = LoaderUtils;
  43872. exports.LoadingManager = LoadingManager;
  43873. exports.LoopOnce = LoopOnce;
  43874. exports.LoopPingPong = LoopPingPong;
  43875. exports.LoopRepeat = LoopRepeat;
  43876. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  43877. exports.LuminanceFormat = LuminanceFormat;
  43878. exports.MOUSE = MOUSE;
  43879. exports.Material = Material;
  43880. exports.MaterialLoader = MaterialLoader;
  43881. exports.MathUtils = MathUtils;
  43882. exports.Matrix2 = Matrix2;
  43883. exports.Matrix3 = Matrix3;
  43884. exports.Matrix4 = Matrix4;
  43885. exports.MaxEquation = MaxEquation;
  43886. exports.Mesh = Mesh;
  43887. exports.MeshBasicMaterial = MeshBasicMaterial;
  43888. exports.MeshDepthMaterial = MeshDepthMaterial;
  43889. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  43890. exports.MeshLambertMaterial = MeshLambertMaterial;
  43891. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  43892. exports.MeshNormalMaterial = MeshNormalMaterial;
  43893. exports.MeshPhongMaterial = MeshPhongMaterial;
  43894. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  43895. exports.MeshStandardMaterial = MeshStandardMaterial;
  43896. exports.MeshToonMaterial = MeshToonMaterial;
  43897. exports.MinEquation = MinEquation;
  43898. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  43899. exports.MixOperation = MixOperation;
  43900. exports.MultiplyBlending = MultiplyBlending;
  43901. exports.MultiplyOperation = MultiplyOperation;
  43902. exports.NearestFilter = NearestFilter;
  43903. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  43904. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  43905. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  43906. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  43907. exports.NeutralToneMapping = NeutralToneMapping;
  43908. exports.NeverCompare = NeverCompare;
  43909. exports.NeverDepth = NeverDepth;
  43910. exports.NeverStencilFunc = NeverStencilFunc;
  43911. exports.NoBlending = NoBlending;
  43912. exports.NoColorSpace = NoColorSpace;
  43913. exports.NoToneMapping = NoToneMapping;
  43914. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  43915. exports.NormalBlending = NormalBlending;
  43916. exports.NotEqualCompare = NotEqualCompare;
  43917. exports.NotEqualDepth = NotEqualDepth;
  43918. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  43919. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  43920. exports.Object3D = Object3D;
  43921. exports.ObjectLoader = ObjectLoader;
  43922. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  43923. exports.OctahedronGeometry = OctahedronGeometry;
  43924. exports.OneFactor = OneFactor;
  43925. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  43926. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  43927. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  43928. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  43929. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  43930. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  43931. exports.OrthographicCamera = OrthographicCamera;
  43932. exports.PCFShadowMap = PCFShadowMap;
  43933. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  43934. exports.PMREMGenerator = PMREMGenerator;
  43935. exports.Path = Path;
  43936. exports.PerspectiveCamera = PerspectiveCamera;
  43937. exports.Plane = Plane;
  43938. exports.PlaneGeometry = PlaneGeometry;
  43939. exports.PlaneHelper = PlaneHelper;
  43940. exports.PointLight = PointLight;
  43941. exports.PointLightHelper = PointLightHelper;
  43942. exports.Points = Points;
  43943. exports.PointsMaterial = PointsMaterial;
  43944. exports.PolarGridHelper = PolarGridHelper;
  43945. exports.PolyhedronGeometry = PolyhedronGeometry;
  43946. exports.PositionalAudio = PositionalAudio;
  43947. exports.PropertyBinding = PropertyBinding;
  43948. exports.PropertyMixer = PropertyMixer;
  43949. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  43950. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  43951. exports.Quaternion = Quaternion;
  43952. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  43953. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  43954. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  43955. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  43956. exports.REVISION = REVISION;
  43957. exports.RGBADepthPacking = RGBADepthPacking;
  43958. exports.RGBAFormat = RGBAFormat;
  43959. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  43960. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  43961. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  43962. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  43963. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  43964. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  43965. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  43966. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  43967. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  43968. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  43969. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  43970. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  43971. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  43972. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  43973. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  43974. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  43975. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  43976. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  43977. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  43978. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  43979. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  43980. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  43981. exports.RGBDepthPacking = RGBDepthPacking;
  43982. exports.RGBFormat = RGBFormat;
  43983. exports.RGBIntegerFormat = RGBIntegerFormat;
  43984. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  43985. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  43986. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  43987. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  43988. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  43989. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  43990. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  43991. exports.RGDepthPacking = RGDepthPacking;
  43992. exports.RGFormat = RGFormat;
  43993. exports.RGIntegerFormat = RGIntegerFormat;
  43994. exports.RawShaderMaterial = RawShaderMaterial;
  43995. exports.Ray = Ray;
  43996. exports.Raycaster = Raycaster;
  43997. exports.RectAreaLight = RectAreaLight;
  43998. exports.RedFormat = RedFormat;
  43999. exports.RedIntegerFormat = RedIntegerFormat;
  44000. exports.ReinhardToneMapping = ReinhardToneMapping;
  44001. exports.RenderTarget = RenderTarget;
  44002. exports.RenderTarget3D = RenderTarget3D;
  44003. exports.RenderTargetArray = RenderTargetArray;
  44004. exports.RepeatWrapping = RepeatWrapping;
  44005. exports.ReplaceStencilOp = ReplaceStencilOp;
  44006. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  44007. exports.RingGeometry = RingGeometry;
  44008. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  44009. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  44010. exports.SRGBColorSpace = SRGBColorSpace;
  44011. exports.SRGBTransfer = SRGBTransfer;
  44012. exports.Scene = Scene;
  44013. exports.ShaderChunk = ShaderChunk;
  44014. exports.ShaderLib = ShaderLib;
  44015. exports.ShaderMaterial = ShaderMaterial;
  44016. exports.ShadowMaterial = ShadowMaterial;
  44017. exports.Shape = Shape;
  44018. exports.ShapeGeometry = ShapeGeometry;
  44019. exports.ShapePath = ShapePath;
  44020. exports.ShapeUtils = ShapeUtils;
  44021. exports.ShortType = ShortType;
  44022. exports.Skeleton = Skeleton;
  44023. exports.SkeletonHelper = SkeletonHelper;
  44024. exports.SkinnedMesh = SkinnedMesh;
  44025. exports.Source = Source;
  44026. exports.Sphere = Sphere;
  44027. exports.SphereGeometry = SphereGeometry;
  44028. exports.Spherical = Spherical;
  44029. exports.SphericalHarmonics3 = SphericalHarmonics3;
  44030. exports.SplineCurve = SplineCurve;
  44031. exports.SpotLight = SpotLight;
  44032. exports.SpotLightHelper = SpotLightHelper;
  44033. exports.Sprite = Sprite;
  44034. exports.SpriteMaterial = SpriteMaterial;
  44035. exports.SrcAlphaFactor = SrcAlphaFactor;
  44036. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  44037. exports.SrcColorFactor = SrcColorFactor;
  44038. exports.StaticCopyUsage = StaticCopyUsage;
  44039. exports.StaticDrawUsage = StaticDrawUsage;
  44040. exports.StaticReadUsage = StaticReadUsage;
  44041. exports.StereoCamera = StereoCamera;
  44042. exports.StreamCopyUsage = StreamCopyUsage;
  44043. exports.StreamDrawUsage = StreamDrawUsage;
  44044. exports.StreamReadUsage = StreamReadUsage;
  44045. exports.StringKeyframeTrack = StringKeyframeTrack;
  44046. exports.SubtractEquation = SubtractEquation;
  44047. exports.SubtractiveBlending = SubtractiveBlending;
  44048. exports.TOUCH = TOUCH;
  44049. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  44050. exports.TetrahedronGeometry = TetrahedronGeometry;
  44051. exports.Texture = Texture;
  44052. exports.TextureLoader = TextureLoader;
  44053. exports.TextureUtils = TextureUtils;
  44054. exports.TimestampQuery = TimestampQuery;
  44055. exports.TorusGeometry = TorusGeometry;
  44056. exports.TorusKnotGeometry = TorusKnotGeometry;
  44057. exports.Triangle = Triangle;
  44058. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  44059. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  44060. exports.TrianglesDrawMode = TrianglesDrawMode;
  44061. exports.TubeGeometry = TubeGeometry;
  44062. exports.UVMapping = UVMapping;
  44063. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  44064. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  44065. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  44066. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  44067. exports.Uniform = Uniform;
  44068. exports.UniformsGroup = UniformsGroup;
  44069. exports.UniformsLib = UniformsLib;
  44070. exports.UniformsUtils = UniformsUtils;
  44071. exports.UnsignedByteType = UnsignedByteType;
  44072. exports.UnsignedInt248Type = UnsignedInt248Type;
  44073. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  44074. exports.UnsignedIntType = UnsignedIntType;
  44075. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  44076. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  44077. exports.UnsignedShortType = UnsignedShortType;
  44078. exports.VSMShadowMap = VSMShadowMap;
  44079. exports.Vector2 = Vector2;
  44080. exports.Vector3 = Vector3;
  44081. exports.Vector4 = Vector4;
  44082. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  44083. exports.VideoFrameTexture = VideoFrameTexture;
  44084. exports.VideoTexture = VideoTexture;
  44085. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  44086. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  44087. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  44088. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  44089. exports.WebGLRenderTarget = WebGLRenderTarget;
  44090. exports.WebGLRenderer = WebGLRenderer;
  44091. exports.WebGLUtils = WebGLUtils;
  44092. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  44093. exports.WebXRController = WebXRController;
  44094. exports.WireframeGeometry = WireframeGeometry;
  44095. exports.WrapAroundEnding = WrapAroundEnding;
  44096. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  44097. exports.ZeroFactor = ZeroFactor;
  44098. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  44099. exports.ZeroStencilOp = ZeroStencilOp;
  44100. exports.createCanvasElement = createCanvasElement;
粤ICP备19079148号