three.module.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '151dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const TwoPassDoubleSide = 2; // r149
  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 NeverDepth = 0;
  44. const AlwaysDepth = 1;
  45. const LessDepth = 2;
  46. const LessEqualDepth = 3;
  47. const EqualDepth = 4;
  48. const GreaterEqualDepth = 5;
  49. const GreaterDepth = 6;
  50. const NotEqualDepth = 7;
  51. const MultiplyOperation = 0;
  52. const MixOperation = 1;
  53. const AddOperation = 2;
  54. const NoToneMapping = 0;
  55. const LinearToneMapping = 1;
  56. const ReinhardToneMapping = 2;
  57. const CineonToneMapping = 3;
  58. const ACESFilmicToneMapping = 4;
  59. const CustomToneMapping = 5;
  60. const UVMapping = 300;
  61. const CubeReflectionMapping = 301;
  62. const CubeRefractionMapping = 302;
  63. const EquirectangularReflectionMapping = 303;
  64. const EquirectangularRefractionMapping = 304;
  65. const CubeUVReflectionMapping = 306;
  66. const RepeatWrapping = 1000;
  67. const ClampToEdgeWrapping = 1001;
  68. const MirroredRepeatWrapping = 1002;
  69. const NearestFilter = 1003;
  70. const NearestMipmapNearestFilter = 1004;
  71. const NearestMipMapNearestFilter = 1004;
  72. const NearestMipmapLinearFilter = 1005;
  73. const NearestMipMapLinearFilter = 1005;
  74. const LinearFilter = 1006;
  75. const LinearMipmapNearestFilter = 1007;
  76. const LinearMipMapNearestFilter = 1007;
  77. const LinearMipmapLinearFilter = 1008;
  78. const LinearMipMapLinearFilter = 1008;
  79. const UnsignedByteType = 1009;
  80. const ByteType = 1010;
  81. const ShortType = 1011;
  82. const UnsignedShortType = 1012;
  83. const IntType = 1013;
  84. const UnsignedIntType = 1014;
  85. const FloatType = 1015;
  86. const HalfFloatType = 1016;
  87. const UnsignedShort4444Type = 1017;
  88. const UnsignedShort5551Type = 1018;
  89. const UnsignedInt248Type = 1020;
  90. const AlphaFormat = 1021;
  91. const RGBAFormat = 1023;
  92. const LuminanceFormat = 1024;
  93. const LuminanceAlphaFormat = 1025;
  94. const DepthFormat = 1026;
  95. const DepthStencilFormat = 1027;
  96. const RedFormat = 1028;
  97. const RedIntegerFormat = 1029;
  98. const RGFormat = 1030;
  99. const RGIntegerFormat = 1031;
  100. const RGBAIntegerFormat = 1033;
  101. const RGB_S3TC_DXT1_Format = 33776;
  102. const RGBA_S3TC_DXT1_Format = 33777;
  103. const RGBA_S3TC_DXT3_Format = 33778;
  104. const RGBA_S3TC_DXT5_Format = 33779;
  105. const RGB_PVRTC_4BPPV1_Format = 35840;
  106. const RGB_PVRTC_2BPPV1_Format = 35841;
  107. const RGBA_PVRTC_4BPPV1_Format = 35842;
  108. const RGBA_PVRTC_2BPPV1_Format = 35843;
  109. const RGB_ETC1_Format = 36196;
  110. const RGB_ETC2_Format = 37492;
  111. const RGBA_ETC2_EAC_Format = 37496;
  112. const RGBA_ASTC_4x4_Format = 37808;
  113. const RGBA_ASTC_5x4_Format = 37809;
  114. const RGBA_ASTC_5x5_Format = 37810;
  115. const RGBA_ASTC_6x5_Format = 37811;
  116. const RGBA_ASTC_6x6_Format = 37812;
  117. const RGBA_ASTC_8x5_Format = 37813;
  118. const RGBA_ASTC_8x6_Format = 37814;
  119. const RGBA_ASTC_8x8_Format = 37815;
  120. const RGBA_ASTC_10x5_Format = 37816;
  121. const RGBA_ASTC_10x6_Format = 37817;
  122. const RGBA_ASTC_10x8_Format = 37818;
  123. const RGBA_ASTC_10x10_Format = 37819;
  124. const RGBA_ASTC_12x10_Format = 37820;
  125. const RGBA_ASTC_12x12_Format = 37821;
  126. const RGBA_BPTC_Format = 36492;
  127. const RED_RGTC1_Format = 36283;
  128. const SIGNED_RED_RGTC1_Format = 36284;
  129. const RED_GREEN_RGTC2_Format = 36285;
  130. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  131. const LoopOnce = 2200;
  132. const LoopRepeat = 2201;
  133. const LoopPingPong = 2202;
  134. const InterpolateDiscrete = 2300;
  135. const InterpolateLinear = 2301;
  136. const InterpolateSmooth = 2302;
  137. const ZeroCurvatureEnding = 2400;
  138. const ZeroSlopeEnding = 2401;
  139. const WrapAroundEnding = 2402;
  140. const NormalAnimationBlendMode = 2500;
  141. const AdditiveAnimationBlendMode = 2501;
  142. const TrianglesDrawMode = 0;
  143. const TriangleStripDrawMode = 1;
  144. const TriangleFanDrawMode = 2;
  145. const LinearEncoding = 3000;
  146. const sRGBEncoding = 3001;
  147. const BasicDepthPacking = 3200;
  148. const RGBADepthPacking = 3201;
  149. const TangentSpaceNormalMap = 0;
  150. const ObjectSpaceNormalMap = 1;
  151. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  152. const NoColorSpace = '';
  153. const SRGBColorSpace = 'srgb';
  154. const LinearSRGBColorSpace = 'srgb-linear';
  155. const DisplayP3ColorSpace = 'display-p3';
  156. const ZeroStencilOp = 0;
  157. const KeepStencilOp = 7680;
  158. const ReplaceStencilOp = 7681;
  159. const IncrementStencilOp = 7682;
  160. const DecrementStencilOp = 7683;
  161. const IncrementWrapStencilOp = 34055;
  162. const DecrementWrapStencilOp = 34056;
  163. const InvertStencilOp = 5386;
  164. const NeverStencilFunc = 512;
  165. const LessStencilFunc = 513;
  166. const EqualStencilFunc = 514;
  167. const LessEqualStencilFunc = 515;
  168. const GreaterStencilFunc = 516;
  169. const NotEqualStencilFunc = 517;
  170. const GreaterEqualStencilFunc = 518;
  171. const AlwaysStencilFunc = 519;
  172. const StaticDrawUsage = 35044;
  173. const DynamicDrawUsage = 35048;
  174. const StreamDrawUsage = 35040;
  175. const StaticReadUsage = 35045;
  176. const DynamicReadUsage = 35049;
  177. const StreamReadUsage = 35041;
  178. const StaticCopyUsage = 35046;
  179. const DynamicCopyUsage = 35050;
  180. const StreamCopyUsage = 35042;
  181. const GLSL1 = '100';
  182. const GLSL3 = '300 es';
  183. const _SRGBAFormat = 1035; // fallback for WebGL 1
  184. /**
  185. * https://github.com/mrdoob/eventdispatcher.js/
  186. */
  187. class EventDispatcher {
  188. addEventListener( type, listener ) {
  189. if ( this._listeners === undefined ) this._listeners = {};
  190. const listeners = this._listeners;
  191. if ( listeners[ type ] === undefined ) {
  192. listeners[ type ] = [];
  193. }
  194. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  195. listeners[ type ].push( listener );
  196. }
  197. }
  198. hasEventListener( type, listener ) {
  199. if ( this._listeners === undefined ) return false;
  200. const listeners = this._listeners;
  201. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  202. }
  203. removeEventListener( type, listener ) {
  204. if ( this._listeners === undefined ) return;
  205. const listeners = this._listeners;
  206. const listenerArray = listeners[ type ];
  207. if ( listenerArray !== undefined ) {
  208. const index = listenerArray.indexOf( listener );
  209. if ( index !== - 1 ) {
  210. listenerArray.splice( index, 1 );
  211. }
  212. }
  213. }
  214. dispatchEvent( event ) {
  215. if ( this._listeners === undefined ) return;
  216. const listeners = this._listeners;
  217. const listenerArray = listeners[ event.type ];
  218. if ( listenerArray !== undefined ) {
  219. event.target = this;
  220. // Make a copy, in case listeners are removed while iterating.
  221. const array = listenerArray.slice( 0 );
  222. for ( let i = 0, l = array.length; i < l; i ++ ) {
  223. array[ i ].call( this, event );
  224. }
  225. event.target = null;
  226. }
  227. }
  228. }
  229. 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' ];
  230. let _seed = 1234567;
  231. const DEG2RAD = Math.PI / 180;
  232. const RAD2DEG = 180 / Math.PI;
  233. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  234. function generateUUID() {
  235. const d0 = Math.random() * 0xffffffff | 0;
  236. const d1 = Math.random() * 0xffffffff | 0;
  237. const d2 = Math.random() * 0xffffffff | 0;
  238. const d3 = Math.random() * 0xffffffff | 0;
  239. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  240. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  241. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  242. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  243. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  244. return uuid.toLowerCase();
  245. }
  246. function clamp( value, min, max ) {
  247. return Math.max( min, Math.min( max, value ) );
  248. }
  249. // compute euclidean modulo of m % n
  250. // https://en.wikipedia.org/wiki/Modulo_operation
  251. function euclideanModulo( n, m ) {
  252. return ( ( n % m ) + m ) % m;
  253. }
  254. // Linear mapping from range <a1, a2> to range <b1, b2>
  255. function mapLinear( x, a1, a2, b1, b2 ) {
  256. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  257. }
  258. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  259. function inverseLerp( x, y, value ) {
  260. if ( x !== y ) {
  261. return ( value - x ) / ( y - x );
  262. } else {
  263. return 0;
  264. }
  265. }
  266. // https://en.wikipedia.org/wiki/Linear_interpolation
  267. function lerp( x, y, t ) {
  268. return ( 1 - t ) * x + t * y;
  269. }
  270. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  271. function damp( x, y, lambda, dt ) {
  272. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  273. }
  274. // https://www.desmos.com/calculator/vcsjnyz7x4
  275. function pingpong( x, length = 1 ) {
  276. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  277. }
  278. // http://en.wikipedia.org/wiki/Smoothstep
  279. function smoothstep( x, min, max ) {
  280. if ( x <= min ) return 0;
  281. if ( x >= max ) return 1;
  282. x = ( x - min ) / ( max - min );
  283. return x * x * ( 3 - 2 * x );
  284. }
  285. function smootherstep( x, min, max ) {
  286. if ( x <= min ) return 0;
  287. if ( x >= max ) return 1;
  288. x = ( x - min ) / ( max - min );
  289. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  290. }
  291. // Random integer from <low, high> interval
  292. function randInt( low, high ) {
  293. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  294. }
  295. // Random float from <low, high> interval
  296. function randFloat( low, high ) {
  297. return low + Math.random() * ( high - low );
  298. }
  299. // Random float from <-range/2, range/2> interval
  300. function randFloatSpread( range ) {
  301. return range * ( 0.5 - Math.random() );
  302. }
  303. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  304. function seededRandom( s ) {
  305. if ( s !== undefined ) _seed = s;
  306. // Mulberry32 generator
  307. let t = _seed += 0x6D2B79F5;
  308. t = Math.imul( t ^ t >>> 15, t | 1 );
  309. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  310. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  311. }
  312. function degToRad( degrees ) {
  313. return degrees * DEG2RAD;
  314. }
  315. function radToDeg( radians ) {
  316. return radians * RAD2DEG;
  317. }
  318. function isPowerOfTwo( value ) {
  319. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  320. }
  321. function ceilPowerOfTwo( value ) {
  322. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  323. }
  324. function floorPowerOfTwo( value ) {
  325. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  326. }
  327. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  328. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  329. // rotations are applied to the axes in the order specified by 'order'
  330. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  331. // angles are in radians
  332. const cos = Math.cos;
  333. const sin = Math.sin;
  334. const c2 = cos( b / 2 );
  335. const s2 = sin( b / 2 );
  336. const c13 = cos( ( a + c ) / 2 );
  337. const s13 = sin( ( a + c ) / 2 );
  338. const c1_3 = cos( ( a - c ) / 2 );
  339. const s1_3 = sin( ( a - c ) / 2 );
  340. const c3_1 = cos( ( c - a ) / 2 );
  341. const s3_1 = sin( ( c - a ) / 2 );
  342. switch ( order ) {
  343. case 'XYX':
  344. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  345. break;
  346. case 'YZY':
  347. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  348. break;
  349. case 'ZXZ':
  350. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  351. break;
  352. case 'XZX':
  353. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  354. break;
  355. case 'YXY':
  356. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  357. break;
  358. case 'ZYZ':
  359. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  360. break;
  361. default:
  362. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  363. }
  364. }
  365. function denormalize( value, array ) {
  366. switch ( array.constructor ) {
  367. case Float32Array:
  368. return value;
  369. case Uint16Array:
  370. return value / 65535.0;
  371. case Uint8Array:
  372. return value / 255.0;
  373. case Int16Array:
  374. return Math.max( value / 32767.0, - 1.0 );
  375. case Int8Array:
  376. return Math.max( value / 127.0, - 1.0 );
  377. default:
  378. throw new Error( 'Invalid component type.' );
  379. }
  380. }
  381. function normalize( value, array ) {
  382. switch ( array.constructor ) {
  383. case Float32Array:
  384. return value;
  385. case Uint16Array:
  386. return Math.round( value * 65535.0 );
  387. case Uint8Array:
  388. return Math.round( value * 255.0 );
  389. case Int16Array:
  390. return Math.round( value * 32767.0 );
  391. case Int8Array:
  392. return Math.round( value * 127.0 );
  393. default:
  394. throw new Error( 'Invalid component type.' );
  395. }
  396. }
  397. const MathUtils = {
  398. DEG2RAD: DEG2RAD,
  399. RAD2DEG: RAD2DEG,
  400. generateUUID: generateUUID,
  401. clamp: clamp,
  402. euclideanModulo: euclideanModulo,
  403. mapLinear: mapLinear,
  404. inverseLerp: inverseLerp,
  405. lerp: lerp,
  406. damp: damp,
  407. pingpong: pingpong,
  408. smoothstep: smoothstep,
  409. smootherstep: smootherstep,
  410. randInt: randInt,
  411. randFloat: randFloat,
  412. randFloatSpread: randFloatSpread,
  413. seededRandom: seededRandom,
  414. degToRad: degToRad,
  415. radToDeg: radToDeg,
  416. isPowerOfTwo: isPowerOfTwo,
  417. ceilPowerOfTwo: ceilPowerOfTwo,
  418. floorPowerOfTwo: floorPowerOfTwo,
  419. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  420. normalize: normalize,
  421. denormalize: denormalize
  422. };
  423. class Vector2 {
  424. constructor( x = 0, y = 0 ) {
  425. Vector2.prototype.isVector2 = true;
  426. this.x = x;
  427. this.y = y;
  428. }
  429. get width() {
  430. return this.x;
  431. }
  432. set width( value ) {
  433. this.x = value;
  434. }
  435. get height() {
  436. return this.y;
  437. }
  438. set height( value ) {
  439. this.y = value;
  440. }
  441. set( x, y ) {
  442. this.x = x;
  443. this.y = y;
  444. return this;
  445. }
  446. setScalar( scalar ) {
  447. this.x = scalar;
  448. this.y = scalar;
  449. return this;
  450. }
  451. setX( x ) {
  452. this.x = x;
  453. return this;
  454. }
  455. setY( y ) {
  456. this.y = y;
  457. return this;
  458. }
  459. setComponent( index, value ) {
  460. switch ( index ) {
  461. case 0: this.x = value; break;
  462. case 1: this.y = value; break;
  463. default: throw new Error( 'index is out of range: ' + index );
  464. }
  465. return this;
  466. }
  467. getComponent( index ) {
  468. switch ( index ) {
  469. case 0: return this.x;
  470. case 1: return this.y;
  471. default: throw new Error( 'index is out of range: ' + index );
  472. }
  473. }
  474. clone() {
  475. return new this.constructor( this.x, this.y );
  476. }
  477. copy( v ) {
  478. this.x = v.x;
  479. this.y = v.y;
  480. return this;
  481. }
  482. add( v ) {
  483. this.x += v.x;
  484. this.y += v.y;
  485. return this;
  486. }
  487. addScalar( s ) {
  488. this.x += s;
  489. this.y += s;
  490. return this;
  491. }
  492. addVectors( a, b ) {
  493. this.x = a.x + b.x;
  494. this.y = a.y + b.y;
  495. return this;
  496. }
  497. addScaledVector( v, s ) {
  498. this.x += v.x * s;
  499. this.y += v.y * s;
  500. return this;
  501. }
  502. sub( v ) {
  503. this.x -= v.x;
  504. this.y -= v.y;
  505. return this;
  506. }
  507. subScalar( s ) {
  508. this.x -= s;
  509. this.y -= s;
  510. return this;
  511. }
  512. subVectors( a, b ) {
  513. this.x = a.x - b.x;
  514. this.y = a.y - b.y;
  515. return this;
  516. }
  517. multiply( v ) {
  518. this.x *= v.x;
  519. this.y *= v.y;
  520. return this;
  521. }
  522. multiplyScalar( scalar ) {
  523. this.x *= scalar;
  524. this.y *= scalar;
  525. return this;
  526. }
  527. divide( v ) {
  528. this.x /= v.x;
  529. this.y /= v.y;
  530. return this;
  531. }
  532. divideScalar( scalar ) {
  533. return this.multiplyScalar( 1 / scalar );
  534. }
  535. applyMatrix3( m ) {
  536. const x = this.x, y = this.y;
  537. const e = m.elements;
  538. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  539. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  540. return this;
  541. }
  542. min( v ) {
  543. this.x = Math.min( this.x, v.x );
  544. this.y = Math.min( this.y, v.y );
  545. return this;
  546. }
  547. max( v ) {
  548. this.x = Math.max( this.x, v.x );
  549. this.y = Math.max( this.y, v.y );
  550. return this;
  551. }
  552. clamp( min, max ) {
  553. // assumes min < max, componentwise
  554. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  555. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  556. return this;
  557. }
  558. clampScalar( minVal, maxVal ) {
  559. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  560. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  561. return this;
  562. }
  563. clampLength( min, max ) {
  564. const length = this.length();
  565. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  566. }
  567. floor() {
  568. this.x = Math.floor( this.x );
  569. this.y = Math.floor( this.y );
  570. return this;
  571. }
  572. ceil() {
  573. this.x = Math.ceil( this.x );
  574. this.y = Math.ceil( this.y );
  575. return this;
  576. }
  577. round() {
  578. this.x = Math.round( this.x );
  579. this.y = Math.round( this.y );
  580. return this;
  581. }
  582. roundToZero() {
  583. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  584. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  585. return this;
  586. }
  587. negate() {
  588. this.x = - this.x;
  589. this.y = - this.y;
  590. return this;
  591. }
  592. dot( v ) {
  593. return this.x * v.x + this.y * v.y;
  594. }
  595. cross( v ) {
  596. return this.x * v.y - this.y * v.x;
  597. }
  598. lengthSq() {
  599. return this.x * this.x + this.y * this.y;
  600. }
  601. length() {
  602. return Math.sqrt( this.x * this.x + this.y * this.y );
  603. }
  604. manhattanLength() {
  605. return Math.abs( this.x ) + Math.abs( this.y );
  606. }
  607. normalize() {
  608. return this.divideScalar( this.length() || 1 );
  609. }
  610. angle() {
  611. // computes the angle in radians with respect to the positive x-axis
  612. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  613. return angle;
  614. }
  615. angleTo( v ) {
  616. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  617. if ( denominator === 0 ) return Math.PI / 2;
  618. const theta = this.dot( v ) / denominator;
  619. // clamp, to handle numerical problems
  620. return Math.acos( clamp( theta, - 1, 1 ) );
  621. }
  622. distanceTo( v ) {
  623. return Math.sqrt( this.distanceToSquared( v ) );
  624. }
  625. distanceToSquared( v ) {
  626. const dx = this.x - v.x, dy = this.y - v.y;
  627. return dx * dx + dy * dy;
  628. }
  629. manhattanDistanceTo( v ) {
  630. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  631. }
  632. setLength( length ) {
  633. return this.normalize().multiplyScalar( length );
  634. }
  635. lerp( v, alpha ) {
  636. this.x += ( v.x - this.x ) * alpha;
  637. this.y += ( v.y - this.y ) * alpha;
  638. return this;
  639. }
  640. lerpVectors( v1, v2, alpha ) {
  641. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  642. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  643. return this;
  644. }
  645. equals( v ) {
  646. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  647. }
  648. fromArray( array, offset = 0 ) {
  649. this.x = array[ offset ];
  650. this.y = array[ offset + 1 ];
  651. return this;
  652. }
  653. toArray( array = [], offset = 0 ) {
  654. array[ offset ] = this.x;
  655. array[ offset + 1 ] = this.y;
  656. return array;
  657. }
  658. fromBufferAttribute( attribute, index ) {
  659. this.x = attribute.getX( index );
  660. this.y = attribute.getY( index );
  661. return this;
  662. }
  663. rotateAround( center, angle ) {
  664. const c = Math.cos( angle ), s = Math.sin( angle );
  665. const x = this.x - center.x;
  666. const y = this.y - center.y;
  667. this.x = x * c - y * s + center.x;
  668. this.y = x * s + y * c + center.y;
  669. return this;
  670. }
  671. random() {
  672. this.x = Math.random();
  673. this.y = Math.random();
  674. return this;
  675. }
  676. *[ Symbol.iterator ]() {
  677. yield this.x;
  678. yield this.y;
  679. }
  680. }
  681. class Matrix3 {
  682. constructor() {
  683. Matrix3.prototype.isMatrix3 = true;
  684. this.elements = [
  685. 1, 0, 0,
  686. 0, 1, 0,
  687. 0, 0, 1
  688. ];
  689. }
  690. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  691. const te = this.elements;
  692. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  693. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  694. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  695. return this;
  696. }
  697. identity() {
  698. this.set(
  699. 1, 0, 0,
  700. 0, 1, 0,
  701. 0, 0, 1
  702. );
  703. return this;
  704. }
  705. copy( m ) {
  706. const te = this.elements;
  707. const me = m.elements;
  708. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  709. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  710. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  711. return this;
  712. }
  713. extractBasis( xAxis, yAxis, zAxis ) {
  714. xAxis.setFromMatrix3Column( this, 0 );
  715. yAxis.setFromMatrix3Column( this, 1 );
  716. zAxis.setFromMatrix3Column( this, 2 );
  717. return this;
  718. }
  719. setFromMatrix4( m ) {
  720. const me = m.elements;
  721. this.set(
  722. me[ 0 ], me[ 4 ], me[ 8 ],
  723. me[ 1 ], me[ 5 ], me[ 9 ],
  724. me[ 2 ], me[ 6 ], me[ 10 ]
  725. );
  726. return this;
  727. }
  728. multiply( m ) {
  729. return this.multiplyMatrices( this, m );
  730. }
  731. premultiply( m ) {
  732. return this.multiplyMatrices( m, this );
  733. }
  734. multiplyMatrices( a, b ) {
  735. const ae = a.elements;
  736. const be = b.elements;
  737. const te = this.elements;
  738. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  739. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  740. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  741. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  742. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  743. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  744. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  745. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  746. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  747. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  748. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  749. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  750. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  751. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  752. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  753. return this;
  754. }
  755. multiplyScalar( s ) {
  756. const te = this.elements;
  757. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  758. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  759. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  760. return this;
  761. }
  762. determinant() {
  763. const te = this.elements;
  764. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  765. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  766. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  767. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  768. }
  769. invert() {
  770. const te = this.elements,
  771. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  772. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  773. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  774. t11 = n33 * n22 - n32 * n23,
  775. t12 = n32 * n13 - n33 * n12,
  776. t13 = n23 * n12 - n22 * n13,
  777. det = n11 * t11 + n21 * t12 + n31 * t13;
  778. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  779. const detInv = 1 / det;
  780. te[ 0 ] = t11 * detInv;
  781. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  782. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  783. te[ 3 ] = t12 * detInv;
  784. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  785. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  786. te[ 6 ] = t13 * detInv;
  787. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  788. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  789. return this;
  790. }
  791. transpose() {
  792. let tmp;
  793. const m = this.elements;
  794. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  795. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  796. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  797. return this;
  798. }
  799. getNormalMatrix( matrix4 ) {
  800. return this.setFromMatrix4( matrix4 ).invert().transpose();
  801. }
  802. transposeIntoArray( r ) {
  803. const m = this.elements;
  804. r[ 0 ] = m[ 0 ];
  805. r[ 1 ] = m[ 3 ];
  806. r[ 2 ] = m[ 6 ];
  807. r[ 3 ] = m[ 1 ];
  808. r[ 4 ] = m[ 4 ];
  809. r[ 5 ] = m[ 7 ];
  810. r[ 6 ] = m[ 2 ];
  811. r[ 7 ] = m[ 5 ];
  812. r[ 8 ] = m[ 8 ];
  813. return this;
  814. }
  815. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  816. const c = Math.cos( rotation );
  817. const s = Math.sin( rotation );
  818. this.set(
  819. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  820. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  821. 0, 0, 1
  822. );
  823. return this;
  824. }
  825. //
  826. scale( sx, sy ) {
  827. this.premultiply( _m3.makeScale( sx, sy ) );
  828. return this;
  829. }
  830. rotate( theta ) {
  831. this.premultiply( _m3.makeRotation( - theta ) );
  832. return this;
  833. }
  834. translate( tx, ty ) {
  835. this.premultiply( _m3.makeTranslation( tx, ty ) );
  836. return this;
  837. }
  838. // for 2D Transforms
  839. makeTranslation( x, y ) {
  840. this.set(
  841. 1, 0, x,
  842. 0, 1, y,
  843. 0, 0, 1
  844. );
  845. return this;
  846. }
  847. makeRotation( theta ) {
  848. // counterclockwise
  849. const c = Math.cos( theta );
  850. const s = Math.sin( theta );
  851. this.set(
  852. c, - s, 0,
  853. s, c, 0,
  854. 0, 0, 1
  855. );
  856. return this;
  857. }
  858. makeScale( x, y ) {
  859. this.set(
  860. x, 0, 0,
  861. 0, y, 0,
  862. 0, 0, 1
  863. );
  864. return this;
  865. }
  866. //
  867. equals( matrix ) {
  868. const te = this.elements;
  869. const me = matrix.elements;
  870. for ( let i = 0; i < 9; i ++ ) {
  871. if ( te[ i ] !== me[ i ] ) return false;
  872. }
  873. return true;
  874. }
  875. fromArray( array, offset = 0 ) {
  876. for ( let i = 0; i < 9; i ++ ) {
  877. this.elements[ i ] = array[ i + offset ];
  878. }
  879. return this;
  880. }
  881. toArray( array = [], offset = 0 ) {
  882. const te = this.elements;
  883. array[ offset ] = te[ 0 ];
  884. array[ offset + 1 ] = te[ 1 ];
  885. array[ offset + 2 ] = te[ 2 ];
  886. array[ offset + 3 ] = te[ 3 ];
  887. array[ offset + 4 ] = te[ 4 ];
  888. array[ offset + 5 ] = te[ 5 ];
  889. array[ offset + 6 ] = te[ 6 ];
  890. array[ offset + 7 ] = te[ 7 ];
  891. array[ offset + 8 ] = te[ 8 ];
  892. return array;
  893. }
  894. clone() {
  895. return new this.constructor().fromArray( this.elements );
  896. }
  897. }
  898. const _m3 = /*@__PURE__*/ new Matrix3();
  899. function arrayNeedsUint32( array ) {
  900. // assumes larger values usually on last
  901. for ( let i = array.length - 1; i >= 0; -- i ) {
  902. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  903. }
  904. return false;
  905. }
  906. const TYPED_ARRAYS = {
  907. Int8Array: Int8Array,
  908. Uint8Array: Uint8Array,
  909. Uint8ClampedArray: Uint8ClampedArray,
  910. Int16Array: Int16Array,
  911. Uint16Array: Uint16Array,
  912. Int32Array: Int32Array,
  913. Uint32Array: Uint32Array,
  914. Float32Array: Float32Array,
  915. Float64Array: Float64Array
  916. };
  917. function getTypedArray( type, buffer ) {
  918. return new TYPED_ARRAYS[ type ]( buffer );
  919. }
  920. function createElementNS( name ) {
  921. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  922. }
  923. function deepClone( value ) {
  924. if ( typeof structuredClone === 'function' ) {
  925. return structuredClone( value );
  926. }
  927. return JSON.parse( JSON.stringify( value ) );
  928. }
  929. function SRGBToLinear( c ) {
  930. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  931. }
  932. function LinearToSRGB( c ) {
  933. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  934. }
  935. /**
  936. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  937. * or clipping. Based on W3C specifications for sRGB and Display P3,
  938. * and ICC specifications for the D50 connection space. Values in/out
  939. * are _linear_ sRGB and _linear_ Display P3.
  940. *
  941. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  942. *
  943. * Reference:
  944. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  945. */
  946. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().fromArray( [
  947. 0.8224621, 0.0331941, 0.0170827,
  948. 0.1775380, 0.9668058, 0.0723974,
  949. - 0.0000001, 0.0000001, 0.9105199
  950. ] );
  951. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().fromArray( [
  952. 1.2249401, - 0.0420569, - 0.0196376,
  953. - 0.2249404, 1.0420571, - 0.0786361,
  954. 0.0000001, 0.0000000, 1.0982735
  955. ] );
  956. function DisplayP3ToLinearSRGB( color ) {
  957. // Display P3 uses the sRGB transfer functions
  958. return color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB );
  959. }
  960. function LinearSRGBToDisplayP3( color ) {
  961. // Display P3 uses the sRGB transfer functions
  962. return color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB();
  963. }
  964. // Conversions from <source> to Linear-sRGB reference space.
  965. const TO_LINEAR = {
  966. [ LinearSRGBColorSpace ]: ( color ) => color,
  967. [ SRGBColorSpace ]: ( color ) => color.convertSRGBToLinear(),
  968. [ DisplayP3ColorSpace ]: DisplayP3ToLinearSRGB,
  969. };
  970. // Conversions to <target> from Linear-sRGB reference space.
  971. const FROM_LINEAR = {
  972. [ LinearSRGBColorSpace ]: ( color ) => color,
  973. [ SRGBColorSpace ]: ( color ) => color.convertLinearToSRGB(),
  974. [ DisplayP3ColorSpace ]: LinearSRGBToDisplayP3,
  975. };
  976. const ColorManagement = {
  977. enabled: false,
  978. get legacyMode() {
  979. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  980. return ! this.enabled;
  981. },
  982. set legacyMode( legacyMode ) {
  983. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  984. this.enabled = ! legacyMode;
  985. },
  986. get workingColorSpace() {
  987. return LinearSRGBColorSpace;
  988. },
  989. set workingColorSpace( colorSpace ) {
  990. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  991. },
  992. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  993. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  994. return color;
  995. }
  996. const sourceToLinear = TO_LINEAR[ sourceColorSpace ];
  997. const targetFromLinear = FROM_LINEAR[ targetColorSpace ];
  998. if ( sourceToLinear === undefined || targetFromLinear === undefined ) {
  999. throw new Error( `Unsupported color space conversion, "${ sourceColorSpace }" to "${ targetColorSpace }".` );
  1000. }
  1001. return targetFromLinear( sourceToLinear( color ) );
  1002. },
  1003. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1004. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1005. },
  1006. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1007. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1008. },
  1009. };
  1010. let _canvas;
  1011. class ImageUtils {
  1012. static getDataURL( image ) {
  1013. if ( /^data:/i.test( image.src ) ) {
  1014. return image.src;
  1015. }
  1016. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1017. return image.src;
  1018. }
  1019. let canvas;
  1020. if ( image instanceof HTMLCanvasElement ) {
  1021. canvas = image;
  1022. } else {
  1023. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1024. _canvas.width = image.width;
  1025. _canvas.height = image.height;
  1026. const context = _canvas.getContext( '2d' );
  1027. if ( image instanceof ImageData ) {
  1028. context.putImageData( image, 0, 0 );
  1029. } else {
  1030. context.drawImage( image, 0, 0, image.width, image.height );
  1031. }
  1032. canvas = _canvas;
  1033. }
  1034. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1035. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1036. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1037. } else {
  1038. return canvas.toDataURL( 'image/png' );
  1039. }
  1040. }
  1041. static sRGBToLinear( image ) {
  1042. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1043. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1044. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1045. const canvas = createElementNS( 'canvas' );
  1046. canvas.width = image.width;
  1047. canvas.height = image.height;
  1048. const context = canvas.getContext( '2d' );
  1049. context.drawImage( image, 0, 0, image.width, image.height );
  1050. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1051. const data = imageData.data;
  1052. for ( let i = 0; i < data.length; i ++ ) {
  1053. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1054. }
  1055. context.putImageData( imageData, 0, 0 );
  1056. return canvas;
  1057. } else if ( image.data ) {
  1058. const data = image.data.slice( 0 );
  1059. for ( let i = 0; i < data.length; i ++ ) {
  1060. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1061. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1062. } else {
  1063. // assuming float
  1064. data[ i ] = SRGBToLinear( data[ i ] );
  1065. }
  1066. }
  1067. return {
  1068. data: data,
  1069. width: image.width,
  1070. height: image.height
  1071. };
  1072. } else {
  1073. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1074. return image;
  1075. }
  1076. }
  1077. }
  1078. class Source {
  1079. constructor( data = null ) {
  1080. this.isSource = true;
  1081. this.uuid = generateUUID();
  1082. this.data = data;
  1083. this.version = 0;
  1084. }
  1085. set needsUpdate( value ) {
  1086. if ( value === true ) this.version ++;
  1087. }
  1088. toJSON( meta ) {
  1089. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1090. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1091. return meta.images[ this.uuid ];
  1092. }
  1093. const output = {
  1094. uuid: this.uuid,
  1095. url: ''
  1096. };
  1097. const data = this.data;
  1098. if ( data !== null ) {
  1099. let url;
  1100. if ( Array.isArray( data ) ) {
  1101. // cube texture
  1102. url = [];
  1103. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1104. if ( data[ i ].isDataTexture ) {
  1105. url.push( serializeImage( data[ i ].image ) );
  1106. } else {
  1107. url.push( serializeImage( data[ i ] ) );
  1108. }
  1109. }
  1110. } else {
  1111. // texture
  1112. url = serializeImage( data );
  1113. }
  1114. output.url = url;
  1115. }
  1116. if ( ! isRootObject ) {
  1117. meta.images[ this.uuid ] = output;
  1118. }
  1119. return output;
  1120. }
  1121. }
  1122. function serializeImage( image ) {
  1123. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1124. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1125. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1126. // default images
  1127. return ImageUtils.getDataURL( image );
  1128. } else {
  1129. if ( image.data ) {
  1130. // images of DataTexture
  1131. return {
  1132. data: Array.from( image.data ),
  1133. width: image.width,
  1134. height: image.height,
  1135. type: image.data.constructor.name
  1136. };
  1137. } else {
  1138. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1139. return {};
  1140. }
  1141. }
  1142. }
  1143. let textureId = 0;
  1144. class Texture extends EventDispatcher {
  1145. 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, encoding = LinearEncoding ) {
  1146. super();
  1147. this.isTexture = true;
  1148. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1149. this.uuid = generateUUID();
  1150. this.name = '';
  1151. this.source = new Source( image );
  1152. this.mipmaps = [];
  1153. this.mapping = mapping;
  1154. this.channel = 0;
  1155. this.wrapS = wrapS;
  1156. this.wrapT = wrapT;
  1157. this.magFilter = magFilter;
  1158. this.minFilter = minFilter;
  1159. this.anisotropy = anisotropy;
  1160. this.format = format;
  1161. this.internalFormat = null;
  1162. this.type = type;
  1163. this.offset = new Vector2( 0, 0 );
  1164. this.repeat = new Vector2( 1, 1 );
  1165. this.center = new Vector2( 0, 0 );
  1166. this.rotation = 0;
  1167. this.matrixAutoUpdate = true;
  1168. this.matrix = new Matrix3();
  1169. this.generateMipmaps = true;
  1170. this.premultiplyAlpha = false;
  1171. this.flipY = true;
  1172. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1173. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1174. //
  1175. // Also changing the encoding after already used by a Material will not automatically make the Material
  1176. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1177. this.encoding = encoding;
  1178. this.userData = {};
  1179. this.version = 0;
  1180. this.onUpdate = null;
  1181. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1182. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1183. }
  1184. get image() {
  1185. return this.source.data;
  1186. }
  1187. set image( value = null ) {
  1188. this.source.data = value;
  1189. }
  1190. updateMatrix() {
  1191. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1192. }
  1193. clone() {
  1194. return new this.constructor().copy( this );
  1195. }
  1196. copy( source ) {
  1197. this.name = source.name;
  1198. this.source = source.source;
  1199. this.mipmaps = source.mipmaps.slice( 0 );
  1200. this.mapping = source.mapping;
  1201. this.channel = source.channel;
  1202. this.wrapS = source.wrapS;
  1203. this.wrapT = source.wrapT;
  1204. this.magFilter = source.magFilter;
  1205. this.minFilter = source.minFilter;
  1206. this.anisotropy = source.anisotropy;
  1207. this.format = source.format;
  1208. this.internalFormat = source.internalFormat;
  1209. this.type = source.type;
  1210. this.offset.copy( source.offset );
  1211. this.repeat.copy( source.repeat );
  1212. this.center.copy( source.center );
  1213. this.rotation = source.rotation;
  1214. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1215. this.matrix.copy( source.matrix );
  1216. this.generateMipmaps = source.generateMipmaps;
  1217. this.premultiplyAlpha = source.premultiplyAlpha;
  1218. this.flipY = source.flipY;
  1219. this.unpackAlignment = source.unpackAlignment;
  1220. this.encoding = source.encoding;
  1221. this.userData = deepClone( source.userData );
  1222. this.needsUpdate = true;
  1223. return this;
  1224. }
  1225. toJSON( meta ) {
  1226. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1227. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1228. return meta.textures[ this.uuid ];
  1229. }
  1230. const output = {
  1231. metadata: {
  1232. version: 4.5,
  1233. type: 'Texture',
  1234. generator: 'Texture.toJSON'
  1235. },
  1236. uuid: this.uuid,
  1237. name: this.name,
  1238. image: this.source.toJSON( meta ).uuid,
  1239. mapping: this.mapping,
  1240. channel: this.channel,
  1241. repeat: [ this.repeat.x, this.repeat.y ],
  1242. offset: [ this.offset.x, this.offset.y ],
  1243. center: [ this.center.x, this.center.y ],
  1244. rotation: this.rotation,
  1245. wrap: [ this.wrapS, this.wrapT ],
  1246. format: this.format,
  1247. internalFormat: this.internalFormat,
  1248. type: this.type,
  1249. encoding: this.encoding,
  1250. minFilter: this.minFilter,
  1251. magFilter: this.magFilter,
  1252. anisotropy: this.anisotropy,
  1253. flipY: this.flipY,
  1254. generateMipmaps: this.generateMipmaps,
  1255. premultiplyAlpha: this.premultiplyAlpha,
  1256. unpackAlignment: this.unpackAlignment
  1257. };
  1258. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1259. if ( ! isRootObject ) {
  1260. meta.textures[ this.uuid ] = output;
  1261. }
  1262. return output;
  1263. }
  1264. dispose() {
  1265. this.dispatchEvent( { type: 'dispose' } );
  1266. }
  1267. transformUv( uv ) {
  1268. if ( this.mapping !== UVMapping ) return uv;
  1269. uv.applyMatrix3( this.matrix );
  1270. if ( uv.x < 0 || uv.x > 1 ) {
  1271. switch ( this.wrapS ) {
  1272. case RepeatWrapping:
  1273. uv.x = uv.x - Math.floor( uv.x );
  1274. break;
  1275. case ClampToEdgeWrapping:
  1276. uv.x = uv.x < 0 ? 0 : 1;
  1277. break;
  1278. case MirroredRepeatWrapping:
  1279. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1280. uv.x = Math.ceil( uv.x ) - uv.x;
  1281. } else {
  1282. uv.x = uv.x - Math.floor( uv.x );
  1283. }
  1284. break;
  1285. }
  1286. }
  1287. if ( uv.y < 0 || uv.y > 1 ) {
  1288. switch ( this.wrapT ) {
  1289. case RepeatWrapping:
  1290. uv.y = uv.y - Math.floor( uv.y );
  1291. break;
  1292. case ClampToEdgeWrapping:
  1293. uv.y = uv.y < 0 ? 0 : 1;
  1294. break;
  1295. case MirroredRepeatWrapping:
  1296. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1297. uv.y = Math.ceil( uv.y ) - uv.y;
  1298. } else {
  1299. uv.y = uv.y - Math.floor( uv.y );
  1300. }
  1301. break;
  1302. }
  1303. }
  1304. if ( this.flipY ) {
  1305. uv.y = 1 - uv.y;
  1306. }
  1307. return uv;
  1308. }
  1309. set needsUpdate( value ) {
  1310. if ( value === true ) {
  1311. this.version ++;
  1312. this.source.needsUpdate = true;
  1313. }
  1314. }
  1315. }
  1316. Texture.DEFAULT_IMAGE = null;
  1317. Texture.DEFAULT_MAPPING = UVMapping;
  1318. Texture.DEFAULT_ANISOTROPY = 1;
  1319. class Vector4 {
  1320. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1321. Vector4.prototype.isVector4 = true;
  1322. this.x = x;
  1323. this.y = y;
  1324. this.z = z;
  1325. this.w = w;
  1326. }
  1327. get width() {
  1328. return this.z;
  1329. }
  1330. set width( value ) {
  1331. this.z = value;
  1332. }
  1333. get height() {
  1334. return this.w;
  1335. }
  1336. set height( value ) {
  1337. this.w = value;
  1338. }
  1339. set( x, y, z, w ) {
  1340. this.x = x;
  1341. this.y = y;
  1342. this.z = z;
  1343. this.w = w;
  1344. return this;
  1345. }
  1346. setScalar( scalar ) {
  1347. this.x = scalar;
  1348. this.y = scalar;
  1349. this.z = scalar;
  1350. this.w = scalar;
  1351. return this;
  1352. }
  1353. setX( x ) {
  1354. this.x = x;
  1355. return this;
  1356. }
  1357. setY( y ) {
  1358. this.y = y;
  1359. return this;
  1360. }
  1361. setZ( z ) {
  1362. this.z = z;
  1363. return this;
  1364. }
  1365. setW( w ) {
  1366. this.w = w;
  1367. return this;
  1368. }
  1369. setComponent( index, value ) {
  1370. switch ( index ) {
  1371. case 0: this.x = value; break;
  1372. case 1: this.y = value; break;
  1373. case 2: this.z = value; break;
  1374. case 3: this.w = value; break;
  1375. default: throw new Error( 'index is out of range: ' + index );
  1376. }
  1377. return this;
  1378. }
  1379. getComponent( index ) {
  1380. switch ( index ) {
  1381. case 0: return this.x;
  1382. case 1: return this.y;
  1383. case 2: return this.z;
  1384. case 3: return this.w;
  1385. default: throw new Error( 'index is out of range: ' + index );
  1386. }
  1387. }
  1388. clone() {
  1389. return new this.constructor( this.x, this.y, this.z, this.w );
  1390. }
  1391. copy( v ) {
  1392. this.x = v.x;
  1393. this.y = v.y;
  1394. this.z = v.z;
  1395. this.w = ( v.w !== undefined ) ? v.w : 1;
  1396. return this;
  1397. }
  1398. add( v ) {
  1399. this.x += v.x;
  1400. this.y += v.y;
  1401. this.z += v.z;
  1402. this.w += v.w;
  1403. return this;
  1404. }
  1405. addScalar( s ) {
  1406. this.x += s;
  1407. this.y += s;
  1408. this.z += s;
  1409. this.w += s;
  1410. return this;
  1411. }
  1412. addVectors( a, b ) {
  1413. this.x = a.x + b.x;
  1414. this.y = a.y + b.y;
  1415. this.z = a.z + b.z;
  1416. this.w = a.w + b.w;
  1417. return this;
  1418. }
  1419. addScaledVector( v, s ) {
  1420. this.x += v.x * s;
  1421. this.y += v.y * s;
  1422. this.z += v.z * s;
  1423. this.w += v.w * s;
  1424. return this;
  1425. }
  1426. sub( v ) {
  1427. this.x -= v.x;
  1428. this.y -= v.y;
  1429. this.z -= v.z;
  1430. this.w -= v.w;
  1431. return this;
  1432. }
  1433. subScalar( s ) {
  1434. this.x -= s;
  1435. this.y -= s;
  1436. this.z -= s;
  1437. this.w -= s;
  1438. return this;
  1439. }
  1440. subVectors( a, b ) {
  1441. this.x = a.x - b.x;
  1442. this.y = a.y - b.y;
  1443. this.z = a.z - b.z;
  1444. this.w = a.w - b.w;
  1445. return this;
  1446. }
  1447. multiply( v ) {
  1448. this.x *= v.x;
  1449. this.y *= v.y;
  1450. this.z *= v.z;
  1451. this.w *= v.w;
  1452. return this;
  1453. }
  1454. multiplyScalar( scalar ) {
  1455. this.x *= scalar;
  1456. this.y *= scalar;
  1457. this.z *= scalar;
  1458. this.w *= scalar;
  1459. return this;
  1460. }
  1461. applyMatrix4( m ) {
  1462. const x = this.x, y = this.y, z = this.z, w = this.w;
  1463. const e = m.elements;
  1464. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1465. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1466. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1467. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1468. return this;
  1469. }
  1470. divideScalar( scalar ) {
  1471. return this.multiplyScalar( 1 / scalar );
  1472. }
  1473. setAxisAngleFromQuaternion( q ) {
  1474. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1475. // q is assumed to be normalized
  1476. this.w = 2 * Math.acos( q.w );
  1477. const s = Math.sqrt( 1 - q.w * q.w );
  1478. if ( s < 0.0001 ) {
  1479. this.x = 1;
  1480. this.y = 0;
  1481. this.z = 0;
  1482. } else {
  1483. this.x = q.x / s;
  1484. this.y = q.y / s;
  1485. this.z = q.z / s;
  1486. }
  1487. return this;
  1488. }
  1489. setAxisAngleFromRotationMatrix( m ) {
  1490. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1491. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1492. let angle, x, y, z; // variables for result
  1493. const epsilon = 0.01, // margin to allow for rounding errors
  1494. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1495. te = m.elements,
  1496. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1497. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1498. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1499. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1500. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1501. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1502. // singularity found
  1503. // first check for identity matrix which must have +1 for all terms
  1504. // in leading diagonal and zero in other terms
  1505. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1506. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1507. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1508. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1509. // this singularity is identity matrix so angle = 0
  1510. this.set( 1, 0, 0, 0 );
  1511. return this; // zero angle, arbitrary axis
  1512. }
  1513. // otherwise this singularity is angle = 180
  1514. angle = Math.PI;
  1515. const xx = ( m11 + 1 ) / 2;
  1516. const yy = ( m22 + 1 ) / 2;
  1517. const zz = ( m33 + 1 ) / 2;
  1518. const xy = ( m12 + m21 ) / 4;
  1519. const xz = ( m13 + m31 ) / 4;
  1520. const yz = ( m23 + m32 ) / 4;
  1521. if ( ( xx > yy ) && ( xx > zz ) ) {
  1522. // m11 is the largest diagonal term
  1523. if ( xx < epsilon ) {
  1524. x = 0;
  1525. y = 0.707106781;
  1526. z = 0.707106781;
  1527. } else {
  1528. x = Math.sqrt( xx );
  1529. y = xy / x;
  1530. z = xz / x;
  1531. }
  1532. } else if ( yy > zz ) {
  1533. // m22 is the largest diagonal term
  1534. if ( yy < epsilon ) {
  1535. x = 0.707106781;
  1536. y = 0;
  1537. z = 0.707106781;
  1538. } else {
  1539. y = Math.sqrt( yy );
  1540. x = xy / y;
  1541. z = yz / y;
  1542. }
  1543. } else {
  1544. // m33 is the largest diagonal term so base result on this
  1545. if ( zz < epsilon ) {
  1546. x = 0.707106781;
  1547. y = 0.707106781;
  1548. z = 0;
  1549. } else {
  1550. z = Math.sqrt( zz );
  1551. x = xz / z;
  1552. y = yz / z;
  1553. }
  1554. }
  1555. this.set( x, y, z, angle );
  1556. return this; // return 180 deg rotation
  1557. }
  1558. // as we have reached here there are no singularities so we can handle normally
  1559. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1560. ( m13 - m31 ) * ( m13 - m31 ) +
  1561. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1562. if ( Math.abs( s ) < 0.001 ) s = 1;
  1563. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1564. // caught by singularity test above, but I've left it in just in case
  1565. this.x = ( m32 - m23 ) / s;
  1566. this.y = ( m13 - m31 ) / s;
  1567. this.z = ( m21 - m12 ) / s;
  1568. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1569. return this;
  1570. }
  1571. min( v ) {
  1572. this.x = Math.min( this.x, v.x );
  1573. this.y = Math.min( this.y, v.y );
  1574. this.z = Math.min( this.z, v.z );
  1575. this.w = Math.min( this.w, v.w );
  1576. return this;
  1577. }
  1578. max( v ) {
  1579. this.x = Math.max( this.x, v.x );
  1580. this.y = Math.max( this.y, v.y );
  1581. this.z = Math.max( this.z, v.z );
  1582. this.w = Math.max( this.w, v.w );
  1583. return this;
  1584. }
  1585. clamp( min, max ) {
  1586. // assumes min < max, componentwise
  1587. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1588. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1589. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1590. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1591. return this;
  1592. }
  1593. clampScalar( minVal, maxVal ) {
  1594. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1595. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1596. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1597. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1598. return this;
  1599. }
  1600. clampLength( min, max ) {
  1601. const length = this.length();
  1602. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1603. }
  1604. floor() {
  1605. this.x = Math.floor( this.x );
  1606. this.y = Math.floor( this.y );
  1607. this.z = Math.floor( this.z );
  1608. this.w = Math.floor( this.w );
  1609. return this;
  1610. }
  1611. ceil() {
  1612. this.x = Math.ceil( this.x );
  1613. this.y = Math.ceil( this.y );
  1614. this.z = Math.ceil( this.z );
  1615. this.w = Math.ceil( this.w );
  1616. return this;
  1617. }
  1618. round() {
  1619. this.x = Math.round( this.x );
  1620. this.y = Math.round( this.y );
  1621. this.z = Math.round( this.z );
  1622. this.w = Math.round( this.w );
  1623. return this;
  1624. }
  1625. roundToZero() {
  1626. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1627. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1628. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1629. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1630. return this;
  1631. }
  1632. negate() {
  1633. this.x = - this.x;
  1634. this.y = - this.y;
  1635. this.z = - this.z;
  1636. this.w = - this.w;
  1637. return this;
  1638. }
  1639. dot( v ) {
  1640. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1641. }
  1642. lengthSq() {
  1643. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1644. }
  1645. length() {
  1646. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1647. }
  1648. manhattanLength() {
  1649. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1650. }
  1651. normalize() {
  1652. return this.divideScalar( this.length() || 1 );
  1653. }
  1654. setLength( length ) {
  1655. return this.normalize().multiplyScalar( length );
  1656. }
  1657. lerp( v, alpha ) {
  1658. this.x += ( v.x - this.x ) * alpha;
  1659. this.y += ( v.y - this.y ) * alpha;
  1660. this.z += ( v.z - this.z ) * alpha;
  1661. this.w += ( v.w - this.w ) * alpha;
  1662. return this;
  1663. }
  1664. lerpVectors( v1, v2, alpha ) {
  1665. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1666. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1667. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1668. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1669. return this;
  1670. }
  1671. equals( v ) {
  1672. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1673. }
  1674. fromArray( array, offset = 0 ) {
  1675. this.x = array[ offset ];
  1676. this.y = array[ offset + 1 ];
  1677. this.z = array[ offset + 2 ];
  1678. this.w = array[ offset + 3 ];
  1679. return this;
  1680. }
  1681. toArray( array = [], offset = 0 ) {
  1682. array[ offset ] = this.x;
  1683. array[ offset + 1 ] = this.y;
  1684. array[ offset + 2 ] = this.z;
  1685. array[ offset + 3 ] = this.w;
  1686. return array;
  1687. }
  1688. fromBufferAttribute( attribute, index ) {
  1689. this.x = attribute.getX( index );
  1690. this.y = attribute.getY( index );
  1691. this.z = attribute.getZ( index );
  1692. this.w = attribute.getW( index );
  1693. return this;
  1694. }
  1695. random() {
  1696. this.x = Math.random();
  1697. this.y = Math.random();
  1698. this.z = Math.random();
  1699. this.w = Math.random();
  1700. return this;
  1701. }
  1702. *[ Symbol.iterator ]() {
  1703. yield this.x;
  1704. yield this.y;
  1705. yield this.z;
  1706. yield this.w;
  1707. }
  1708. }
  1709. /*
  1710. In options, we can specify:
  1711. * Texture parameters for an auto-generated target texture
  1712. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1713. */
  1714. class WebGLRenderTarget extends EventDispatcher {
  1715. constructor( width = 1, height = 1, options = {} ) {
  1716. super();
  1717. this.isWebGLRenderTarget = true;
  1718. this.width = width;
  1719. this.height = height;
  1720. this.depth = 1;
  1721. this.scissor = new Vector4( 0, 0, width, height );
  1722. this.scissorTest = false;
  1723. this.viewport = new Vector4( 0, 0, width, height );
  1724. const image = { width: width, height: height, depth: 1 };
  1725. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1726. this.texture.isRenderTargetTexture = true;
  1727. this.texture.flipY = false;
  1728. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1729. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1730. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1731. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1732. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1733. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1734. this.samples = options.samples !== undefined ? options.samples : 0;
  1735. }
  1736. setSize( width, height, depth = 1 ) {
  1737. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1738. this.width = width;
  1739. this.height = height;
  1740. this.depth = depth;
  1741. this.texture.image.width = width;
  1742. this.texture.image.height = height;
  1743. this.texture.image.depth = depth;
  1744. this.dispose();
  1745. }
  1746. this.viewport.set( 0, 0, width, height );
  1747. this.scissor.set( 0, 0, width, height );
  1748. }
  1749. clone() {
  1750. return new this.constructor().copy( this );
  1751. }
  1752. copy( source ) {
  1753. this.width = source.width;
  1754. this.height = source.height;
  1755. this.depth = source.depth;
  1756. this.viewport.copy( source.viewport );
  1757. this.texture = source.texture.clone();
  1758. this.texture.isRenderTargetTexture = true;
  1759. // ensure image object is not shared, see #20328
  1760. const image = Object.assign( {}, source.texture.image );
  1761. this.texture.source = new Source( image );
  1762. this.depthBuffer = source.depthBuffer;
  1763. this.stencilBuffer = source.stencilBuffer;
  1764. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1765. this.samples = source.samples;
  1766. return this;
  1767. }
  1768. dispose() {
  1769. this.dispatchEvent( { type: 'dispose' } );
  1770. }
  1771. }
  1772. class DataArrayTexture extends Texture {
  1773. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1774. super( null );
  1775. this.isDataArrayTexture = true;
  1776. this.image = { data, width, height, depth };
  1777. this.magFilter = NearestFilter;
  1778. this.minFilter = NearestFilter;
  1779. this.wrapR = ClampToEdgeWrapping;
  1780. this.generateMipmaps = false;
  1781. this.flipY = false;
  1782. this.unpackAlignment = 1;
  1783. }
  1784. }
  1785. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1786. constructor( width = 1, height = 1, depth = 1 ) {
  1787. super( width, height );
  1788. this.isWebGLArrayRenderTarget = true;
  1789. this.depth = depth;
  1790. this.texture = new DataArrayTexture( null, width, height, depth );
  1791. this.texture.isRenderTargetTexture = true;
  1792. }
  1793. }
  1794. class Data3DTexture extends Texture {
  1795. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1796. // We're going to add .setXXX() methods for setting properties later.
  1797. // Users can still set in DataTexture3D directly.
  1798. //
  1799. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1800. // texture.anisotropy = 16;
  1801. //
  1802. // See #14839
  1803. super( null );
  1804. this.isData3DTexture = true;
  1805. this.image = { data, width, height, depth };
  1806. this.magFilter = NearestFilter;
  1807. this.minFilter = NearestFilter;
  1808. this.wrapR = ClampToEdgeWrapping;
  1809. this.generateMipmaps = false;
  1810. this.flipY = false;
  1811. this.unpackAlignment = 1;
  1812. }
  1813. }
  1814. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1815. constructor( width = 1, height = 1, depth = 1 ) {
  1816. super( width, height );
  1817. this.isWebGL3DRenderTarget = true;
  1818. this.depth = depth;
  1819. this.texture = new Data3DTexture( null, width, height, depth );
  1820. this.texture.isRenderTargetTexture = true;
  1821. }
  1822. }
  1823. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1824. constructor( width = 1, height = 1, count = 1, options = {} ) {
  1825. super( width, height, options );
  1826. this.isWebGLMultipleRenderTargets = true;
  1827. const texture = this.texture;
  1828. this.texture = [];
  1829. for ( let i = 0; i < count; i ++ ) {
  1830. this.texture[ i ] = texture.clone();
  1831. this.texture[ i ].isRenderTargetTexture = true;
  1832. }
  1833. }
  1834. setSize( width, height, depth = 1 ) {
  1835. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1836. this.width = width;
  1837. this.height = height;
  1838. this.depth = depth;
  1839. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1840. this.texture[ i ].image.width = width;
  1841. this.texture[ i ].image.height = height;
  1842. this.texture[ i ].image.depth = depth;
  1843. }
  1844. this.dispose();
  1845. }
  1846. this.viewport.set( 0, 0, width, height );
  1847. this.scissor.set( 0, 0, width, height );
  1848. return this;
  1849. }
  1850. copy( source ) {
  1851. this.dispose();
  1852. this.width = source.width;
  1853. this.height = source.height;
  1854. this.depth = source.depth;
  1855. this.viewport.set( 0, 0, this.width, this.height );
  1856. this.scissor.set( 0, 0, this.width, this.height );
  1857. this.depthBuffer = source.depthBuffer;
  1858. this.stencilBuffer = source.stencilBuffer;
  1859. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1860. this.texture.length = 0;
  1861. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1862. this.texture[ i ] = source.texture[ i ].clone();
  1863. this.texture[ i ].isRenderTargetTexture = true;
  1864. }
  1865. return this;
  1866. }
  1867. }
  1868. class Quaternion {
  1869. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1870. this.isQuaternion = true;
  1871. this._x = x;
  1872. this._y = y;
  1873. this._z = z;
  1874. this._w = w;
  1875. }
  1876. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1877. // fuzz-free, array-based Quaternion SLERP operation
  1878. let x0 = src0[ srcOffset0 + 0 ],
  1879. y0 = src0[ srcOffset0 + 1 ],
  1880. z0 = src0[ srcOffset0 + 2 ],
  1881. w0 = src0[ srcOffset0 + 3 ];
  1882. const x1 = src1[ srcOffset1 + 0 ],
  1883. y1 = src1[ srcOffset1 + 1 ],
  1884. z1 = src1[ srcOffset1 + 2 ],
  1885. w1 = src1[ srcOffset1 + 3 ];
  1886. if ( t === 0 ) {
  1887. dst[ dstOffset + 0 ] = x0;
  1888. dst[ dstOffset + 1 ] = y0;
  1889. dst[ dstOffset + 2 ] = z0;
  1890. dst[ dstOffset + 3 ] = w0;
  1891. return;
  1892. }
  1893. if ( t === 1 ) {
  1894. dst[ dstOffset + 0 ] = x1;
  1895. dst[ dstOffset + 1 ] = y1;
  1896. dst[ dstOffset + 2 ] = z1;
  1897. dst[ dstOffset + 3 ] = w1;
  1898. return;
  1899. }
  1900. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1901. let s = 1 - t;
  1902. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1903. dir = ( cos >= 0 ? 1 : - 1 ),
  1904. sqrSin = 1 - cos * cos;
  1905. // Skip the Slerp for tiny steps to avoid numeric problems:
  1906. if ( sqrSin > Number.EPSILON ) {
  1907. const sin = Math.sqrt( sqrSin ),
  1908. len = Math.atan2( sin, cos * dir );
  1909. s = Math.sin( s * len ) / sin;
  1910. t = Math.sin( t * len ) / sin;
  1911. }
  1912. const tDir = t * dir;
  1913. x0 = x0 * s + x1 * tDir;
  1914. y0 = y0 * s + y1 * tDir;
  1915. z0 = z0 * s + z1 * tDir;
  1916. w0 = w0 * s + w1 * tDir;
  1917. // Normalize in case we just did a lerp:
  1918. if ( s === 1 - t ) {
  1919. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1920. x0 *= f;
  1921. y0 *= f;
  1922. z0 *= f;
  1923. w0 *= f;
  1924. }
  1925. }
  1926. dst[ dstOffset ] = x0;
  1927. dst[ dstOffset + 1 ] = y0;
  1928. dst[ dstOffset + 2 ] = z0;
  1929. dst[ dstOffset + 3 ] = w0;
  1930. }
  1931. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1932. const x0 = src0[ srcOffset0 ];
  1933. const y0 = src0[ srcOffset0 + 1 ];
  1934. const z0 = src0[ srcOffset0 + 2 ];
  1935. const w0 = src0[ srcOffset0 + 3 ];
  1936. const x1 = src1[ srcOffset1 ];
  1937. const y1 = src1[ srcOffset1 + 1 ];
  1938. const z1 = src1[ srcOffset1 + 2 ];
  1939. const w1 = src1[ srcOffset1 + 3 ];
  1940. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1941. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1942. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1943. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1944. return dst;
  1945. }
  1946. get x() {
  1947. return this._x;
  1948. }
  1949. set x( value ) {
  1950. this._x = value;
  1951. this._onChangeCallback();
  1952. }
  1953. get y() {
  1954. return this._y;
  1955. }
  1956. set y( value ) {
  1957. this._y = value;
  1958. this._onChangeCallback();
  1959. }
  1960. get z() {
  1961. return this._z;
  1962. }
  1963. set z( value ) {
  1964. this._z = value;
  1965. this._onChangeCallback();
  1966. }
  1967. get w() {
  1968. return this._w;
  1969. }
  1970. set w( value ) {
  1971. this._w = value;
  1972. this._onChangeCallback();
  1973. }
  1974. set( x, y, z, w ) {
  1975. this._x = x;
  1976. this._y = y;
  1977. this._z = z;
  1978. this._w = w;
  1979. this._onChangeCallback();
  1980. return this;
  1981. }
  1982. clone() {
  1983. return new this.constructor( this._x, this._y, this._z, this._w );
  1984. }
  1985. copy( quaternion ) {
  1986. this._x = quaternion.x;
  1987. this._y = quaternion.y;
  1988. this._z = quaternion.z;
  1989. this._w = quaternion.w;
  1990. this._onChangeCallback();
  1991. return this;
  1992. }
  1993. setFromEuler( euler, update ) {
  1994. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1995. // http://www.mathworks.com/matlabcentral/fileexchange/
  1996. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1997. // content/SpinCalc.m
  1998. const cos = Math.cos;
  1999. const sin = Math.sin;
  2000. const c1 = cos( x / 2 );
  2001. const c2 = cos( y / 2 );
  2002. const c3 = cos( z / 2 );
  2003. const s1 = sin( x / 2 );
  2004. const s2 = sin( y / 2 );
  2005. const s3 = sin( z / 2 );
  2006. switch ( order ) {
  2007. case 'XYZ':
  2008. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2009. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2010. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2011. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2012. break;
  2013. case 'YXZ':
  2014. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2015. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2016. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2017. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2018. break;
  2019. case 'ZXY':
  2020. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2021. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2022. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2023. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2024. break;
  2025. case 'ZYX':
  2026. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2027. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2028. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2029. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2030. break;
  2031. case 'YZX':
  2032. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2033. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2034. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2035. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2036. break;
  2037. case 'XZY':
  2038. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2039. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2040. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2041. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2042. break;
  2043. default:
  2044. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2045. }
  2046. if ( update !== false ) this._onChangeCallback();
  2047. return this;
  2048. }
  2049. setFromAxisAngle( axis, angle ) {
  2050. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2051. // assumes axis is normalized
  2052. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2053. this._x = axis.x * s;
  2054. this._y = axis.y * s;
  2055. this._z = axis.z * s;
  2056. this._w = Math.cos( halfAngle );
  2057. this._onChangeCallback();
  2058. return this;
  2059. }
  2060. setFromRotationMatrix( m ) {
  2061. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2062. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2063. const te = m.elements,
  2064. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2065. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2066. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2067. trace = m11 + m22 + m33;
  2068. if ( trace > 0 ) {
  2069. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2070. this._w = 0.25 / s;
  2071. this._x = ( m32 - m23 ) * s;
  2072. this._y = ( m13 - m31 ) * s;
  2073. this._z = ( m21 - m12 ) * s;
  2074. } else if ( m11 > m22 && m11 > m33 ) {
  2075. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2076. this._w = ( m32 - m23 ) / s;
  2077. this._x = 0.25 * s;
  2078. this._y = ( m12 + m21 ) / s;
  2079. this._z = ( m13 + m31 ) / s;
  2080. } else if ( m22 > m33 ) {
  2081. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2082. this._w = ( m13 - m31 ) / s;
  2083. this._x = ( m12 + m21 ) / s;
  2084. this._y = 0.25 * s;
  2085. this._z = ( m23 + m32 ) / s;
  2086. } else {
  2087. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2088. this._w = ( m21 - m12 ) / s;
  2089. this._x = ( m13 + m31 ) / s;
  2090. this._y = ( m23 + m32 ) / s;
  2091. this._z = 0.25 * s;
  2092. }
  2093. this._onChangeCallback();
  2094. return this;
  2095. }
  2096. setFromUnitVectors( vFrom, vTo ) {
  2097. // assumes direction vectors vFrom and vTo are normalized
  2098. let r = vFrom.dot( vTo ) + 1;
  2099. if ( r < Number.EPSILON ) {
  2100. // vFrom and vTo point in opposite directions
  2101. r = 0;
  2102. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2103. this._x = - vFrom.y;
  2104. this._y = vFrom.x;
  2105. this._z = 0;
  2106. this._w = r;
  2107. } else {
  2108. this._x = 0;
  2109. this._y = - vFrom.z;
  2110. this._z = vFrom.y;
  2111. this._w = r;
  2112. }
  2113. } else {
  2114. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2115. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2116. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2117. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2118. this._w = r;
  2119. }
  2120. return this.normalize();
  2121. }
  2122. angleTo( q ) {
  2123. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2124. }
  2125. rotateTowards( q, step ) {
  2126. const angle = this.angleTo( q );
  2127. if ( angle === 0 ) return this;
  2128. const t = Math.min( 1, step / angle );
  2129. this.slerp( q, t );
  2130. return this;
  2131. }
  2132. identity() {
  2133. return this.set( 0, 0, 0, 1 );
  2134. }
  2135. invert() {
  2136. // quaternion is assumed to have unit length
  2137. return this.conjugate();
  2138. }
  2139. conjugate() {
  2140. this._x *= - 1;
  2141. this._y *= - 1;
  2142. this._z *= - 1;
  2143. this._onChangeCallback();
  2144. return this;
  2145. }
  2146. dot( v ) {
  2147. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2148. }
  2149. lengthSq() {
  2150. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2151. }
  2152. length() {
  2153. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2154. }
  2155. normalize() {
  2156. let l = this.length();
  2157. if ( l === 0 ) {
  2158. this._x = 0;
  2159. this._y = 0;
  2160. this._z = 0;
  2161. this._w = 1;
  2162. } else {
  2163. l = 1 / l;
  2164. this._x = this._x * l;
  2165. this._y = this._y * l;
  2166. this._z = this._z * l;
  2167. this._w = this._w * l;
  2168. }
  2169. this._onChangeCallback();
  2170. return this;
  2171. }
  2172. multiply( q ) {
  2173. return this.multiplyQuaternions( this, q );
  2174. }
  2175. premultiply( q ) {
  2176. return this.multiplyQuaternions( q, this );
  2177. }
  2178. multiplyQuaternions( a, b ) {
  2179. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2180. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2181. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2182. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2183. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2184. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2185. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2186. this._onChangeCallback();
  2187. return this;
  2188. }
  2189. slerp( qb, t ) {
  2190. if ( t === 0 ) return this;
  2191. if ( t === 1 ) return this.copy( qb );
  2192. const x = this._x, y = this._y, z = this._z, w = this._w;
  2193. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2194. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2195. if ( cosHalfTheta < 0 ) {
  2196. this._w = - qb._w;
  2197. this._x = - qb._x;
  2198. this._y = - qb._y;
  2199. this._z = - qb._z;
  2200. cosHalfTheta = - cosHalfTheta;
  2201. } else {
  2202. this.copy( qb );
  2203. }
  2204. if ( cosHalfTheta >= 1.0 ) {
  2205. this._w = w;
  2206. this._x = x;
  2207. this._y = y;
  2208. this._z = z;
  2209. return this;
  2210. }
  2211. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2212. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2213. const s = 1 - t;
  2214. this._w = s * w + t * this._w;
  2215. this._x = s * x + t * this._x;
  2216. this._y = s * y + t * this._y;
  2217. this._z = s * z + t * this._z;
  2218. this.normalize();
  2219. this._onChangeCallback();
  2220. return this;
  2221. }
  2222. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2223. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2224. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2225. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2226. this._w = ( w * ratioA + this._w * ratioB );
  2227. this._x = ( x * ratioA + this._x * ratioB );
  2228. this._y = ( y * ratioA + this._y * ratioB );
  2229. this._z = ( z * ratioA + this._z * ratioB );
  2230. this._onChangeCallback();
  2231. return this;
  2232. }
  2233. slerpQuaternions( qa, qb, t ) {
  2234. return this.copy( qa ).slerp( qb, t );
  2235. }
  2236. random() {
  2237. // Derived from http://planning.cs.uiuc.edu/node198.html
  2238. // Note, this source uses w, x, y, z ordering,
  2239. // so we swap the order below.
  2240. const u1 = Math.random();
  2241. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2242. const sqrtu1 = Math.sqrt( u1 );
  2243. const u2 = 2 * Math.PI * Math.random();
  2244. const u3 = 2 * Math.PI * Math.random();
  2245. return this.set(
  2246. sqrt1u1 * Math.cos( u2 ),
  2247. sqrtu1 * Math.sin( u3 ),
  2248. sqrtu1 * Math.cos( u3 ),
  2249. sqrt1u1 * Math.sin( u2 ),
  2250. );
  2251. }
  2252. equals( quaternion ) {
  2253. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2254. }
  2255. fromArray( array, offset = 0 ) {
  2256. this._x = array[ offset ];
  2257. this._y = array[ offset + 1 ];
  2258. this._z = array[ offset + 2 ];
  2259. this._w = array[ offset + 3 ];
  2260. this._onChangeCallback();
  2261. return this;
  2262. }
  2263. toArray( array = [], offset = 0 ) {
  2264. array[ offset ] = this._x;
  2265. array[ offset + 1 ] = this._y;
  2266. array[ offset + 2 ] = this._z;
  2267. array[ offset + 3 ] = this._w;
  2268. return array;
  2269. }
  2270. fromBufferAttribute( attribute, index ) {
  2271. this._x = attribute.getX( index );
  2272. this._y = attribute.getY( index );
  2273. this._z = attribute.getZ( index );
  2274. this._w = attribute.getW( index );
  2275. return this;
  2276. }
  2277. toJSON() {
  2278. return this.toArray();
  2279. }
  2280. _onChange( callback ) {
  2281. this._onChangeCallback = callback;
  2282. return this;
  2283. }
  2284. _onChangeCallback() {}
  2285. *[ Symbol.iterator ]() {
  2286. yield this._x;
  2287. yield this._y;
  2288. yield this._z;
  2289. yield this._w;
  2290. }
  2291. }
  2292. class Vector3 {
  2293. constructor( x = 0, y = 0, z = 0 ) {
  2294. Vector3.prototype.isVector3 = true;
  2295. this.x = x;
  2296. this.y = y;
  2297. this.z = z;
  2298. }
  2299. set( x, y, z ) {
  2300. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2301. this.x = x;
  2302. this.y = y;
  2303. this.z = z;
  2304. return this;
  2305. }
  2306. setScalar( scalar ) {
  2307. this.x = scalar;
  2308. this.y = scalar;
  2309. this.z = scalar;
  2310. return this;
  2311. }
  2312. setX( x ) {
  2313. this.x = x;
  2314. return this;
  2315. }
  2316. setY( y ) {
  2317. this.y = y;
  2318. return this;
  2319. }
  2320. setZ( z ) {
  2321. this.z = z;
  2322. return this;
  2323. }
  2324. setComponent( index, value ) {
  2325. switch ( index ) {
  2326. case 0: this.x = value; break;
  2327. case 1: this.y = value; break;
  2328. case 2: this.z = value; break;
  2329. default: throw new Error( 'index is out of range: ' + index );
  2330. }
  2331. return this;
  2332. }
  2333. getComponent( index ) {
  2334. switch ( index ) {
  2335. case 0: return this.x;
  2336. case 1: return this.y;
  2337. case 2: return this.z;
  2338. default: throw new Error( 'index is out of range: ' + index );
  2339. }
  2340. }
  2341. clone() {
  2342. return new this.constructor( this.x, this.y, this.z );
  2343. }
  2344. copy( v ) {
  2345. this.x = v.x;
  2346. this.y = v.y;
  2347. this.z = v.z;
  2348. return this;
  2349. }
  2350. add( v ) {
  2351. this.x += v.x;
  2352. this.y += v.y;
  2353. this.z += v.z;
  2354. return this;
  2355. }
  2356. addScalar( s ) {
  2357. this.x += s;
  2358. this.y += s;
  2359. this.z += s;
  2360. return this;
  2361. }
  2362. addVectors( a, b ) {
  2363. this.x = a.x + b.x;
  2364. this.y = a.y + b.y;
  2365. this.z = a.z + b.z;
  2366. return this;
  2367. }
  2368. addScaledVector( v, s ) {
  2369. this.x += v.x * s;
  2370. this.y += v.y * s;
  2371. this.z += v.z * s;
  2372. return this;
  2373. }
  2374. sub( v ) {
  2375. this.x -= v.x;
  2376. this.y -= v.y;
  2377. this.z -= v.z;
  2378. return this;
  2379. }
  2380. subScalar( s ) {
  2381. this.x -= s;
  2382. this.y -= s;
  2383. this.z -= s;
  2384. return this;
  2385. }
  2386. subVectors( a, b ) {
  2387. this.x = a.x - b.x;
  2388. this.y = a.y - b.y;
  2389. this.z = a.z - b.z;
  2390. return this;
  2391. }
  2392. multiply( v ) {
  2393. this.x *= v.x;
  2394. this.y *= v.y;
  2395. this.z *= v.z;
  2396. return this;
  2397. }
  2398. multiplyScalar( scalar ) {
  2399. this.x *= scalar;
  2400. this.y *= scalar;
  2401. this.z *= scalar;
  2402. return this;
  2403. }
  2404. multiplyVectors( a, b ) {
  2405. this.x = a.x * b.x;
  2406. this.y = a.y * b.y;
  2407. this.z = a.z * b.z;
  2408. return this;
  2409. }
  2410. applyEuler( euler ) {
  2411. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2412. }
  2413. applyAxisAngle( axis, angle ) {
  2414. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2415. }
  2416. applyMatrix3( m ) {
  2417. const x = this.x, y = this.y, z = this.z;
  2418. const e = m.elements;
  2419. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2420. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2421. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2422. return this;
  2423. }
  2424. applyNormalMatrix( m ) {
  2425. return this.applyMatrix3( m ).normalize();
  2426. }
  2427. applyMatrix4( m ) {
  2428. const x = this.x, y = this.y, z = this.z;
  2429. const e = m.elements;
  2430. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2431. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2432. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2433. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2434. return this;
  2435. }
  2436. applyQuaternion( q ) {
  2437. const x = this.x, y = this.y, z = this.z;
  2438. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2439. // calculate quat * vector
  2440. const ix = qw * x + qy * z - qz * y;
  2441. const iy = qw * y + qz * x - qx * z;
  2442. const iz = qw * z + qx * y - qy * x;
  2443. const iw = - qx * x - qy * y - qz * z;
  2444. // calculate result * inverse quat
  2445. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2446. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2447. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2448. return this;
  2449. }
  2450. project( camera ) {
  2451. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2452. }
  2453. unproject( camera ) {
  2454. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2455. }
  2456. transformDirection( m ) {
  2457. // input: THREE.Matrix4 affine matrix
  2458. // vector interpreted as a direction
  2459. const x = this.x, y = this.y, z = this.z;
  2460. const e = m.elements;
  2461. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2462. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2463. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2464. return this.normalize();
  2465. }
  2466. divide( v ) {
  2467. this.x /= v.x;
  2468. this.y /= v.y;
  2469. this.z /= v.z;
  2470. return this;
  2471. }
  2472. divideScalar( scalar ) {
  2473. return this.multiplyScalar( 1 / scalar );
  2474. }
  2475. min( v ) {
  2476. this.x = Math.min( this.x, v.x );
  2477. this.y = Math.min( this.y, v.y );
  2478. this.z = Math.min( this.z, v.z );
  2479. return this;
  2480. }
  2481. max( v ) {
  2482. this.x = Math.max( this.x, v.x );
  2483. this.y = Math.max( this.y, v.y );
  2484. this.z = Math.max( this.z, v.z );
  2485. return this;
  2486. }
  2487. clamp( min, max ) {
  2488. // assumes min < max, componentwise
  2489. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2490. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2491. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2492. return this;
  2493. }
  2494. clampScalar( minVal, maxVal ) {
  2495. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2496. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2497. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2498. return this;
  2499. }
  2500. clampLength( min, max ) {
  2501. const length = this.length();
  2502. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2503. }
  2504. floor() {
  2505. this.x = Math.floor( this.x );
  2506. this.y = Math.floor( this.y );
  2507. this.z = Math.floor( this.z );
  2508. return this;
  2509. }
  2510. ceil() {
  2511. this.x = Math.ceil( this.x );
  2512. this.y = Math.ceil( this.y );
  2513. this.z = Math.ceil( this.z );
  2514. return this;
  2515. }
  2516. round() {
  2517. this.x = Math.round( this.x );
  2518. this.y = Math.round( this.y );
  2519. this.z = Math.round( this.z );
  2520. return this;
  2521. }
  2522. roundToZero() {
  2523. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2524. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2525. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2526. return this;
  2527. }
  2528. negate() {
  2529. this.x = - this.x;
  2530. this.y = - this.y;
  2531. this.z = - this.z;
  2532. return this;
  2533. }
  2534. dot( v ) {
  2535. return this.x * v.x + this.y * v.y + this.z * v.z;
  2536. }
  2537. // TODO lengthSquared?
  2538. lengthSq() {
  2539. return this.x * this.x + this.y * this.y + this.z * this.z;
  2540. }
  2541. length() {
  2542. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2543. }
  2544. manhattanLength() {
  2545. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2546. }
  2547. normalize() {
  2548. return this.divideScalar( this.length() || 1 );
  2549. }
  2550. setLength( length ) {
  2551. return this.normalize().multiplyScalar( length );
  2552. }
  2553. lerp( v, alpha ) {
  2554. this.x += ( v.x - this.x ) * alpha;
  2555. this.y += ( v.y - this.y ) * alpha;
  2556. this.z += ( v.z - this.z ) * alpha;
  2557. return this;
  2558. }
  2559. lerpVectors( v1, v2, alpha ) {
  2560. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2561. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2562. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2563. return this;
  2564. }
  2565. cross( v ) {
  2566. return this.crossVectors( this, v );
  2567. }
  2568. crossVectors( a, b ) {
  2569. const ax = a.x, ay = a.y, az = a.z;
  2570. const bx = b.x, by = b.y, bz = b.z;
  2571. this.x = ay * bz - az * by;
  2572. this.y = az * bx - ax * bz;
  2573. this.z = ax * by - ay * bx;
  2574. return this;
  2575. }
  2576. projectOnVector( v ) {
  2577. const denominator = v.lengthSq();
  2578. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2579. const scalar = v.dot( this ) / denominator;
  2580. return this.copy( v ).multiplyScalar( scalar );
  2581. }
  2582. projectOnPlane( planeNormal ) {
  2583. _vector$b.copy( this ).projectOnVector( planeNormal );
  2584. return this.sub( _vector$b );
  2585. }
  2586. reflect( normal ) {
  2587. // reflect incident vector off plane orthogonal to normal
  2588. // normal is assumed to have unit length
  2589. return this.sub( _vector$b.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2590. }
  2591. angleTo( v ) {
  2592. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2593. if ( denominator === 0 ) return Math.PI / 2;
  2594. const theta = this.dot( v ) / denominator;
  2595. // clamp, to handle numerical problems
  2596. return Math.acos( clamp( theta, - 1, 1 ) );
  2597. }
  2598. distanceTo( v ) {
  2599. return Math.sqrt( this.distanceToSquared( v ) );
  2600. }
  2601. distanceToSquared( v ) {
  2602. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2603. return dx * dx + dy * dy + dz * dz;
  2604. }
  2605. manhattanDistanceTo( v ) {
  2606. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2607. }
  2608. setFromSpherical( s ) {
  2609. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2610. }
  2611. setFromSphericalCoords( radius, phi, theta ) {
  2612. const sinPhiRadius = Math.sin( phi ) * radius;
  2613. this.x = sinPhiRadius * Math.sin( theta );
  2614. this.y = Math.cos( phi ) * radius;
  2615. this.z = sinPhiRadius * Math.cos( theta );
  2616. return this;
  2617. }
  2618. setFromCylindrical( c ) {
  2619. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2620. }
  2621. setFromCylindricalCoords( radius, theta, y ) {
  2622. this.x = radius * Math.sin( theta );
  2623. this.y = y;
  2624. this.z = radius * Math.cos( theta );
  2625. return this;
  2626. }
  2627. setFromMatrixPosition( m ) {
  2628. const e = m.elements;
  2629. this.x = e[ 12 ];
  2630. this.y = e[ 13 ];
  2631. this.z = e[ 14 ];
  2632. return this;
  2633. }
  2634. setFromMatrixScale( m ) {
  2635. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2636. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2637. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2638. this.x = sx;
  2639. this.y = sy;
  2640. this.z = sz;
  2641. return this;
  2642. }
  2643. setFromMatrixColumn( m, index ) {
  2644. return this.fromArray( m.elements, index * 4 );
  2645. }
  2646. setFromMatrix3Column( m, index ) {
  2647. return this.fromArray( m.elements, index * 3 );
  2648. }
  2649. setFromEuler( e ) {
  2650. this.x = e._x;
  2651. this.y = e._y;
  2652. this.z = e._z;
  2653. return this;
  2654. }
  2655. setFromColor( c ) {
  2656. this.x = c.r;
  2657. this.y = c.g;
  2658. this.z = c.b;
  2659. return this;
  2660. }
  2661. equals( v ) {
  2662. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2663. }
  2664. fromArray( array, offset = 0 ) {
  2665. this.x = array[ offset ];
  2666. this.y = array[ offset + 1 ];
  2667. this.z = array[ offset + 2 ];
  2668. return this;
  2669. }
  2670. toArray( array = [], offset = 0 ) {
  2671. array[ offset ] = this.x;
  2672. array[ offset + 1 ] = this.y;
  2673. array[ offset + 2 ] = this.z;
  2674. return array;
  2675. }
  2676. fromBufferAttribute( attribute, index ) {
  2677. this.x = attribute.getX( index );
  2678. this.y = attribute.getY( index );
  2679. this.z = attribute.getZ( index );
  2680. return this;
  2681. }
  2682. random() {
  2683. this.x = Math.random();
  2684. this.y = Math.random();
  2685. this.z = Math.random();
  2686. return this;
  2687. }
  2688. randomDirection() {
  2689. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2690. const u = ( Math.random() - 0.5 ) * 2;
  2691. const t = Math.random() * Math.PI * 2;
  2692. const f = Math.sqrt( 1 - u ** 2 );
  2693. this.x = f * Math.cos( t );
  2694. this.y = f * Math.sin( t );
  2695. this.z = u;
  2696. return this;
  2697. }
  2698. *[ Symbol.iterator ]() {
  2699. yield this.x;
  2700. yield this.y;
  2701. yield this.z;
  2702. }
  2703. }
  2704. const _vector$b = /*@__PURE__*/ new Vector3();
  2705. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2706. class Box3 {
  2707. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2708. this.isBox3 = true;
  2709. this.min = min;
  2710. this.max = max;
  2711. }
  2712. set( min, max ) {
  2713. this.min.copy( min );
  2714. this.max.copy( max );
  2715. return this;
  2716. }
  2717. setFromArray( array ) {
  2718. this.makeEmpty();
  2719. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2720. this.expandByPoint( _vector$a.fromArray( array, i ) );
  2721. }
  2722. return this;
  2723. }
  2724. setFromBufferAttribute( attribute ) {
  2725. this.makeEmpty();
  2726. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2727. this.expandByPoint( _vector$a.fromBufferAttribute( attribute, i ) );
  2728. }
  2729. return this;
  2730. }
  2731. setFromPoints( points ) {
  2732. this.makeEmpty();
  2733. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2734. this.expandByPoint( points[ i ] );
  2735. }
  2736. return this;
  2737. }
  2738. setFromCenterAndSize( center, size ) {
  2739. const halfSize = _vector$a.copy( size ).multiplyScalar( 0.5 );
  2740. this.min.copy( center ).sub( halfSize );
  2741. this.max.copy( center ).add( halfSize );
  2742. return this;
  2743. }
  2744. setFromObject( object, precise = false ) {
  2745. this.makeEmpty();
  2746. return this.expandByObject( object, precise );
  2747. }
  2748. clone() {
  2749. return new this.constructor().copy( this );
  2750. }
  2751. copy( box ) {
  2752. this.min.copy( box.min );
  2753. this.max.copy( box.max );
  2754. return this;
  2755. }
  2756. makeEmpty() {
  2757. this.min.x = this.min.y = this.min.z = + Infinity;
  2758. this.max.x = this.max.y = this.max.z = - Infinity;
  2759. return this;
  2760. }
  2761. isEmpty() {
  2762. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2763. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2764. }
  2765. getCenter( target ) {
  2766. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2767. }
  2768. getSize( target ) {
  2769. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2770. }
  2771. expandByPoint( point ) {
  2772. this.min.min( point );
  2773. this.max.max( point );
  2774. return this;
  2775. }
  2776. expandByVector( vector ) {
  2777. this.min.sub( vector );
  2778. this.max.add( vector );
  2779. return this;
  2780. }
  2781. expandByScalar( scalar ) {
  2782. this.min.addScalar( - scalar );
  2783. this.max.addScalar( scalar );
  2784. return this;
  2785. }
  2786. expandByObject( object, precise = false ) {
  2787. // Computes the world-axis-aligned bounding box of an object (including its children),
  2788. // accounting for both the object's, and children's, world transforms
  2789. object.updateWorldMatrix( false, false );
  2790. if ( object.boundingBox !== undefined ) {
  2791. if ( object.boundingBox === null ) {
  2792. object.computeBoundingBox();
  2793. }
  2794. _box$3.copy( object.boundingBox );
  2795. _box$3.applyMatrix4( object.matrixWorld );
  2796. this.union( _box$3 );
  2797. } else {
  2798. const geometry = object.geometry;
  2799. if ( geometry !== undefined ) {
  2800. if ( precise && geometry.attributes !== undefined && geometry.attributes.position !== undefined ) {
  2801. const position = geometry.attributes.position;
  2802. for ( let i = 0, l = position.count; i < l; i ++ ) {
  2803. _vector$a.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  2804. this.expandByPoint( _vector$a );
  2805. }
  2806. } else {
  2807. if ( geometry.boundingBox === null ) {
  2808. geometry.computeBoundingBox();
  2809. }
  2810. _box$3.copy( geometry.boundingBox );
  2811. _box$3.applyMatrix4( object.matrixWorld );
  2812. this.union( _box$3 );
  2813. }
  2814. }
  2815. }
  2816. const children = object.children;
  2817. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2818. this.expandByObject( children[ i ], precise );
  2819. }
  2820. return this;
  2821. }
  2822. containsPoint( point ) {
  2823. return point.x < this.min.x || point.x > this.max.x ||
  2824. point.y < this.min.y || point.y > this.max.y ||
  2825. point.z < this.min.z || point.z > this.max.z ? false : true;
  2826. }
  2827. containsBox( box ) {
  2828. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2829. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2830. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2831. }
  2832. getParameter( point, target ) {
  2833. // This can potentially have a divide by zero if the box
  2834. // has a size dimension of 0.
  2835. return target.set(
  2836. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2837. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2838. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2839. );
  2840. }
  2841. intersectsBox( box ) {
  2842. // using 6 splitting planes to rule out intersections.
  2843. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2844. box.max.y < this.min.y || box.min.y > this.max.y ||
  2845. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2846. }
  2847. intersectsSphere( sphere ) {
  2848. // Find the point on the AABB closest to the sphere center.
  2849. this.clampPoint( sphere.center, _vector$a );
  2850. // If that point is inside the sphere, the AABB and sphere intersect.
  2851. return _vector$a.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2852. }
  2853. intersectsPlane( plane ) {
  2854. // We compute the minimum and maximum dot product values. If those values
  2855. // are on the same side (back or front) of the plane, then there is no intersection.
  2856. let min, max;
  2857. if ( plane.normal.x > 0 ) {
  2858. min = plane.normal.x * this.min.x;
  2859. max = plane.normal.x * this.max.x;
  2860. } else {
  2861. min = plane.normal.x * this.max.x;
  2862. max = plane.normal.x * this.min.x;
  2863. }
  2864. if ( plane.normal.y > 0 ) {
  2865. min += plane.normal.y * this.min.y;
  2866. max += plane.normal.y * this.max.y;
  2867. } else {
  2868. min += plane.normal.y * this.max.y;
  2869. max += plane.normal.y * this.min.y;
  2870. }
  2871. if ( plane.normal.z > 0 ) {
  2872. min += plane.normal.z * this.min.z;
  2873. max += plane.normal.z * this.max.z;
  2874. } else {
  2875. min += plane.normal.z * this.max.z;
  2876. max += plane.normal.z * this.min.z;
  2877. }
  2878. return ( min <= - plane.constant && max >= - plane.constant );
  2879. }
  2880. intersectsTriangle( triangle ) {
  2881. if ( this.isEmpty() ) {
  2882. return false;
  2883. }
  2884. // compute box center and extents
  2885. this.getCenter( _center );
  2886. _extents.subVectors( this.max, _center );
  2887. // translate triangle to aabb origin
  2888. _v0$2.subVectors( triangle.a, _center );
  2889. _v1$7.subVectors( triangle.b, _center );
  2890. _v2$4.subVectors( triangle.c, _center );
  2891. // compute edge vectors for triangle
  2892. _f0.subVectors( _v1$7, _v0$2 );
  2893. _f1.subVectors( _v2$4, _v1$7 );
  2894. _f2.subVectors( _v0$2, _v2$4 );
  2895. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2896. // 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
  2897. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2898. let axes = [
  2899. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2900. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2901. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2902. ];
  2903. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2904. return false;
  2905. }
  2906. // test 3 face normals from the aabb
  2907. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2908. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2909. return false;
  2910. }
  2911. // finally testing the face normal of the triangle
  2912. // use already existing triangle edge vectors here
  2913. _triangleNormal.crossVectors( _f0, _f1 );
  2914. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2915. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2916. }
  2917. clampPoint( point, target ) {
  2918. return target.copy( point ).clamp( this.min, this.max );
  2919. }
  2920. distanceToPoint( point ) {
  2921. return this.clampPoint( point, _vector$a ).distanceTo( point );
  2922. }
  2923. getBoundingSphere( target ) {
  2924. if ( this.isEmpty() ) {
  2925. target.makeEmpty();
  2926. } else {
  2927. this.getCenter( target.center );
  2928. target.radius = this.getSize( _vector$a ).length() * 0.5;
  2929. }
  2930. return target;
  2931. }
  2932. intersect( box ) {
  2933. this.min.max( box.min );
  2934. this.max.min( box.max );
  2935. // 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.
  2936. if ( this.isEmpty() ) this.makeEmpty();
  2937. return this;
  2938. }
  2939. union( box ) {
  2940. this.min.min( box.min );
  2941. this.max.max( box.max );
  2942. return this;
  2943. }
  2944. applyMatrix4( matrix ) {
  2945. // transform of empty box is an empty box.
  2946. if ( this.isEmpty() ) return this;
  2947. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2948. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2949. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2950. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2951. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2952. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2953. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2954. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2955. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2956. this.setFromPoints( _points );
  2957. return this;
  2958. }
  2959. translate( offset ) {
  2960. this.min.add( offset );
  2961. this.max.add( offset );
  2962. return this;
  2963. }
  2964. equals( box ) {
  2965. return box.min.equals( this.min ) && box.max.equals( this.max );
  2966. }
  2967. }
  2968. const _points = [
  2969. /*@__PURE__*/ new Vector3(),
  2970. /*@__PURE__*/ new Vector3(),
  2971. /*@__PURE__*/ new Vector3(),
  2972. /*@__PURE__*/ new Vector3(),
  2973. /*@__PURE__*/ new Vector3(),
  2974. /*@__PURE__*/ new Vector3(),
  2975. /*@__PURE__*/ new Vector3(),
  2976. /*@__PURE__*/ new Vector3()
  2977. ];
  2978. const _vector$a = /*@__PURE__*/ new Vector3();
  2979. const _box$3 = /*@__PURE__*/ new Box3();
  2980. // triangle centered vertices
  2981. const _v0$2 = /*@__PURE__*/ new Vector3();
  2982. const _v1$7 = /*@__PURE__*/ new Vector3();
  2983. const _v2$4 = /*@__PURE__*/ new Vector3();
  2984. // triangle edge vectors
  2985. const _f0 = /*@__PURE__*/ new Vector3();
  2986. const _f1 = /*@__PURE__*/ new Vector3();
  2987. const _f2 = /*@__PURE__*/ new Vector3();
  2988. const _center = /*@__PURE__*/ new Vector3();
  2989. const _extents = /*@__PURE__*/ new Vector3();
  2990. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2991. const _testAxis = /*@__PURE__*/ new Vector3();
  2992. function satForAxes( axes, v0, v1, v2, extents ) {
  2993. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2994. _testAxis.fromArray( axes, i );
  2995. // project the aabb onto the separating axis
  2996. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2997. // project all 3 vertices of the triangle onto the separating axis
  2998. const p0 = v0.dot( _testAxis );
  2999. const p1 = v1.dot( _testAxis );
  3000. const p2 = v2.dot( _testAxis );
  3001. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3002. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3003. // points of the projected triangle are outside the projected half-length of the aabb
  3004. // the axis is separating and we can exit
  3005. return false;
  3006. }
  3007. }
  3008. return true;
  3009. }
  3010. const _box$2 = /*@__PURE__*/ new Box3();
  3011. const _v1$6 = /*@__PURE__*/ new Vector3();
  3012. const _v2$3 = /*@__PURE__*/ new Vector3();
  3013. class Sphere {
  3014. constructor( center = new Vector3(), radius = - 1 ) {
  3015. this.center = center;
  3016. this.radius = radius;
  3017. }
  3018. set( center, radius ) {
  3019. this.center.copy( center );
  3020. this.radius = radius;
  3021. return this;
  3022. }
  3023. setFromPoints( points, optionalCenter ) {
  3024. const center = this.center;
  3025. if ( optionalCenter !== undefined ) {
  3026. center.copy( optionalCenter );
  3027. } else {
  3028. _box$2.setFromPoints( points ).getCenter( center );
  3029. }
  3030. let maxRadiusSq = 0;
  3031. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3032. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3033. }
  3034. this.radius = Math.sqrt( maxRadiusSq );
  3035. return this;
  3036. }
  3037. copy( sphere ) {
  3038. this.center.copy( sphere.center );
  3039. this.radius = sphere.radius;
  3040. return this;
  3041. }
  3042. isEmpty() {
  3043. return ( this.radius < 0 );
  3044. }
  3045. makeEmpty() {
  3046. this.center.set( 0, 0, 0 );
  3047. this.radius = - 1;
  3048. return this;
  3049. }
  3050. containsPoint( point ) {
  3051. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3052. }
  3053. distanceToPoint( point ) {
  3054. return ( point.distanceTo( this.center ) - this.radius );
  3055. }
  3056. intersectsSphere( sphere ) {
  3057. const radiusSum = this.radius + sphere.radius;
  3058. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3059. }
  3060. intersectsBox( box ) {
  3061. return box.intersectsSphere( this );
  3062. }
  3063. intersectsPlane( plane ) {
  3064. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3065. }
  3066. clampPoint( point, target ) {
  3067. const deltaLengthSq = this.center.distanceToSquared( point );
  3068. target.copy( point );
  3069. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3070. target.sub( this.center ).normalize();
  3071. target.multiplyScalar( this.radius ).add( this.center );
  3072. }
  3073. return target;
  3074. }
  3075. getBoundingBox( target ) {
  3076. if ( this.isEmpty() ) {
  3077. // Empty sphere produces empty bounding box
  3078. target.makeEmpty();
  3079. return target;
  3080. }
  3081. target.set( this.center, this.center );
  3082. target.expandByScalar( this.radius );
  3083. return target;
  3084. }
  3085. applyMatrix4( matrix ) {
  3086. this.center.applyMatrix4( matrix );
  3087. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3088. return this;
  3089. }
  3090. translate( offset ) {
  3091. this.center.add( offset );
  3092. return this;
  3093. }
  3094. expandByPoint( point ) {
  3095. if ( this.isEmpty() ) {
  3096. this.center.copy( point );
  3097. this.radius = 0;
  3098. return this;
  3099. }
  3100. _v1$6.subVectors( point, this.center );
  3101. const lengthSq = _v1$6.lengthSq();
  3102. if ( lengthSq > ( this.radius * this.radius ) ) {
  3103. // calculate the minimal sphere
  3104. const length = Math.sqrt( lengthSq );
  3105. const delta = ( length - this.radius ) * 0.5;
  3106. this.center.addScaledVector( _v1$6, delta / length );
  3107. this.radius += delta;
  3108. }
  3109. return this;
  3110. }
  3111. union( sphere ) {
  3112. if ( sphere.isEmpty() ) {
  3113. return this;
  3114. }
  3115. if ( this.isEmpty() ) {
  3116. this.copy( sphere );
  3117. return this;
  3118. }
  3119. if ( this.center.equals( sphere.center ) === true ) {
  3120. this.radius = Math.max( this.radius, sphere.radius );
  3121. } else {
  3122. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3123. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3124. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3125. }
  3126. return this;
  3127. }
  3128. equals( sphere ) {
  3129. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3130. }
  3131. clone() {
  3132. return new this.constructor().copy( this );
  3133. }
  3134. }
  3135. const _vector$9 = /*@__PURE__*/ new Vector3();
  3136. const _segCenter = /*@__PURE__*/ new Vector3();
  3137. const _segDir = /*@__PURE__*/ new Vector3();
  3138. const _diff = /*@__PURE__*/ new Vector3();
  3139. const _edge1 = /*@__PURE__*/ new Vector3();
  3140. const _edge2 = /*@__PURE__*/ new Vector3();
  3141. const _normal$1 = /*@__PURE__*/ new Vector3();
  3142. class Ray {
  3143. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3144. this.origin = origin;
  3145. this.direction = direction;
  3146. }
  3147. set( origin, direction ) {
  3148. this.origin.copy( origin );
  3149. this.direction.copy( direction );
  3150. return this;
  3151. }
  3152. copy( ray ) {
  3153. this.origin.copy( ray.origin );
  3154. this.direction.copy( ray.direction );
  3155. return this;
  3156. }
  3157. at( t, target ) {
  3158. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3159. }
  3160. lookAt( v ) {
  3161. this.direction.copy( v ).sub( this.origin ).normalize();
  3162. return this;
  3163. }
  3164. recast( t ) {
  3165. this.origin.copy( this.at( t, _vector$9 ) );
  3166. return this;
  3167. }
  3168. closestPointToPoint( point, target ) {
  3169. target.subVectors( point, this.origin );
  3170. const directionDistance = target.dot( this.direction );
  3171. if ( directionDistance < 0 ) {
  3172. return target.copy( this.origin );
  3173. }
  3174. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3175. }
  3176. distanceToPoint( point ) {
  3177. return Math.sqrt( this.distanceSqToPoint( point ) );
  3178. }
  3179. distanceSqToPoint( point ) {
  3180. const directionDistance = _vector$9.subVectors( point, this.origin ).dot( this.direction );
  3181. // point behind the ray
  3182. if ( directionDistance < 0 ) {
  3183. return this.origin.distanceToSquared( point );
  3184. }
  3185. _vector$9.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3186. return _vector$9.distanceToSquared( point );
  3187. }
  3188. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3189. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3190. // It returns the min distance between the ray and the segment
  3191. // defined by v0 and v1
  3192. // It can also set two optional targets :
  3193. // - The closest point on the ray
  3194. // - The closest point on the segment
  3195. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3196. _segDir.copy( v1 ).sub( v0 ).normalize();
  3197. _diff.copy( this.origin ).sub( _segCenter );
  3198. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3199. const a01 = - this.direction.dot( _segDir );
  3200. const b0 = _diff.dot( this.direction );
  3201. const b1 = - _diff.dot( _segDir );
  3202. const c = _diff.lengthSq();
  3203. const det = Math.abs( 1 - a01 * a01 );
  3204. let s0, s1, sqrDist, extDet;
  3205. if ( det > 0 ) {
  3206. // The ray and segment are not parallel.
  3207. s0 = a01 * b1 - b0;
  3208. s1 = a01 * b0 - b1;
  3209. extDet = segExtent * det;
  3210. if ( s0 >= 0 ) {
  3211. if ( s1 >= - extDet ) {
  3212. if ( s1 <= extDet ) {
  3213. // region 0
  3214. // Minimum at interior points of ray and segment.
  3215. const invDet = 1 / det;
  3216. s0 *= invDet;
  3217. s1 *= invDet;
  3218. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3219. } else {
  3220. // region 1
  3221. s1 = segExtent;
  3222. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3223. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3224. }
  3225. } else {
  3226. // region 5
  3227. s1 = - segExtent;
  3228. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3229. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3230. }
  3231. } else {
  3232. if ( s1 <= - extDet ) {
  3233. // region 4
  3234. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3235. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3236. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3237. } else if ( s1 <= extDet ) {
  3238. // region 3
  3239. s0 = 0;
  3240. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3241. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3242. } else {
  3243. // region 2
  3244. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3245. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3246. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3247. }
  3248. }
  3249. } else {
  3250. // Ray and segment are parallel.
  3251. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3252. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3253. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3254. }
  3255. if ( optionalPointOnRay ) {
  3256. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3257. }
  3258. if ( optionalPointOnSegment ) {
  3259. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3260. }
  3261. return sqrDist;
  3262. }
  3263. intersectSphere( sphere, target ) {
  3264. _vector$9.subVectors( sphere.center, this.origin );
  3265. const tca = _vector$9.dot( this.direction );
  3266. const d2 = _vector$9.dot( _vector$9 ) - tca * tca;
  3267. const radius2 = sphere.radius * sphere.radius;
  3268. if ( d2 > radius2 ) return null;
  3269. const thc = Math.sqrt( radius2 - d2 );
  3270. // t0 = first intersect point - entrance on front of sphere
  3271. const t0 = tca - thc;
  3272. // t1 = second intersect point - exit point on back of sphere
  3273. const t1 = tca + thc;
  3274. // test to see if t1 is behind the ray - if so, return null
  3275. if ( t1 < 0 ) return null;
  3276. // test to see if t0 is behind the ray:
  3277. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3278. // in order to always return an intersect point that is in front of the ray.
  3279. if ( t0 < 0 ) return this.at( t1, target );
  3280. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3281. return this.at( t0, target );
  3282. }
  3283. intersectsSphere( sphere ) {
  3284. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3285. }
  3286. distanceToPlane( plane ) {
  3287. const denominator = plane.normal.dot( this.direction );
  3288. if ( denominator === 0 ) {
  3289. // line is coplanar, return origin
  3290. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3291. return 0;
  3292. }
  3293. // Null is preferable to undefined since undefined means.... it is undefined
  3294. return null;
  3295. }
  3296. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3297. // Return if the ray never intersects the plane
  3298. return t >= 0 ? t : null;
  3299. }
  3300. intersectPlane( plane, target ) {
  3301. const t = this.distanceToPlane( plane );
  3302. if ( t === null ) {
  3303. return null;
  3304. }
  3305. return this.at( t, target );
  3306. }
  3307. intersectsPlane( plane ) {
  3308. // check if the ray lies on the plane first
  3309. const distToPoint = plane.distanceToPoint( this.origin );
  3310. if ( distToPoint === 0 ) {
  3311. return true;
  3312. }
  3313. const denominator = plane.normal.dot( this.direction );
  3314. if ( denominator * distToPoint < 0 ) {
  3315. return true;
  3316. }
  3317. // ray origin is behind the plane (and is pointing behind it)
  3318. return false;
  3319. }
  3320. intersectBox( box, target ) {
  3321. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3322. const invdirx = 1 / this.direction.x,
  3323. invdiry = 1 / this.direction.y,
  3324. invdirz = 1 / this.direction.z;
  3325. const origin = this.origin;
  3326. if ( invdirx >= 0 ) {
  3327. tmin = ( box.min.x - origin.x ) * invdirx;
  3328. tmax = ( box.max.x - origin.x ) * invdirx;
  3329. } else {
  3330. tmin = ( box.max.x - origin.x ) * invdirx;
  3331. tmax = ( box.min.x - origin.x ) * invdirx;
  3332. }
  3333. if ( invdiry >= 0 ) {
  3334. tymin = ( box.min.y - origin.y ) * invdiry;
  3335. tymax = ( box.max.y - origin.y ) * invdiry;
  3336. } else {
  3337. tymin = ( box.max.y - origin.y ) * invdiry;
  3338. tymax = ( box.min.y - origin.y ) * invdiry;
  3339. }
  3340. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3341. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3342. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3343. if ( invdirz >= 0 ) {
  3344. tzmin = ( box.min.z - origin.z ) * invdirz;
  3345. tzmax = ( box.max.z - origin.z ) * invdirz;
  3346. } else {
  3347. tzmin = ( box.max.z - origin.z ) * invdirz;
  3348. tzmax = ( box.min.z - origin.z ) * invdirz;
  3349. }
  3350. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3351. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3352. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3353. //return point closest to the ray (positive side)
  3354. if ( tmax < 0 ) return null;
  3355. return this.at( tmin >= 0 ? tmin : tmax, target );
  3356. }
  3357. intersectsBox( box ) {
  3358. return this.intersectBox( box, _vector$9 ) !== null;
  3359. }
  3360. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3361. // Compute the offset origin, edges, and normal.
  3362. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3363. _edge1.subVectors( b, a );
  3364. _edge2.subVectors( c, a );
  3365. _normal$1.crossVectors( _edge1, _edge2 );
  3366. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3367. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3368. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3369. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3370. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3371. let DdN = this.direction.dot( _normal$1 );
  3372. let sign;
  3373. if ( DdN > 0 ) {
  3374. if ( backfaceCulling ) return null;
  3375. sign = 1;
  3376. } else if ( DdN < 0 ) {
  3377. sign = - 1;
  3378. DdN = - DdN;
  3379. } else {
  3380. return null;
  3381. }
  3382. _diff.subVectors( this.origin, a );
  3383. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3384. // b1 < 0, no intersection
  3385. if ( DdQxE2 < 0 ) {
  3386. return null;
  3387. }
  3388. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3389. // b2 < 0, no intersection
  3390. if ( DdE1xQ < 0 ) {
  3391. return null;
  3392. }
  3393. // b1+b2 > 1, no intersection
  3394. if ( DdQxE2 + DdE1xQ > DdN ) {
  3395. return null;
  3396. }
  3397. // Line intersects triangle, check if ray does.
  3398. const QdN = - sign * _diff.dot( _normal$1 );
  3399. // t < 0, no intersection
  3400. if ( QdN < 0 ) {
  3401. return null;
  3402. }
  3403. // Ray intersects triangle.
  3404. return this.at( QdN / DdN, target );
  3405. }
  3406. applyMatrix4( matrix4 ) {
  3407. this.origin.applyMatrix4( matrix4 );
  3408. this.direction.transformDirection( matrix4 );
  3409. return this;
  3410. }
  3411. equals( ray ) {
  3412. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3413. }
  3414. clone() {
  3415. return new this.constructor().copy( this );
  3416. }
  3417. }
  3418. class Matrix4 {
  3419. constructor() {
  3420. Matrix4.prototype.isMatrix4 = true;
  3421. this.elements = [
  3422. 1, 0, 0, 0,
  3423. 0, 1, 0, 0,
  3424. 0, 0, 1, 0,
  3425. 0, 0, 0, 1
  3426. ];
  3427. }
  3428. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3429. const te = this.elements;
  3430. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3431. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3432. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3433. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3434. return this;
  3435. }
  3436. identity() {
  3437. this.set(
  3438. 1, 0, 0, 0,
  3439. 0, 1, 0, 0,
  3440. 0, 0, 1, 0,
  3441. 0, 0, 0, 1
  3442. );
  3443. return this;
  3444. }
  3445. clone() {
  3446. return new Matrix4().fromArray( this.elements );
  3447. }
  3448. copy( m ) {
  3449. const te = this.elements;
  3450. const me = m.elements;
  3451. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3452. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3453. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3454. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3455. return this;
  3456. }
  3457. copyPosition( m ) {
  3458. const te = this.elements, me = m.elements;
  3459. te[ 12 ] = me[ 12 ];
  3460. te[ 13 ] = me[ 13 ];
  3461. te[ 14 ] = me[ 14 ];
  3462. return this;
  3463. }
  3464. setFromMatrix3( m ) {
  3465. const me = m.elements;
  3466. this.set(
  3467. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3468. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3469. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3470. 0, 0, 0, 1
  3471. );
  3472. return this;
  3473. }
  3474. extractBasis( xAxis, yAxis, zAxis ) {
  3475. xAxis.setFromMatrixColumn( this, 0 );
  3476. yAxis.setFromMatrixColumn( this, 1 );
  3477. zAxis.setFromMatrixColumn( this, 2 );
  3478. return this;
  3479. }
  3480. makeBasis( xAxis, yAxis, zAxis ) {
  3481. this.set(
  3482. xAxis.x, yAxis.x, zAxis.x, 0,
  3483. xAxis.y, yAxis.y, zAxis.y, 0,
  3484. xAxis.z, yAxis.z, zAxis.z, 0,
  3485. 0, 0, 0, 1
  3486. );
  3487. return this;
  3488. }
  3489. extractRotation( m ) {
  3490. // this method does not support reflection matrices
  3491. const te = this.elements;
  3492. const me = m.elements;
  3493. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3494. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3495. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3496. te[ 0 ] = me[ 0 ] * scaleX;
  3497. te[ 1 ] = me[ 1 ] * scaleX;
  3498. te[ 2 ] = me[ 2 ] * scaleX;
  3499. te[ 3 ] = 0;
  3500. te[ 4 ] = me[ 4 ] * scaleY;
  3501. te[ 5 ] = me[ 5 ] * scaleY;
  3502. te[ 6 ] = me[ 6 ] * scaleY;
  3503. te[ 7 ] = 0;
  3504. te[ 8 ] = me[ 8 ] * scaleZ;
  3505. te[ 9 ] = me[ 9 ] * scaleZ;
  3506. te[ 10 ] = me[ 10 ] * scaleZ;
  3507. te[ 11 ] = 0;
  3508. te[ 12 ] = 0;
  3509. te[ 13 ] = 0;
  3510. te[ 14 ] = 0;
  3511. te[ 15 ] = 1;
  3512. return this;
  3513. }
  3514. makeRotationFromEuler( euler ) {
  3515. const te = this.elements;
  3516. const x = euler.x, y = euler.y, z = euler.z;
  3517. const a = Math.cos( x ), b = Math.sin( x );
  3518. const c = Math.cos( y ), d = Math.sin( y );
  3519. const e = Math.cos( z ), f = Math.sin( z );
  3520. if ( euler.order === 'XYZ' ) {
  3521. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3522. te[ 0 ] = c * e;
  3523. te[ 4 ] = - c * f;
  3524. te[ 8 ] = d;
  3525. te[ 1 ] = af + be * d;
  3526. te[ 5 ] = ae - bf * d;
  3527. te[ 9 ] = - b * c;
  3528. te[ 2 ] = bf - ae * d;
  3529. te[ 6 ] = be + af * d;
  3530. te[ 10 ] = a * c;
  3531. } else if ( euler.order === 'YXZ' ) {
  3532. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3533. te[ 0 ] = ce + df * b;
  3534. te[ 4 ] = de * b - cf;
  3535. te[ 8 ] = a * d;
  3536. te[ 1 ] = a * f;
  3537. te[ 5 ] = a * e;
  3538. te[ 9 ] = - b;
  3539. te[ 2 ] = cf * b - de;
  3540. te[ 6 ] = df + ce * b;
  3541. te[ 10 ] = a * c;
  3542. } else if ( euler.order === 'ZXY' ) {
  3543. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3544. te[ 0 ] = ce - df * b;
  3545. te[ 4 ] = - a * f;
  3546. te[ 8 ] = de + cf * b;
  3547. te[ 1 ] = cf + de * b;
  3548. te[ 5 ] = a * e;
  3549. te[ 9 ] = df - ce * b;
  3550. te[ 2 ] = - a * d;
  3551. te[ 6 ] = b;
  3552. te[ 10 ] = a * c;
  3553. } else if ( euler.order === 'ZYX' ) {
  3554. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3555. te[ 0 ] = c * e;
  3556. te[ 4 ] = be * d - af;
  3557. te[ 8 ] = ae * d + bf;
  3558. te[ 1 ] = c * f;
  3559. te[ 5 ] = bf * d + ae;
  3560. te[ 9 ] = af * d - be;
  3561. te[ 2 ] = - d;
  3562. te[ 6 ] = b * c;
  3563. te[ 10 ] = a * c;
  3564. } else if ( euler.order === 'YZX' ) {
  3565. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3566. te[ 0 ] = c * e;
  3567. te[ 4 ] = bd - ac * f;
  3568. te[ 8 ] = bc * f + ad;
  3569. te[ 1 ] = f;
  3570. te[ 5 ] = a * e;
  3571. te[ 9 ] = - b * e;
  3572. te[ 2 ] = - d * e;
  3573. te[ 6 ] = ad * f + bc;
  3574. te[ 10 ] = ac - bd * f;
  3575. } else if ( euler.order === 'XZY' ) {
  3576. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3577. te[ 0 ] = c * e;
  3578. te[ 4 ] = - f;
  3579. te[ 8 ] = d * e;
  3580. te[ 1 ] = ac * f + bd;
  3581. te[ 5 ] = a * e;
  3582. te[ 9 ] = ad * f - bc;
  3583. te[ 2 ] = bc * f - ad;
  3584. te[ 6 ] = b * e;
  3585. te[ 10 ] = bd * f + ac;
  3586. }
  3587. // bottom row
  3588. te[ 3 ] = 0;
  3589. te[ 7 ] = 0;
  3590. te[ 11 ] = 0;
  3591. // last column
  3592. te[ 12 ] = 0;
  3593. te[ 13 ] = 0;
  3594. te[ 14 ] = 0;
  3595. te[ 15 ] = 1;
  3596. return this;
  3597. }
  3598. makeRotationFromQuaternion( q ) {
  3599. return this.compose( _zero, q, _one );
  3600. }
  3601. lookAt( eye, target, up ) {
  3602. const te = this.elements;
  3603. _z.subVectors( eye, target );
  3604. if ( _z.lengthSq() === 0 ) {
  3605. // eye and target are in the same position
  3606. _z.z = 1;
  3607. }
  3608. _z.normalize();
  3609. _x.crossVectors( up, _z );
  3610. if ( _x.lengthSq() === 0 ) {
  3611. // up and z are parallel
  3612. if ( Math.abs( up.z ) === 1 ) {
  3613. _z.x += 0.0001;
  3614. } else {
  3615. _z.z += 0.0001;
  3616. }
  3617. _z.normalize();
  3618. _x.crossVectors( up, _z );
  3619. }
  3620. _x.normalize();
  3621. _y.crossVectors( _z, _x );
  3622. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3623. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3624. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3625. return this;
  3626. }
  3627. multiply( m ) {
  3628. return this.multiplyMatrices( this, m );
  3629. }
  3630. premultiply( m ) {
  3631. return this.multiplyMatrices( m, this );
  3632. }
  3633. multiplyMatrices( a, b ) {
  3634. const ae = a.elements;
  3635. const be = b.elements;
  3636. const te = this.elements;
  3637. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3638. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3639. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3640. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3641. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3642. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3643. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3644. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3645. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3646. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3647. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3648. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3649. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3650. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3651. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3652. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3653. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3654. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3655. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3656. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3657. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3658. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3659. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3660. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3661. return this;
  3662. }
  3663. multiplyScalar( s ) {
  3664. const te = this.elements;
  3665. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3666. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3667. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3668. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3669. return this;
  3670. }
  3671. determinant() {
  3672. const te = this.elements;
  3673. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3674. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3675. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3676. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3677. //TODO: make this more efficient
  3678. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3679. return (
  3680. n41 * (
  3681. + n14 * n23 * n32
  3682. - n13 * n24 * n32
  3683. - n14 * n22 * n33
  3684. + n12 * n24 * n33
  3685. + n13 * n22 * n34
  3686. - n12 * n23 * n34
  3687. ) +
  3688. n42 * (
  3689. + n11 * n23 * n34
  3690. - n11 * n24 * n33
  3691. + n14 * n21 * n33
  3692. - n13 * n21 * n34
  3693. + n13 * n24 * n31
  3694. - n14 * n23 * n31
  3695. ) +
  3696. n43 * (
  3697. + n11 * n24 * n32
  3698. - n11 * n22 * n34
  3699. - n14 * n21 * n32
  3700. + n12 * n21 * n34
  3701. + n14 * n22 * n31
  3702. - n12 * n24 * n31
  3703. ) +
  3704. n44 * (
  3705. - n13 * n22 * n31
  3706. - n11 * n23 * n32
  3707. + n11 * n22 * n33
  3708. + n13 * n21 * n32
  3709. - n12 * n21 * n33
  3710. + n12 * n23 * n31
  3711. )
  3712. );
  3713. }
  3714. transpose() {
  3715. const te = this.elements;
  3716. let tmp;
  3717. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3718. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3719. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3720. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3721. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3722. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3723. return this;
  3724. }
  3725. setPosition( x, y, z ) {
  3726. const te = this.elements;
  3727. if ( x.isVector3 ) {
  3728. te[ 12 ] = x.x;
  3729. te[ 13 ] = x.y;
  3730. te[ 14 ] = x.z;
  3731. } else {
  3732. te[ 12 ] = x;
  3733. te[ 13 ] = y;
  3734. te[ 14 ] = z;
  3735. }
  3736. return this;
  3737. }
  3738. invert() {
  3739. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3740. const te = this.elements,
  3741. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3742. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3743. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3744. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3745. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3746. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3747. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3748. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3749. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3750. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3751. const detInv = 1 / det;
  3752. te[ 0 ] = t11 * detInv;
  3753. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3754. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3755. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3756. te[ 4 ] = t12 * detInv;
  3757. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3758. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3759. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3760. te[ 8 ] = t13 * detInv;
  3761. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3762. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3763. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3764. te[ 12 ] = t14 * detInv;
  3765. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3766. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3767. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3768. return this;
  3769. }
  3770. scale( v ) {
  3771. const te = this.elements;
  3772. const x = v.x, y = v.y, z = v.z;
  3773. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3774. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3775. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3776. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3777. return this;
  3778. }
  3779. getMaxScaleOnAxis() {
  3780. const te = this.elements;
  3781. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3782. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3783. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3784. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3785. }
  3786. makeTranslation( x, y, z ) {
  3787. this.set(
  3788. 1, 0, 0, x,
  3789. 0, 1, 0, y,
  3790. 0, 0, 1, z,
  3791. 0, 0, 0, 1
  3792. );
  3793. return this;
  3794. }
  3795. makeRotationX( theta ) {
  3796. const c = Math.cos( theta ), s = Math.sin( theta );
  3797. this.set(
  3798. 1, 0, 0, 0,
  3799. 0, c, - s, 0,
  3800. 0, s, c, 0,
  3801. 0, 0, 0, 1
  3802. );
  3803. return this;
  3804. }
  3805. makeRotationY( theta ) {
  3806. const c = Math.cos( theta ), s = Math.sin( theta );
  3807. this.set(
  3808. c, 0, s, 0,
  3809. 0, 1, 0, 0,
  3810. - s, 0, c, 0,
  3811. 0, 0, 0, 1
  3812. );
  3813. return this;
  3814. }
  3815. makeRotationZ( theta ) {
  3816. const c = Math.cos( theta ), s = Math.sin( theta );
  3817. this.set(
  3818. c, - s, 0, 0,
  3819. s, c, 0, 0,
  3820. 0, 0, 1, 0,
  3821. 0, 0, 0, 1
  3822. );
  3823. return this;
  3824. }
  3825. makeRotationAxis( axis, angle ) {
  3826. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3827. const c = Math.cos( angle );
  3828. const s = Math.sin( angle );
  3829. const t = 1 - c;
  3830. const x = axis.x, y = axis.y, z = axis.z;
  3831. const tx = t * x, ty = t * y;
  3832. this.set(
  3833. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3834. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3835. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3836. 0, 0, 0, 1
  3837. );
  3838. return this;
  3839. }
  3840. makeScale( x, y, z ) {
  3841. this.set(
  3842. x, 0, 0, 0,
  3843. 0, y, 0, 0,
  3844. 0, 0, z, 0,
  3845. 0, 0, 0, 1
  3846. );
  3847. return this;
  3848. }
  3849. makeShear( xy, xz, yx, yz, zx, zy ) {
  3850. this.set(
  3851. 1, yx, zx, 0,
  3852. xy, 1, zy, 0,
  3853. xz, yz, 1, 0,
  3854. 0, 0, 0, 1
  3855. );
  3856. return this;
  3857. }
  3858. compose( position, quaternion, scale ) {
  3859. const te = this.elements;
  3860. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3861. const x2 = x + x, y2 = y + y, z2 = z + z;
  3862. const xx = x * x2, xy = x * y2, xz = x * z2;
  3863. const yy = y * y2, yz = y * z2, zz = z * z2;
  3864. const wx = w * x2, wy = w * y2, wz = w * z2;
  3865. const sx = scale.x, sy = scale.y, sz = scale.z;
  3866. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3867. te[ 1 ] = ( xy + wz ) * sx;
  3868. te[ 2 ] = ( xz - wy ) * sx;
  3869. te[ 3 ] = 0;
  3870. te[ 4 ] = ( xy - wz ) * sy;
  3871. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3872. te[ 6 ] = ( yz + wx ) * sy;
  3873. te[ 7 ] = 0;
  3874. te[ 8 ] = ( xz + wy ) * sz;
  3875. te[ 9 ] = ( yz - wx ) * sz;
  3876. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3877. te[ 11 ] = 0;
  3878. te[ 12 ] = position.x;
  3879. te[ 13 ] = position.y;
  3880. te[ 14 ] = position.z;
  3881. te[ 15 ] = 1;
  3882. return this;
  3883. }
  3884. decompose( position, quaternion, scale ) {
  3885. const te = this.elements;
  3886. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3887. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3888. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3889. // if determine is negative, we need to invert one scale
  3890. const det = this.determinant();
  3891. if ( det < 0 ) sx = - sx;
  3892. position.x = te[ 12 ];
  3893. position.y = te[ 13 ];
  3894. position.z = te[ 14 ];
  3895. // scale the rotation part
  3896. _m1$2.copy( this );
  3897. const invSX = 1 / sx;
  3898. const invSY = 1 / sy;
  3899. const invSZ = 1 / sz;
  3900. _m1$2.elements[ 0 ] *= invSX;
  3901. _m1$2.elements[ 1 ] *= invSX;
  3902. _m1$2.elements[ 2 ] *= invSX;
  3903. _m1$2.elements[ 4 ] *= invSY;
  3904. _m1$2.elements[ 5 ] *= invSY;
  3905. _m1$2.elements[ 6 ] *= invSY;
  3906. _m1$2.elements[ 8 ] *= invSZ;
  3907. _m1$2.elements[ 9 ] *= invSZ;
  3908. _m1$2.elements[ 10 ] *= invSZ;
  3909. quaternion.setFromRotationMatrix( _m1$2 );
  3910. scale.x = sx;
  3911. scale.y = sy;
  3912. scale.z = sz;
  3913. return this;
  3914. }
  3915. makePerspective( left, right, top, bottom, near, far ) {
  3916. const te = this.elements;
  3917. const x = 2 * near / ( right - left );
  3918. const y = 2 * near / ( top - bottom );
  3919. const a = ( right + left ) / ( right - left );
  3920. const b = ( top + bottom ) / ( top - bottom );
  3921. const c = - ( far + near ) / ( far - near );
  3922. const d = - 2 * far * near / ( far - near );
  3923. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3924. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3925. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3926. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3927. return this;
  3928. }
  3929. makeOrthographic( left, right, top, bottom, near, far ) {
  3930. const te = this.elements;
  3931. const w = 1.0 / ( right - left );
  3932. const h = 1.0 / ( top - bottom );
  3933. const p = 1.0 / ( far - near );
  3934. const x = ( right + left ) * w;
  3935. const y = ( top + bottom ) * h;
  3936. const z = ( far + near ) * p;
  3937. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3938. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3939. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3940. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3941. return this;
  3942. }
  3943. equals( matrix ) {
  3944. const te = this.elements;
  3945. const me = matrix.elements;
  3946. for ( let i = 0; i < 16; i ++ ) {
  3947. if ( te[ i ] !== me[ i ] ) return false;
  3948. }
  3949. return true;
  3950. }
  3951. fromArray( array, offset = 0 ) {
  3952. for ( let i = 0; i < 16; i ++ ) {
  3953. this.elements[ i ] = array[ i + offset ];
  3954. }
  3955. return this;
  3956. }
  3957. toArray( array = [], offset = 0 ) {
  3958. const te = this.elements;
  3959. array[ offset ] = te[ 0 ];
  3960. array[ offset + 1 ] = te[ 1 ];
  3961. array[ offset + 2 ] = te[ 2 ];
  3962. array[ offset + 3 ] = te[ 3 ];
  3963. array[ offset + 4 ] = te[ 4 ];
  3964. array[ offset + 5 ] = te[ 5 ];
  3965. array[ offset + 6 ] = te[ 6 ];
  3966. array[ offset + 7 ] = te[ 7 ];
  3967. array[ offset + 8 ] = te[ 8 ];
  3968. array[ offset + 9 ] = te[ 9 ];
  3969. array[ offset + 10 ] = te[ 10 ];
  3970. array[ offset + 11 ] = te[ 11 ];
  3971. array[ offset + 12 ] = te[ 12 ];
  3972. array[ offset + 13 ] = te[ 13 ];
  3973. array[ offset + 14 ] = te[ 14 ];
  3974. array[ offset + 15 ] = te[ 15 ];
  3975. return array;
  3976. }
  3977. }
  3978. const _v1$5 = /*@__PURE__*/ new Vector3();
  3979. const _m1$2 = /*@__PURE__*/ new Matrix4();
  3980. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3981. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3982. const _x = /*@__PURE__*/ new Vector3();
  3983. const _y = /*@__PURE__*/ new Vector3();
  3984. const _z = /*@__PURE__*/ new Vector3();
  3985. const _matrix = /*@__PURE__*/ new Matrix4();
  3986. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  3987. class Euler {
  3988. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  3989. this.isEuler = true;
  3990. this._x = x;
  3991. this._y = y;
  3992. this._z = z;
  3993. this._order = order;
  3994. }
  3995. get x() {
  3996. return this._x;
  3997. }
  3998. set x( value ) {
  3999. this._x = value;
  4000. this._onChangeCallback();
  4001. }
  4002. get y() {
  4003. return this._y;
  4004. }
  4005. set y( value ) {
  4006. this._y = value;
  4007. this._onChangeCallback();
  4008. }
  4009. get z() {
  4010. return this._z;
  4011. }
  4012. set z( value ) {
  4013. this._z = value;
  4014. this._onChangeCallback();
  4015. }
  4016. get order() {
  4017. return this._order;
  4018. }
  4019. set order( value ) {
  4020. this._order = value;
  4021. this._onChangeCallback();
  4022. }
  4023. set( x, y, z, order = this._order ) {
  4024. this._x = x;
  4025. this._y = y;
  4026. this._z = z;
  4027. this._order = order;
  4028. this._onChangeCallback();
  4029. return this;
  4030. }
  4031. clone() {
  4032. return new this.constructor( this._x, this._y, this._z, this._order );
  4033. }
  4034. copy( euler ) {
  4035. this._x = euler._x;
  4036. this._y = euler._y;
  4037. this._z = euler._z;
  4038. this._order = euler._order;
  4039. this._onChangeCallback();
  4040. return this;
  4041. }
  4042. setFromRotationMatrix( m, order = this._order, update = true ) {
  4043. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4044. const te = m.elements;
  4045. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4046. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4047. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4048. switch ( order ) {
  4049. case 'XYZ':
  4050. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4051. if ( Math.abs( m13 ) < 0.9999999 ) {
  4052. this._x = Math.atan2( - m23, m33 );
  4053. this._z = Math.atan2( - m12, m11 );
  4054. } else {
  4055. this._x = Math.atan2( m32, m22 );
  4056. this._z = 0;
  4057. }
  4058. break;
  4059. case 'YXZ':
  4060. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4061. if ( Math.abs( m23 ) < 0.9999999 ) {
  4062. this._y = Math.atan2( m13, m33 );
  4063. this._z = Math.atan2( m21, m22 );
  4064. } else {
  4065. this._y = Math.atan2( - m31, m11 );
  4066. this._z = 0;
  4067. }
  4068. break;
  4069. case 'ZXY':
  4070. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4071. if ( Math.abs( m32 ) < 0.9999999 ) {
  4072. this._y = Math.atan2( - m31, m33 );
  4073. this._z = Math.atan2( - m12, m22 );
  4074. } else {
  4075. this._y = 0;
  4076. this._z = Math.atan2( m21, m11 );
  4077. }
  4078. break;
  4079. case 'ZYX':
  4080. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4081. if ( Math.abs( m31 ) < 0.9999999 ) {
  4082. this._x = Math.atan2( m32, m33 );
  4083. this._z = Math.atan2( m21, m11 );
  4084. } else {
  4085. this._x = 0;
  4086. this._z = Math.atan2( - m12, m22 );
  4087. }
  4088. break;
  4089. case 'YZX':
  4090. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4091. if ( Math.abs( m21 ) < 0.9999999 ) {
  4092. this._x = Math.atan2( - m23, m22 );
  4093. this._y = Math.atan2( - m31, m11 );
  4094. } else {
  4095. this._x = 0;
  4096. this._y = Math.atan2( m13, m33 );
  4097. }
  4098. break;
  4099. case 'XZY':
  4100. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4101. if ( Math.abs( m12 ) < 0.9999999 ) {
  4102. this._x = Math.atan2( m32, m22 );
  4103. this._y = Math.atan2( m13, m11 );
  4104. } else {
  4105. this._x = Math.atan2( - m23, m33 );
  4106. this._y = 0;
  4107. }
  4108. break;
  4109. default:
  4110. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4111. }
  4112. this._order = order;
  4113. if ( update === true ) this._onChangeCallback();
  4114. return this;
  4115. }
  4116. setFromQuaternion( q, order, update ) {
  4117. _matrix.makeRotationFromQuaternion( q );
  4118. return this.setFromRotationMatrix( _matrix, order, update );
  4119. }
  4120. setFromVector3( v, order = this._order ) {
  4121. return this.set( v.x, v.y, v.z, order );
  4122. }
  4123. reorder( newOrder ) {
  4124. // WARNING: this discards revolution information -bhouston
  4125. _quaternion$3.setFromEuler( this );
  4126. return this.setFromQuaternion( _quaternion$3, newOrder );
  4127. }
  4128. equals( euler ) {
  4129. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4130. }
  4131. fromArray( array ) {
  4132. this._x = array[ 0 ];
  4133. this._y = array[ 1 ];
  4134. this._z = array[ 2 ];
  4135. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4136. this._onChangeCallback();
  4137. return this;
  4138. }
  4139. toArray( array = [], offset = 0 ) {
  4140. array[ offset ] = this._x;
  4141. array[ offset + 1 ] = this._y;
  4142. array[ offset + 2 ] = this._z;
  4143. array[ offset + 3 ] = this._order;
  4144. return array;
  4145. }
  4146. _onChange( callback ) {
  4147. this._onChangeCallback = callback;
  4148. return this;
  4149. }
  4150. _onChangeCallback() {}
  4151. *[ Symbol.iterator ]() {
  4152. yield this._x;
  4153. yield this._y;
  4154. yield this._z;
  4155. yield this._order;
  4156. }
  4157. }
  4158. Euler.DEFAULT_ORDER = 'XYZ';
  4159. class Layers {
  4160. constructor() {
  4161. this.mask = 1 | 0;
  4162. }
  4163. set( channel ) {
  4164. this.mask = ( 1 << channel | 0 ) >>> 0;
  4165. }
  4166. enable( channel ) {
  4167. this.mask |= 1 << channel | 0;
  4168. }
  4169. enableAll() {
  4170. this.mask = 0xffffffff | 0;
  4171. }
  4172. toggle( channel ) {
  4173. this.mask ^= 1 << channel | 0;
  4174. }
  4175. disable( channel ) {
  4176. this.mask &= ~ ( 1 << channel | 0 );
  4177. }
  4178. disableAll() {
  4179. this.mask = 0;
  4180. }
  4181. test( layers ) {
  4182. return ( this.mask & layers.mask ) !== 0;
  4183. }
  4184. isEnabled( channel ) {
  4185. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4186. }
  4187. }
  4188. let _object3DId = 0;
  4189. const _v1$4 = /*@__PURE__*/ new Vector3();
  4190. const _q1 = /*@__PURE__*/ new Quaternion();
  4191. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4192. const _target = /*@__PURE__*/ new Vector3();
  4193. const _position$3 = /*@__PURE__*/ new Vector3();
  4194. const _scale$2 = /*@__PURE__*/ new Vector3();
  4195. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4196. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4197. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4198. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4199. const _addedEvent = { type: 'added' };
  4200. const _removedEvent = { type: 'removed' };
  4201. class Object3D extends EventDispatcher {
  4202. constructor() {
  4203. super();
  4204. this.isObject3D = true;
  4205. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4206. this.uuid = generateUUID();
  4207. this.name = '';
  4208. this.type = 'Object3D';
  4209. this.parent = null;
  4210. this.children = [];
  4211. this.up = Object3D.DEFAULT_UP.clone();
  4212. const position = new Vector3();
  4213. const rotation = new Euler();
  4214. const quaternion = new Quaternion();
  4215. const scale = new Vector3( 1, 1, 1 );
  4216. function onRotationChange() {
  4217. quaternion.setFromEuler( rotation, false );
  4218. }
  4219. function onQuaternionChange() {
  4220. rotation.setFromQuaternion( quaternion, undefined, false );
  4221. }
  4222. rotation._onChange( onRotationChange );
  4223. quaternion._onChange( onQuaternionChange );
  4224. Object.defineProperties( this, {
  4225. position: {
  4226. configurable: true,
  4227. enumerable: true,
  4228. value: position
  4229. },
  4230. rotation: {
  4231. configurable: true,
  4232. enumerable: true,
  4233. value: rotation
  4234. },
  4235. quaternion: {
  4236. configurable: true,
  4237. enumerable: true,
  4238. value: quaternion
  4239. },
  4240. scale: {
  4241. configurable: true,
  4242. enumerable: true,
  4243. value: scale
  4244. },
  4245. modelViewMatrix: {
  4246. value: new Matrix4()
  4247. },
  4248. normalMatrix: {
  4249. value: new Matrix3()
  4250. }
  4251. } );
  4252. this.matrix = new Matrix4();
  4253. this.matrixWorld = new Matrix4();
  4254. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4255. this.matrixWorldNeedsUpdate = false;
  4256. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4257. this.layers = new Layers();
  4258. this.visible = true;
  4259. this.castShadow = false;
  4260. this.receiveShadow = false;
  4261. this.frustumCulled = true;
  4262. this.renderOrder = 0;
  4263. this.animations = [];
  4264. this.userData = {};
  4265. }
  4266. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4267. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4268. applyMatrix4( matrix ) {
  4269. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4270. this.matrix.premultiply( matrix );
  4271. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4272. }
  4273. applyQuaternion( q ) {
  4274. this.quaternion.premultiply( q );
  4275. return this;
  4276. }
  4277. setRotationFromAxisAngle( axis, angle ) {
  4278. // assumes axis is normalized
  4279. this.quaternion.setFromAxisAngle( axis, angle );
  4280. }
  4281. setRotationFromEuler( euler ) {
  4282. this.quaternion.setFromEuler( euler, true );
  4283. }
  4284. setRotationFromMatrix( m ) {
  4285. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4286. this.quaternion.setFromRotationMatrix( m );
  4287. }
  4288. setRotationFromQuaternion( q ) {
  4289. // assumes q is normalized
  4290. this.quaternion.copy( q );
  4291. }
  4292. rotateOnAxis( axis, angle ) {
  4293. // rotate object on axis in object space
  4294. // axis is assumed to be normalized
  4295. _q1.setFromAxisAngle( axis, angle );
  4296. this.quaternion.multiply( _q1 );
  4297. return this;
  4298. }
  4299. rotateOnWorldAxis( axis, angle ) {
  4300. // rotate object on axis in world space
  4301. // axis is assumed to be normalized
  4302. // method assumes no rotated parent
  4303. _q1.setFromAxisAngle( axis, angle );
  4304. this.quaternion.premultiply( _q1 );
  4305. return this;
  4306. }
  4307. rotateX( angle ) {
  4308. return this.rotateOnAxis( _xAxis, angle );
  4309. }
  4310. rotateY( angle ) {
  4311. return this.rotateOnAxis( _yAxis, angle );
  4312. }
  4313. rotateZ( angle ) {
  4314. return this.rotateOnAxis( _zAxis, angle );
  4315. }
  4316. translateOnAxis( axis, distance ) {
  4317. // translate object by distance along axis in object space
  4318. // axis is assumed to be normalized
  4319. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4320. this.position.add( _v1$4.multiplyScalar( distance ) );
  4321. return this;
  4322. }
  4323. translateX( distance ) {
  4324. return this.translateOnAxis( _xAxis, distance );
  4325. }
  4326. translateY( distance ) {
  4327. return this.translateOnAxis( _yAxis, distance );
  4328. }
  4329. translateZ( distance ) {
  4330. return this.translateOnAxis( _zAxis, distance );
  4331. }
  4332. localToWorld( vector ) {
  4333. this.updateWorldMatrix( true, false );
  4334. return vector.applyMatrix4( this.matrixWorld );
  4335. }
  4336. worldToLocal( vector ) {
  4337. this.updateWorldMatrix( true, false );
  4338. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4339. }
  4340. lookAt( x, y, z ) {
  4341. // This method does not support objects having non-uniformly-scaled parent(s)
  4342. if ( x.isVector3 ) {
  4343. _target.copy( x );
  4344. } else {
  4345. _target.set( x, y, z );
  4346. }
  4347. const parent = this.parent;
  4348. this.updateWorldMatrix( true, false );
  4349. _position$3.setFromMatrixPosition( this.matrixWorld );
  4350. if ( this.isCamera || this.isLight ) {
  4351. _m1$1.lookAt( _position$3, _target, this.up );
  4352. } else {
  4353. _m1$1.lookAt( _target, _position$3, this.up );
  4354. }
  4355. this.quaternion.setFromRotationMatrix( _m1$1 );
  4356. if ( parent ) {
  4357. _m1$1.extractRotation( parent.matrixWorld );
  4358. _q1.setFromRotationMatrix( _m1$1 );
  4359. this.quaternion.premultiply( _q1.invert() );
  4360. }
  4361. }
  4362. add( object ) {
  4363. if ( arguments.length > 1 ) {
  4364. for ( let i = 0; i < arguments.length; i ++ ) {
  4365. this.add( arguments[ i ] );
  4366. }
  4367. return this;
  4368. }
  4369. if ( object === this ) {
  4370. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4371. return this;
  4372. }
  4373. if ( object && object.isObject3D ) {
  4374. if ( object.parent !== null ) {
  4375. object.parent.remove( object );
  4376. }
  4377. object.parent = this;
  4378. this.children.push( object );
  4379. object.dispatchEvent( _addedEvent );
  4380. } else {
  4381. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4382. }
  4383. return this;
  4384. }
  4385. remove( object ) {
  4386. if ( arguments.length > 1 ) {
  4387. for ( let i = 0; i < arguments.length; i ++ ) {
  4388. this.remove( arguments[ i ] );
  4389. }
  4390. return this;
  4391. }
  4392. const index = this.children.indexOf( object );
  4393. if ( index !== - 1 ) {
  4394. object.parent = null;
  4395. this.children.splice( index, 1 );
  4396. object.dispatchEvent( _removedEvent );
  4397. }
  4398. return this;
  4399. }
  4400. removeFromParent() {
  4401. const parent = this.parent;
  4402. if ( parent !== null ) {
  4403. parent.remove( this );
  4404. }
  4405. return this;
  4406. }
  4407. clear() {
  4408. for ( let i = 0; i < this.children.length; i ++ ) {
  4409. const object = this.children[ i ];
  4410. object.parent = null;
  4411. object.dispatchEvent( _removedEvent );
  4412. }
  4413. this.children.length = 0;
  4414. return this;
  4415. }
  4416. attach( object ) {
  4417. // adds object as a child of this, while maintaining the object's world transform
  4418. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4419. this.updateWorldMatrix( true, false );
  4420. _m1$1.copy( this.matrixWorld ).invert();
  4421. if ( object.parent !== null ) {
  4422. object.parent.updateWorldMatrix( true, false );
  4423. _m1$1.multiply( object.parent.matrixWorld );
  4424. }
  4425. object.applyMatrix4( _m1$1 );
  4426. this.add( object );
  4427. object.updateWorldMatrix( false, true );
  4428. return this;
  4429. }
  4430. getObjectById( id ) {
  4431. return this.getObjectByProperty( 'id', id );
  4432. }
  4433. getObjectByName( name ) {
  4434. return this.getObjectByProperty( 'name', name );
  4435. }
  4436. getObjectByProperty( name, value ) {
  4437. if ( this[ name ] === value ) return this;
  4438. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4439. const child = this.children[ i ];
  4440. const object = child.getObjectByProperty( name, value );
  4441. if ( object !== undefined ) {
  4442. return object;
  4443. }
  4444. }
  4445. return undefined;
  4446. }
  4447. getObjectsByProperty( name, value ) {
  4448. let result = [];
  4449. if ( this[ name ] === value ) result.push( this );
  4450. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4451. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4452. if ( childResult.length > 0 ) {
  4453. result = result.concat( childResult );
  4454. }
  4455. }
  4456. return result;
  4457. }
  4458. getWorldPosition( target ) {
  4459. this.updateWorldMatrix( true, false );
  4460. return target.setFromMatrixPosition( this.matrixWorld );
  4461. }
  4462. getWorldQuaternion( target ) {
  4463. this.updateWorldMatrix( true, false );
  4464. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4465. return target;
  4466. }
  4467. getWorldScale( target ) {
  4468. this.updateWorldMatrix( true, false );
  4469. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4470. return target;
  4471. }
  4472. getWorldDirection( target ) {
  4473. this.updateWorldMatrix( true, false );
  4474. const e = this.matrixWorld.elements;
  4475. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4476. }
  4477. raycast( /* raycaster, intersects */ ) {}
  4478. traverse( callback ) {
  4479. callback( this );
  4480. const children = this.children;
  4481. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4482. children[ i ].traverse( callback );
  4483. }
  4484. }
  4485. traverseVisible( callback ) {
  4486. if ( this.visible === false ) return;
  4487. callback( this );
  4488. const children = this.children;
  4489. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4490. children[ i ].traverseVisible( callback );
  4491. }
  4492. }
  4493. traverseAncestors( callback ) {
  4494. const parent = this.parent;
  4495. if ( parent !== null ) {
  4496. callback( parent );
  4497. parent.traverseAncestors( callback );
  4498. }
  4499. }
  4500. updateMatrix() {
  4501. this.matrix.compose( this.position, this.quaternion, this.scale );
  4502. this.matrixWorldNeedsUpdate = true;
  4503. }
  4504. updateMatrixWorld( force ) {
  4505. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4506. if ( this.matrixWorldNeedsUpdate || force ) {
  4507. if ( this.parent === null ) {
  4508. this.matrixWorld.copy( this.matrix );
  4509. } else {
  4510. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4511. }
  4512. this.matrixWorldNeedsUpdate = false;
  4513. force = true;
  4514. }
  4515. // update children
  4516. const children = this.children;
  4517. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4518. const child = children[ i ];
  4519. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4520. child.updateMatrixWorld( force );
  4521. }
  4522. }
  4523. }
  4524. updateWorldMatrix( updateParents, updateChildren ) {
  4525. const parent = this.parent;
  4526. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4527. parent.updateWorldMatrix( true, false );
  4528. }
  4529. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4530. if ( this.parent === null ) {
  4531. this.matrixWorld.copy( this.matrix );
  4532. } else {
  4533. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4534. }
  4535. // update children
  4536. if ( updateChildren === true ) {
  4537. const children = this.children;
  4538. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4539. const child = children[ i ];
  4540. if ( child.matrixWorldAutoUpdate === true ) {
  4541. child.updateWorldMatrix( false, true );
  4542. }
  4543. }
  4544. }
  4545. }
  4546. toJSON( meta ) {
  4547. // meta is a string when called from JSON.stringify
  4548. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4549. const output = {};
  4550. // meta is a hash used to collect geometries, materials.
  4551. // not providing it implies that this is the root object
  4552. // being serialized.
  4553. if ( isRootObject ) {
  4554. // initialize meta obj
  4555. meta = {
  4556. geometries: {},
  4557. materials: {},
  4558. textures: {},
  4559. images: {},
  4560. shapes: {},
  4561. skeletons: {},
  4562. animations: {},
  4563. nodes: {}
  4564. };
  4565. output.metadata = {
  4566. version: 4.5,
  4567. type: 'Object',
  4568. generator: 'Object3D.toJSON'
  4569. };
  4570. }
  4571. // standard Object3D serialization
  4572. const object = {};
  4573. object.uuid = this.uuid;
  4574. object.type = this.type;
  4575. if ( this.name !== '' ) object.name = this.name;
  4576. if ( this.castShadow === true ) object.castShadow = true;
  4577. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4578. if ( this.visible === false ) object.visible = false;
  4579. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4580. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4581. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4582. object.layers = this.layers.mask;
  4583. object.matrix = this.matrix.toArray();
  4584. object.up = this.up.toArray();
  4585. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4586. // object specific properties
  4587. if ( this.isInstancedMesh ) {
  4588. object.type = 'InstancedMesh';
  4589. object.count = this.count;
  4590. object.instanceMatrix = this.instanceMatrix.toJSON();
  4591. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4592. }
  4593. //
  4594. function serialize( library, element ) {
  4595. if ( library[ element.uuid ] === undefined ) {
  4596. library[ element.uuid ] = element.toJSON( meta );
  4597. }
  4598. return element.uuid;
  4599. }
  4600. if ( this.isScene ) {
  4601. if ( this.background ) {
  4602. if ( this.background.isColor ) {
  4603. object.background = this.background.toJSON();
  4604. } else if ( this.background.isTexture ) {
  4605. object.background = this.background.toJSON( meta ).uuid;
  4606. }
  4607. }
  4608. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4609. object.environment = this.environment.toJSON( meta ).uuid;
  4610. }
  4611. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4612. object.geometry = serialize( meta.geometries, this.geometry );
  4613. const parameters = this.geometry.parameters;
  4614. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4615. const shapes = parameters.shapes;
  4616. if ( Array.isArray( shapes ) ) {
  4617. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4618. const shape = shapes[ i ];
  4619. serialize( meta.shapes, shape );
  4620. }
  4621. } else {
  4622. serialize( meta.shapes, shapes );
  4623. }
  4624. }
  4625. }
  4626. if ( this.isSkinnedMesh ) {
  4627. object.bindMode = this.bindMode;
  4628. object.bindMatrix = this.bindMatrix.toArray();
  4629. if ( this.skeleton !== undefined ) {
  4630. serialize( meta.skeletons, this.skeleton );
  4631. object.skeleton = this.skeleton.uuid;
  4632. }
  4633. }
  4634. if ( this.material !== undefined ) {
  4635. if ( Array.isArray( this.material ) ) {
  4636. const uuids = [];
  4637. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4638. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4639. }
  4640. object.material = uuids;
  4641. } else {
  4642. object.material = serialize( meta.materials, this.material );
  4643. }
  4644. }
  4645. //
  4646. if ( this.children.length > 0 ) {
  4647. object.children = [];
  4648. for ( let i = 0; i < this.children.length; i ++ ) {
  4649. object.children.push( this.children[ i ].toJSON( meta ).object );
  4650. }
  4651. }
  4652. //
  4653. if ( this.animations.length > 0 ) {
  4654. object.animations = [];
  4655. for ( let i = 0; i < this.animations.length; i ++ ) {
  4656. const animation = this.animations[ i ];
  4657. object.animations.push( serialize( meta.animations, animation ) );
  4658. }
  4659. }
  4660. if ( isRootObject ) {
  4661. const geometries = extractFromCache( meta.geometries );
  4662. const materials = extractFromCache( meta.materials );
  4663. const textures = extractFromCache( meta.textures );
  4664. const images = extractFromCache( meta.images );
  4665. const shapes = extractFromCache( meta.shapes );
  4666. const skeletons = extractFromCache( meta.skeletons );
  4667. const animations = extractFromCache( meta.animations );
  4668. const nodes = extractFromCache( meta.nodes );
  4669. if ( geometries.length > 0 ) output.geometries = geometries;
  4670. if ( materials.length > 0 ) output.materials = materials;
  4671. if ( textures.length > 0 ) output.textures = textures;
  4672. if ( images.length > 0 ) output.images = images;
  4673. if ( shapes.length > 0 ) output.shapes = shapes;
  4674. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4675. if ( animations.length > 0 ) output.animations = animations;
  4676. if ( nodes.length > 0 ) output.nodes = nodes;
  4677. }
  4678. output.object = object;
  4679. return output;
  4680. // extract data from the cache hash
  4681. // remove metadata on each item
  4682. // and return as array
  4683. function extractFromCache( cache ) {
  4684. const values = [];
  4685. for ( const key in cache ) {
  4686. const data = cache[ key ];
  4687. delete data.metadata;
  4688. values.push( data );
  4689. }
  4690. return values;
  4691. }
  4692. }
  4693. clone( recursive ) {
  4694. return new this.constructor().copy( this, recursive );
  4695. }
  4696. copy( source, recursive = true ) {
  4697. this.name = source.name;
  4698. this.up.copy( source.up );
  4699. this.position.copy( source.position );
  4700. this.rotation.order = source.rotation.order;
  4701. this.quaternion.copy( source.quaternion );
  4702. this.scale.copy( source.scale );
  4703. this.matrix.copy( source.matrix );
  4704. this.matrixWorld.copy( source.matrixWorld );
  4705. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4706. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4707. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4708. this.layers.mask = source.layers.mask;
  4709. this.visible = source.visible;
  4710. this.castShadow = source.castShadow;
  4711. this.receiveShadow = source.receiveShadow;
  4712. this.frustumCulled = source.frustumCulled;
  4713. this.renderOrder = source.renderOrder;
  4714. this.userData = deepClone( source.userData );
  4715. if ( recursive === true ) {
  4716. for ( let i = 0; i < source.children.length; i ++ ) {
  4717. const child = source.children[ i ];
  4718. this.add( child.clone() );
  4719. }
  4720. }
  4721. return this;
  4722. }
  4723. }
  4724. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4725. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4726. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4727. const _v0$1 = /*@__PURE__*/ new Vector3();
  4728. const _v1$3 = /*@__PURE__*/ new Vector3();
  4729. const _v2$2 = /*@__PURE__*/ new Vector3();
  4730. const _v3$1 = /*@__PURE__*/ new Vector3();
  4731. const _vab = /*@__PURE__*/ new Vector3();
  4732. const _vac = /*@__PURE__*/ new Vector3();
  4733. const _vbc = /*@__PURE__*/ new Vector3();
  4734. const _vap = /*@__PURE__*/ new Vector3();
  4735. const _vbp = /*@__PURE__*/ new Vector3();
  4736. const _vcp = /*@__PURE__*/ new Vector3();
  4737. let warnedGetUV = false;
  4738. class Triangle {
  4739. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4740. this.a = a;
  4741. this.b = b;
  4742. this.c = c;
  4743. }
  4744. static getNormal( a, b, c, target ) {
  4745. target.subVectors( c, b );
  4746. _v0$1.subVectors( a, b );
  4747. target.cross( _v0$1 );
  4748. const targetLengthSq = target.lengthSq();
  4749. if ( targetLengthSq > 0 ) {
  4750. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4751. }
  4752. return target.set( 0, 0, 0 );
  4753. }
  4754. // static/instance method to calculate barycentric coordinates
  4755. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4756. static getBarycoord( point, a, b, c, target ) {
  4757. _v0$1.subVectors( c, a );
  4758. _v1$3.subVectors( b, a );
  4759. _v2$2.subVectors( point, a );
  4760. const dot00 = _v0$1.dot( _v0$1 );
  4761. const dot01 = _v0$1.dot( _v1$3 );
  4762. const dot02 = _v0$1.dot( _v2$2 );
  4763. const dot11 = _v1$3.dot( _v1$3 );
  4764. const dot12 = _v1$3.dot( _v2$2 );
  4765. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4766. // collinear or singular triangle
  4767. if ( denom === 0 ) {
  4768. // arbitrary location outside of triangle?
  4769. // not sure if this is the best idea, maybe should be returning undefined
  4770. return target.set( - 2, - 1, - 1 );
  4771. }
  4772. const invDenom = 1 / denom;
  4773. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4774. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4775. // barycentric coordinates must always sum to 1
  4776. return target.set( 1 - u - v, v, u );
  4777. }
  4778. static containsPoint( point, a, b, c ) {
  4779. this.getBarycoord( point, a, b, c, _v3$1 );
  4780. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4781. }
  4782. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { // @deprecated, r151
  4783. if ( warnedGetUV === false ) {
  4784. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4785. warnedGetUV = true;
  4786. }
  4787. return this.getInterpolation( point, p1, p2, p3, uv1, uv2, uv3, target );
  4788. }
  4789. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4790. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4791. target.setScalar( 0 );
  4792. target.addScaledVector( v1, _v3$1.x );
  4793. target.addScaledVector( v2, _v3$1.y );
  4794. target.addScaledVector( v3, _v3$1.z );
  4795. return target;
  4796. }
  4797. static isFrontFacing( a, b, c, direction ) {
  4798. _v0$1.subVectors( c, b );
  4799. _v1$3.subVectors( a, b );
  4800. // strictly front facing
  4801. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4802. }
  4803. set( a, b, c ) {
  4804. this.a.copy( a );
  4805. this.b.copy( b );
  4806. this.c.copy( c );
  4807. return this;
  4808. }
  4809. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4810. this.a.copy( points[ i0 ] );
  4811. this.b.copy( points[ i1 ] );
  4812. this.c.copy( points[ i2 ] );
  4813. return this;
  4814. }
  4815. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4816. this.a.fromBufferAttribute( attribute, i0 );
  4817. this.b.fromBufferAttribute( attribute, i1 );
  4818. this.c.fromBufferAttribute( attribute, i2 );
  4819. return this;
  4820. }
  4821. clone() {
  4822. return new this.constructor().copy( this );
  4823. }
  4824. copy( triangle ) {
  4825. this.a.copy( triangle.a );
  4826. this.b.copy( triangle.b );
  4827. this.c.copy( triangle.c );
  4828. return this;
  4829. }
  4830. getArea() {
  4831. _v0$1.subVectors( this.c, this.b );
  4832. _v1$3.subVectors( this.a, this.b );
  4833. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4834. }
  4835. getMidpoint( target ) {
  4836. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4837. }
  4838. getNormal( target ) {
  4839. return Triangle.getNormal( this.a, this.b, this.c, target );
  4840. }
  4841. getPlane( target ) {
  4842. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4843. }
  4844. getBarycoord( point, target ) {
  4845. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4846. }
  4847. getUV( point, uv1, uv2, uv3, target ) { // @deprecated, r151
  4848. if ( warnedGetUV === false ) {
  4849. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4850. warnedGetUV = true;
  4851. }
  4852. return Triangle.getInterpolation( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4853. }
  4854. getInterpolation( point, v1, v2, v3, target ) {
  4855. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  4856. }
  4857. containsPoint( point ) {
  4858. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4859. }
  4860. isFrontFacing( direction ) {
  4861. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4862. }
  4863. intersectsBox( box ) {
  4864. return box.intersectsTriangle( this );
  4865. }
  4866. closestPointToPoint( p, target ) {
  4867. const a = this.a, b = this.b, c = this.c;
  4868. let v, w;
  4869. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4870. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4871. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4872. // basically, we're distinguishing which of the voronoi regions of the triangle
  4873. // the point lies in with the minimum amount of redundant computation.
  4874. _vab.subVectors( b, a );
  4875. _vac.subVectors( c, a );
  4876. _vap.subVectors( p, a );
  4877. const d1 = _vab.dot( _vap );
  4878. const d2 = _vac.dot( _vap );
  4879. if ( d1 <= 0 && d2 <= 0 ) {
  4880. // vertex region of A; barycentric coords (1, 0, 0)
  4881. return target.copy( a );
  4882. }
  4883. _vbp.subVectors( p, b );
  4884. const d3 = _vab.dot( _vbp );
  4885. const d4 = _vac.dot( _vbp );
  4886. if ( d3 >= 0 && d4 <= d3 ) {
  4887. // vertex region of B; barycentric coords (0, 1, 0)
  4888. return target.copy( b );
  4889. }
  4890. const vc = d1 * d4 - d3 * d2;
  4891. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4892. v = d1 / ( d1 - d3 );
  4893. // edge region of AB; barycentric coords (1-v, v, 0)
  4894. return target.copy( a ).addScaledVector( _vab, v );
  4895. }
  4896. _vcp.subVectors( p, c );
  4897. const d5 = _vab.dot( _vcp );
  4898. const d6 = _vac.dot( _vcp );
  4899. if ( d6 >= 0 && d5 <= d6 ) {
  4900. // vertex region of C; barycentric coords (0, 0, 1)
  4901. return target.copy( c );
  4902. }
  4903. const vb = d5 * d2 - d1 * d6;
  4904. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4905. w = d2 / ( d2 - d6 );
  4906. // edge region of AC; barycentric coords (1-w, 0, w)
  4907. return target.copy( a ).addScaledVector( _vac, w );
  4908. }
  4909. const va = d3 * d6 - d5 * d4;
  4910. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4911. _vbc.subVectors( c, b );
  4912. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4913. // edge region of BC; barycentric coords (0, 1-w, w)
  4914. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4915. }
  4916. // face region
  4917. const denom = 1 / ( va + vb + vc );
  4918. // u = va * denom
  4919. v = vb * denom;
  4920. w = vc * denom;
  4921. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4922. }
  4923. equals( triangle ) {
  4924. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4925. }
  4926. }
  4927. let materialId = 0;
  4928. class Material extends EventDispatcher {
  4929. constructor() {
  4930. super();
  4931. this.isMaterial = true;
  4932. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4933. this.uuid = generateUUID();
  4934. this.name = '';
  4935. this.type = 'Material';
  4936. this.blending = NormalBlending;
  4937. this.side = FrontSide;
  4938. this.vertexColors = false;
  4939. this.opacity = 1;
  4940. this.transparent = false;
  4941. this.blendSrc = SrcAlphaFactor;
  4942. this.blendDst = OneMinusSrcAlphaFactor;
  4943. this.blendEquation = AddEquation;
  4944. this.blendSrcAlpha = null;
  4945. this.blendDstAlpha = null;
  4946. this.blendEquationAlpha = null;
  4947. this.depthFunc = LessEqualDepth;
  4948. this.depthTest = true;
  4949. this.depthWrite = true;
  4950. this.stencilWriteMask = 0xff;
  4951. this.stencilFunc = AlwaysStencilFunc;
  4952. this.stencilRef = 0;
  4953. this.stencilFuncMask = 0xff;
  4954. this.stencilFail = KeepStencilOp;
  4955. this.stencilZFail = KeepStencilOp;
  4956. this.stencilZPass = KeepStencilOp;
  4957. this.stencilWrite = false;
  4958. this.clippingPlanes = null;
  4959. this.clipIntersection = false;
  4960. this.clipShadows = false;
  4961. this.shadowSide = null;
  4962. this.colorWrite = true;
  4963. this.precision = null; // override the renderer's default precision for this material
  4964. this.polygonOffset = false;
  4965. this.polygonOffsetFactor = 0;
  4966. this.polygonOffsetUnits = 0;
  4967. this.dithering = false;
  4968. this.alphaToCoverage = false;
  4969. this.premultipliedAlpha = false;
  4970. this.forceSinglePass = false;
  4971. this.visible = true;
  4972. this.toneMapped = true;
  4973. this.userData = {};
  4974. this.version = 0;
  4975. this._alphaTest = 0;
  4976. }
  4977. get alphaTest() {
  4978. return this._alphaTest;
  4979. }
  4980. set alphaTest( value ) {
  4981. if ( this._alphaTest > 0 !== value > 0 ) {
  4982. this.version ++;
  4983. }
  4984. this._alphaTest = value;
  4985. }
  4986. onBuild( /* shaderobject, renderer */ ) {}
  4987. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  4988. onBeforeCompile( /* shaderobject, renderer */ ) {}
  4989. customProgramCacheKey() {
  4990. return this.onBeforeCompile.toString();
  4991. }
  4992. setValues( values ) {
  4993. if ( values === undefined ) return;
  4994. for ( const key in values ) {
  4995. const newValue = values[ key ];
  4996. if ( newValue === undefined ) {
  4997. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  4998. continue;
  4999. }
  5000. const currentValue = this[ key ];
  5001. if ( currentValue === undefined ) {
  5002. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5003. continue;
  5004. }
  5005. if ( currentValue && currentValue.isColor ) {
  5006. currentValue.set( newValue );
  5007. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5008. currentValue.copy( newValue );
  5009. } else {
  5010. this[ key ] = newValue;
  5011. }
  5012. }
  5013. }
  5014. toJSON( meta ) {
  5015. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5016. if ( isRootObject ) {
  5017. meta = {
  5018. textures: {},
  5019. images: {}
  5020. };
  5021. }
  5022. const data = {
  5023. metadata: {
  5024. version: 4.5,
  5025. type: 'Material',
  5026. generator: 'Material.toJSON'
  5027. }
  5028. };
  5029. // standard Material serialization
  5030. data.uuid = this.uuid;
  5031. data.type = this.type;
  5032. if ( this.name !== '' ) data.name = this.name;
  5033. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5034. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5035. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5036. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5037. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5038. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5039. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5040. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5041. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5042. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5043. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5044. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5045. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5046. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5047. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5048. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5049. }
  5050. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5051. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5052. }
  5053. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5054. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5055. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5056. }
  5057. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5058. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5059. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5060. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5061. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5062. }
  5063. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5064. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5065. }
  5066. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5067. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5068. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5069. if ( this.lightMap && this.lightMap.isTexture ) {
  5070. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5071. data.lightMapIntensity = this.lightMapIntensity;
  5072. }
  5073. if ( this.aoMap && this.aoMap.isTexture ) {
  5074. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5075. data.aoMapIntensity = this.aoMapIntensity;
  5076. }
  5077. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5078. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5079. data.bumpScale = this.bumpScale;
  5080. }
  5081. if ( this.normalMap && this.normalMap.isTexture ) {
  5082. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5083. data.normalMapType = this.normalMapType;
  5084. data.normalScale = this.normalScale.toArray();
  5085. }
  5086. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5087. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5088. data.displacementScale = this.displacementScale;
  5089. data.displacementBias = this.displacementBias;
  5090. }
  5091. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5092. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5093. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5094. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5095. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5096. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5097. if ( this.envMap && this.envMap.isTexture ) {
  5098. data.envMap = this.envMap.toJSON( meta ).uuid;
  5099. if ( this.combine !== undefined ) data.combine = this.combine;
  5100. }
  5101. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5102. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5103. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5104. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5105. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5106. }
  5107. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5108. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5109. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5110. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5111. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5112. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5113. if ( this.size !== undefined ) data.size = this.size;
  5114. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5115. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5116. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5117. if ( this.side !== FrontSide ) data.side = this.side;
  5118. if ( this.vertexColors ) data.vertexColors = true;
  5119. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5120. if ( this.transparent === true ) data.transparent = this.transparent;
  5121. data.depthFunc = this.depthFunc;
  5122. data.depthTest = this.depthTest;
  5123. data.depthWrite = this.depthWrite;
  5124. data.colorWrite = this.colorWrite;
  5125. data.stencilWrite = this.stencilWrite;
  5126. data.stencilWriteMask = this.stencilWriteMask;
  5127. data.stencilFunc = this.stencilFunc;
  5128. data.stencilRef = this.stencilRef;
  5129. data.stencilFuncMask = this.stencilFuncMask;
  5130. data.stencilFail = this.stencilFail;
  5131. data.stencilZFail = this.stencilZFail;
  5132. data.stencilZPass = this.stencilZPass;
  5133. // rotation (SpriteMaterial)
  5134. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5135. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5136. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5137. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5138. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5139. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5140. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5141. if ( this.scale !== undefined ) data.scale = this.scale;
  5142. if ( this.dithering === true ) data.dithering = true;
  5143. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5144. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5145. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5146. if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;
  5147. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5148. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5149. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5150. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5151. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5152. if ( this.visible === false ) data.visible = false;
  5153. if ( this.toneMapped === false ) data.toneMapped = false;
  5154. if ( this.fog === false ) data.fog = false;
  5155. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5156. // TODO: Copied from Object3D.toJSON
  5157. function extractFromCache( cache ) {
  5158. const values = [];
  5159. for ( const key in cache ) {
  5160. const data = cache[ key ];
  5161. delete data.metadata;
  5162. values.push( data );
  5163. }
  5164. return values;
  5165. }
  5166. if ( isRootObject ) {
  5167. const textures = extractFromCache( meta.textures );
  5168. const images = extractFromCache( meta.images );
  5169. if ( textures.length > 0 ) data.textures = textures;
  5170. if ( images.length > 0 ) data.images = images;
  5171. }
  5172. return data;
  5173. }
  5174. clone() {
  5175. return new this.constructor().copy( this );
  5176. }
  5177. copy( source ) {
  5178. this.name = source.name;
  5179. this.blending = source.blending;
  5180. this.side = source.side;
  5181. this.vertexColors = source.vertexColors;
  5182. this.opacity = source.opacity;
  5183. this.transparent = source.transparent;
  5184. this.blendSrc = source.blendSrc;
  5185. this.blendDst = source.blendDst;
  5186. this.blendEquation = source.blendEquation;
  5187. this.blendSrcAlpha = source.blendSrcAlpha;
  5188. this.blendDstAlpha = source.blendDstAlpha;
  5189. this.blendEquationAlpha = source.blendEquationAlpha;
  5190. this.depthFunc = source.depthFunc;
  5191. this.depthTest = source.depthTest;
  5192. this.depthWrite = source.depthWrite;
  5193. this.stencilWriteMask = source.stencilWriteMask;
  5194. this.stencilFunc = source.stencilFunc;
  5195. this.stencilRef = source.stencilRef;
  5196. this.stencilFuncMask = source.stencilFuncMask;
  5197. this.stencilFail = source.stencilFail;
  5198. this.stencilZFail = source.stencilZFail;
  5199. this.stencilZPass = source.stencilZPass;
  5200. this.stencilWrite = source.stencilWrite;
  5201. const srcPlanes = source.clippingPlanes;
  5202. let dstPlanes = null;
  5203. if ( srcPlanes !== null ) {
  5204. const n = srcPlanes.length;
  5205. dstPlanes = new Array( n );
  5206. for ( let i = 0; i !== n; ++ i ) {
  5207. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5208. }
  5209. }
  5210. this.clippingPlanes = dstPlanes;
  5211. this.clipIntersection = source.clipIntersection;
  5212. this.clipShadows = source.clipShadows;
  5213. this.shadowSide = source.shadowSide;
  5214. this.colorWrite = source.colorWrite;
  5215. this.precision = source.precision;
  5216. this.polygonOffset = source.polygonOffset;
  5217. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5218. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5219. this.dithering = source.dithering;
  5220. this.alphaTest = source.alphaTest;
  5221. this.alphaToCoverage = source.alphaToCoverage;
  5222. this.premultipliedAlpha = source.premultipliedAlpha;
  5223. this.forceSinglePass = source.forceSinglePass;
  5224. this.visible = source.visible;
  5225. this.toneMapped = source.toneMapped;
  5226. this.userData = deepClone( source.userData );
  5227. return this;
  5228. }
  5229. dispose() {
  5230. this.dispatchEvent( { type: 'dispose' } );
  5231. }
  5232. set needsUpdate( value ) {
  5233. if ( value === true ) this.version ++;
  5234. }
  5235. }
  5236. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5237. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5238. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5239. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5240. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5241. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5242. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5243. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5244. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5245. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5246. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5247. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5248. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5249. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5250. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5251. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5252. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5253. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5254. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5255. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5256. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5257. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5258. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5259. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5260. const _hslA = { h: 0, s: 0, l: 0 };
  5261. const _hslB = { h: 0, s: 0, l: 0 };
  5262. function hue2rgb( p, q, t ) {
  5263. if ( t < 0 ) t += 1;
  5264. if ( t > 1 ) t -= 1;
  5265. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5266. if ( t < 1 / 2 ) return q;
  5267. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5268. return p;
  5269. }
  5270. class Color {
  5271. constructor( r, g, b ) {
  5272. this.isColor = true;
  5273. this.r = 1;
  5274. this.g = 1;
  5275. this.b = 1;
  5276. if ( g === undefined && b === undefined ) {
  5277. // r is THREE.Color, hex or string
  5278. return this.set( r );
  5279. }
  5280. return this.setRGB( r, g, b );
  5281. }
  5282. set( value ) {
  5283. if ( value && value.isColor ) {
  5284. this.copy( value );
  5285. } else if ( typeof value === 'number' ) {
  5286. this.setHex( value );
  5287. } else if ( typeof value === 'string' ) {
  5288. this.setStyle( value );
  5289. }
  5290. return this;
  5291. }
  5292. setScalar( scalar ) {
  5293. this.r = scalar;
  5294. this.g = scalar;
  5295. this.b = scalar;
  5296. return this;
  5297. }
  5298. setHex( hex, colorSpace = SRGBColorSpace ) {
  5299. hex = Math.floor( hex );
  5300. this.r = ( hex >> 16 & 255 ) / 255;
  5301. this.g = ( hex >> 8 & 255 ) / 255;
  5302. this.b = ( hex & 255 ) / 255;
  5303. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5304. return this;
  5305. }
  5306. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5307. this.r = r;
  5308. this.g = g;
  5309. this.b = b;
  5310. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5311. return this;
  5312. }
  5313. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5314. // h,s,l ranges are in 0.0 - 1.0
  5315. h = euclideanModulo( h, 1 );
  5316. s = clamp( s, 0, 1 );
  5317. l = clamp( l, 0, 1 );
  5318. if ( s === 0 ) {
  5319. this.r = this.g = this.b = l;
  5320. } else {
  5321. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5322. const q = ( 2 * l ) - p;
  5323. this.r = hue2rgb( q, p, h + 1 / 3 );
  5324. this.g = hue2rgb( q, p, h );
  5325. this.b = hue2rgb( q, p, h - 1 / 3 );
  5326. }
  5327. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5328. return this;
  5329. }
  5330. setStyle( style, colorSpace = SRGBColorSpace ) {
  5331. function handleAlpha( string ) {
  5332. if ( string === undefined ) return;
  5333. if ( parseFloat( string ) < 1 ) {
  5334. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5335. }
  5336. }
  5337. let m;
  5338. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5339. // rgb / hsl
  5340. let color;
  5341. const name = m[ 1 ];
  5342. const components = m[ 2 ];
  5343. switch ( name ) {
  5344. case 'rgb':
  5345. case 'rgba':
  5346. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5347. // rgb(255,0,0) rgba(255,0,0,0.5)
  5348. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5349. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5350. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5351. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5352. handleAlpha( color[ 4 ] );
  5353. return this;
  5354. }
  5355. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5356. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5357. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5358. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5359. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5360. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5361. handleAlpha( color[ 4 ] );
  5362. return this;
  5363. }
  5364. break;
  5365. case 'hsl':
  5366. case 'hsla':
  5367. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5368. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5369. const h = parseFloat( color[ 1 ] ) / 360;
  5370. const s = parseFloat( color[ 2 ] ) / 100;
  5371. const l = parseFloat( color[ 3 ] ) / 100;
  5372. handleAlpha( color[ 4 ] );
  5373. return this.setHSL( h, s, l, colorSpace );
  5374. }
  5375. break;
  5376. default:
  5377. console.warn( 'THREE.Color: Unknown color model ' + style );
  5378. }
  5379. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5380. // hex color
  5381. const hex = m[ 1 ];
  5382. const size = hex.length;
  5383. if ( size === 3 ) {
  5384. // #ff0
  5385. return this.setRGB(
  5386. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5387. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5388. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5389. colorSpace
  5390. );
  5391. } else if ( size === 6 ) {
  5392. // #ff0000
  5393. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5394. } else {
  5395. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5396. }
  5397. } else if ( style && style.length > 0 ) {
  5398. return this.setColorName( style, colorSpace );
  5399. }
  5400. return this;
  5401. }
  5402. setColorName( style, colorSpace = SRGBColorSpace ) {
  5403. // color keywords
  5404. const hex = _colorKeywords[ style.toLowerCase() ];
  5405. if ( hex !== undefined ) {
  5406. // red
  5407. this.setHex( hex, colorSpace );
  5408. } else {
  5409. // unknown color
  5410. console.warn( 'THREE.Color: Unknown color ' + style );
  5411. }
  5412. return this;
  5413. }
  5414. clone() {
  5415. return new this.constructor( this.r, this.g, this.b );
  5416. }
  5417. copy( color ) {
  5418. this.r = color.r;
  5419. this.g = color.g;
  5420. this.b = color.b;
  5421. return this;
  5422. }
  5423. copySRGBToLinear( color ) {
  5424. this.r = SRGBToLinear( color.r );
  5425. this.g = SRGBToLinear( color.g );
  5426. this.b = SRGBToLinear( color.b );
  5427. return this;
  5428. }
  5429. copyLinearToSRGB( color ) {
  5430. this.r = LinearToSRGB( color.r );
  5431. this.g = LinearToSRGB( color.g );
  5432. this.b = LinearToSRGB( color.b );
  5433. return this;
  5434. }
  5435. convertSRGBToLinear() {
  5436. this.copySRGBToLinear( this );
  5437. return this;
  5438. }
  5439. convertLinearToSRGB() {
  5440. this.copyLinearToSRGB( this );
  5441. return this;
  5442. }
  5443. getHex( colorSpace = SRGBColorSpace ) {
  5444. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5445. return clamp( _color.r * 255, 0, 255 ) << 16 ^ clamp( _color.g * 255, 0, 255 ) << 8 ^ clamp( _color.b * 255, 0, 255 ) << 0;
  5446. }
  5447. getHexString( colorSpace = SRGBColorSpace ) {
  5448. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5449. }
  5450. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5451. // h,s,l ranges are in 0.0 - 1.0
  5452. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5453. const r = _color.r, g = _color.g, b = _color.b;
  5454. const max = Math.max( r, g, b );
  5455. const min = Math.min( r, g, b );
  5456. let hue, saturation;
  5457. const lightness = ( min + max ) / 2.0;
  5458. if ( min === max ) {
  5459. hue = 0;
  5460. saturation = 0;
  5461. } else {
  5462. const delta = max - min;
  5463. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5464. switch ( max ) {
  5465. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5466. case g: hue = ( b - r ) / delta + 2; break;
  5467. case b: hue = ( r - g ) / delta + 4; break;
  5468. }
  5469. hue /= 6;
  5470. }
  5471. target.h = hue;
  5472. target.s = saturation;
  5473. target.l = lightness;
  5474. return target;
  5475. }
  5476. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5477. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5478. target.r = _color.r;
  5479. target.g = _color.g;
  5480. target.b = _color.b;
  5481. return target;
  5482. }
  5483. getStyle( colorSpace = SRGBColorSpace ) {
  5484. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5485. const r = _color.r, g = _color.g, b = _color.b;
  5486. if ( colorSpace !== SRGBColorSpace ) {
  5487. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5488. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5489. }
  5490. return `rgb(${( r * 255 ) | 0},${( g * 255 ) | 0},${( b * 255 ) | 0})`;
  5491. }
  5492. offsetHSL( h, s, l ) {
  5493. this.getHSL( _hslA );
  5494. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5495. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5496. return this;
  5497. }
  5498. add( color ) {
  5499. this.r += color.r;
  5500. this.g += color.g;
  5501. this.b += color.b;
  5502. return this;
  5503. }
  5504. addColors( color1, color2 ) {
  5505. this.r = color1.r + color2.r;
  5506. this.g = color1.g + color2.g;
  5507. this.b = color1.b + color2.b;
  5508. return this;
  5509. }
  5510. addScalar( s ) {
  5511. this.r += s;
  5512. this.g += s;
  5513. this.b += s;
  5514. return this;
  5515. }
  5516. sub( color ) {
  5517. this.r = Math.max( 0, this.r - color.r );
  5518. this.g = Math.max( 0, this.g - color.g );
  5519. this.b = Math.max( 0, this.b - color.b );
  5520. return this;
  5521. }
  5522. multiply( color ) {
  5523. this.r *= color.r;
  5524. this.g *= color.g;
  5525. this.b *= color.b;
  5526. return this;
  5527. }
  5528. multiplyScalar( s ) {
  5529. this.r *= s;
  5530. this.g *= s;
  5531. this.b *= s;
  5532. return this;
  5533. }
  5534. lerp( color, alpha ) {
  5535. this.r += ( color.r - this.r ) * alpha;
  5536. this.g += ( color.g - this.g ) * alpha;
  5537. this.b += ( color.b - this.b ) * alpha;
  5538. return this;
  5539. }
  5540. lerpColors( color1, color2, alpha ) {
  5541. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5542. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5543. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5544. return this;
  5545. }
  5546. lerpHSL( color, alpha ) {
  5547. this.getHSL( _hslA );
  5548. color.getHSL( _hslB );
  5549. const h = lerp( _hslA.h, _hslB.h, alpha );
  5550. const s = lerp( _hslA.s, _hslB.s, alpha );
  5551. const l = lerp( _hslA.l, _hslB.l, alpha );
  5552. this.setHSL( h, s, l );
  5553. return this;
  5554. }
  5555. setFromVector3( v ) {
  5556. this.r = v.x;
  5557. this.g = v.y;
  5558. this.b = v.z;
  5559. return this;
  5560. }
  5561. applyMatrix3( m ) {
  5562. const r = this.r, g = this.g, b = this.b;
  5563. const e = m.elements;
  5564. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5565. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5566. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5567. return this;
  5568. }
  5569. equals( c ) {
  5570. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5571. }
  5572. fromArray( array, offset = 0 ) {
  5573. this.r = array[ offset ];
  5574. this.g = array[ offset + 1 ];
  5575. this.b = array[ offset + 2 ];
  5576. return this;
  5577. }
  5578. toArray( array = [], offset = 0 ) {
  5579. array[ offset ] = this.r;
  5580. array[ offset + 1 ] = this.g;
  5581. array[ offset + 2 ] = this.b;
  5582. return array;
  5583. }
  5584. fromBufferAttribute( attribute, index ) {
  5585. this.r = attribute.getX( index );
  5586. this.g = attribute.getY( index );
  5587. this.b = attribute.getZ( index );
  5588. return this;
  5589. }
  5590. toJSON() {
  5591. return this.getHex();
  5592. }
  5593. *[ Symbol.iterator ]() {
  5594. yield this.r;
  5595. yield this.g;
  5596. yield this.b;
  5597. }
  5598. }
  5599. const _color = /*@__PURE__*/ new Color();
  5600. Color.NAMES = _colorKeywords;
  5601. class MeshBasicMaterial extends Material {
  5602. constructor( parameters ) {
  5603. super();
  5604. this.isMeshBasicMaterial = true;
  5605. this.type = 'MeshBasicMaterial';
  5606. this.color = new Color( 0xffffff ); // emissive
  5607. this.map = null;
  5608. this.lightMap = null;
  5609. this.lightMapIntensity = 1.0;
  5610. this.aoMap = null;
  5611. this.aoMapIntensity = 1.0;
  5612. this.specularMap = null;
  5613. this.alphaMap = null;
  5614. this.envMap = null;
  5615. this.combine = MultiplyOperation;
  5616. this.reflectivity = 1;
  5617. this.refractionRatio = 0.98;
  5618. this.wireframe = false;
  5619. this.wireframeLinewidth = 1;
  5620. this.wireframeLinecap = 'round';
  5621. this.wireframeLinejoin = 'round';
  5622. this.fog = true;
  5623. this.setValues( parameters );
  5624. }
  5625. copy( source ) {
  5626. super.copy( source );
  5627. this.color.copy( source.color );
  5628. this.map = source.map;
  5629. this.lightMap = source.lightMap;
  5630. this.lightMapIntensity = source.lightMapIntensity;
  5631. this.aoMap = source.aoMap;
  5632. this.aoMapIntensity = source.aoMapIntensity;
  5633. this.specularMap = source.specularMap;
  5634. this.alphaMap = source.alphaMap;
  5635. this.envMap = source.envMap;
  5636. this.combine = source.combine;
  5637. this.reflectivity = source.reflectivity;
  5638. this.refractionRatio = source.refractionRatio;
  5639. this.wireframe = source.wireframe;
  5640. this.wireframeLinewidth = source.wireframeLinewidth;
  5641. this.wireframeLinecap = source.wireframeLinecap;
  5642. this.wireframeLinejoin = source.wireframeLinejoin;
  5643. this.fog = source.fog;
  5644. return this;
  5645. }
  5646. }
  5647. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5648. const _tables = /*@__PURE__*/ _generateTables();
  5649. function _generateTables() {
  5650. // float32 to float16 helpers
  5651. const buffer = new ArrayBuffer( 4 );
  5652. const floatView = new Float32Array( buffer );
  5653. const uint32View = new Uint32Array( buffer );
  5654. const baseTable = new Uint32Array( 512 );
  5655. const shiftTable = new Uint32Array( 512 );
  5656. for ( let i = 0; i < 256; ++ i ) {
  5657. const e = i - 127;
  5658. // very small number (0, -0)
  5659. if ( e < - 27 ) {
  5660. baseTable[ i ] = 0x0000;
  5661. baseTable[ i | 0x100 ] = 0x8000;
  5662. shiftTable[ i ] = 24;
  5663. shiftTable[ i | 0x100 ] = 24;
  5664. // small number (denorm)
  5665. } else if ( e < - 14 ) {
  5666. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5667. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5668. shiftTable[ i ] = - e - 1;
  5669. shiftTable[ i | 0x100 ] = - e - 1;
  5670. // normal number
  5671. } else if ( e <= 15 ) {
  5672. baseTable[ i ] = ( e + 15 ) << 10;
  5673. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5674. shiftTable[ i ] = 13;
  5675. shiftTable[ i | 0x100 ] = 13;
  5676. // large number (Infinity, -Infinity)
  5677. } else if ( e < 128 ) {
  5678. baseTable[ i ] = 0x7c00;
  5679. baseTable[ i | 0x100 ] = 0xfc00;
  5680. shiftTable[ i ] = 24;
  5681. shiftTable[ i | 0x100 ] = 24;
  5682. // stay (NaN, Infinity, -Infinity)
  5683. } else {
  5684. baseTable[ i ] = 0x7c00;
  5685. baseTable[ i | 0x100 ] = 0xfc00;
  5686. shiftTable[ i ] = 13;
  5687. shiftTable[ i | 0x100 ] = 13;
  5688. }
  5689. }
  5690. // float16 to float32 helpers
  5691. const mantissaTable = new Uint32Array( 2048 );
  5692. const exponentTable = new Uint32Array( 64 );
  5693. const offsetTable = new Uint32Array( 64 );
  5694. for ( let i = 1; i < 1024; ++ i ) {
  5695. let m = i << 13; // zero pad mantissa bits
  5696. let e = 0; // zero exponent
  5697. // normalized
  5698. while ( ( m & 0x00800000 ) === 0 ) {
  5699. m <<= 1;
  5700. e -= 0x00800000; // decrement exponent
  5701. }
  5702. m &= ~ 0x00800000; // clear leading 1 bit
  5703. e += 0x38800000; // adjust bias
  5704. mantissaTable[ i ] = m | e;
  5705. }
  5706. for ( let i = 1024; i < 2048; ++ i ) {
  5707. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5708. }
  5709. for ( let i = 1; i < 31; ++ i ) {
  5710. exponentTable[ i ] = i << 23;
  5711. }
  5712. exponentTable[ 31 ] = 0x47800000;
  5713. exponentTable[ 32 ] = 0x80000000;
  5714. for ( let i = 33; i < 63; ++ i ) {
  5715. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5716. }
  5717. exponentTable[ 63 ] = 0xc7800000;
  5718. for ( let i = 1; i < 64; ++ i ) {
  5719. if ( i !== 32 ) {
  5720. offsetTable[ i ] = 1024;
  5721. }
  5722. }
  5723. return {
  5724. floatView: floatView,
  5725. uint32View: uint32View,
  5726. baseTable: baseTable,
  5727. shiftTable: shiftTable,
  5728. mantissaTable: mantissaTable,
  5729. exponentTable: exponentTable,
  5730. offsetTable: offsetTable
  5731. };
  5732. }
  5733. // float32 to float16
  5734. function toHalfFloat( val ) {
  5735. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5736. val = clamp( val, - 65504, 65504 );
  5737. _tables.floatView[ 0 ] = val;
  5738. const f = _tables.uint32View[ 0 ];
  5739. const e = ( f >> 23 ) & 0x1ff;
  5740. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5741. }
  5742. // float16 to float32
  5743. function fromHalfFloat( val ) {
  5744. const m = val >> 10;
  5745. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5746. return _tables.floatView[ 0 ];
  5747. }
  5748. const DataUtils = {
  5749. toHalfFloat: toHalfFloat,
  5750. fromHalfFloat: fromHalfFloat,
  5751. };
  5752. const _vector$8 = /*@__PURE__*/ new Vector3();
  5753. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5754. class BufferAttribute {
  5755. constructor( array, itemSize, normalized = false ) {
  5756. if ( Array.isArray( array ) ) {
  5757. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5758. }
  5759. this.isBufferAttribute = true;
  5760. this.name = '';
  5761. this.array = array;
  5762. this.itemSize = itemSize;
  5763. this.count = array !== undefined ? array.length / itemSize : 0;
  5764. this.normalized = normalized;
  5765. this.usage = StaticDrawUsage;
  5766. this.updateRange = { offset: 0, count: - 1 };
  5767. this.version = 0;
  5768. }
  5769. onUploadCallback() {}
  5770. set needsUpdate( value ) {
  5771. if ( value === true ) this.version ++;
  5772. }
  5773. setUsage( value ) {
  5774. this.usage = value;
  5775. return this;
  5776. }
  5777. copy( source ) {
  5778. this.name = source.name;
  5779. this.array = new source.array.constructor( source.array );
  5780. this.itemSize = source.itemSize;
  5781. this.count = source.count;
  5782. this.normalized = source.normalized;
  5783. this.usage = source.usage;
  5784. return this;
  5785. }
  5786. copyAt( index1, attribute, index2 ) {
  5787. index1 *= this.itemSize;
  5788. index2 *= attribute.itemSize;
  5789. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5790. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5791. }
  5792. return this;
  5793. }
  5794. copyArray( array ) {
  5795. this.array.set( array );
  5796. return this;
  5797. }
  5798. applyMatrix3( m ) {
  5799. if ( this.itemSize === 2 ) {
  5800. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5801. _vector2$1.fromBufferAttribute( this, i );
  5802. _vector2$1.applyMatrix3( m );
  5803. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5804. }
  5805. } else if ( this.itemSize === 3 ) {
  5806. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5807. _vector$8.fromBufferAttribute( this, i );
  5808. _vector$8.applyMatrix3( m );
  5809. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5810. }
  5811. }
  5812. return this;
  5813. }
  5814. applyMatrix4( m ) {
  5815. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5816. _vector$8.fromBufferAttribute( this, i );
  5817. _vector$8.applyMatrix4( m );
  5818. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5819. }
  5820. return this;
  5821. }
  5822. applyNormalMatrix( m ) {
  5823. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5824. _vector$8.fromBufferAttribute( this, i );
  5825. _vector$8.applyNormalMatrix( m );
  5826. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5827. }
  5828. return this;
  5829. }
  5830. transformDirection( m ) {
  5831. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5832. _vector$8.fromBufferAttribute( this, i );
  5833. _vector$8.transformDirection( m );
  5834. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5835. }
  5836. return this;
  5837. }
  5838. set( value, offset = 0 ) {
  5839. // Matching BufferAttribute constructor, do not normalize the array.
  5840. this.array.set( value, offset );
  5841. return this;
  5842. }
  5843. getX( index ) {
  5844. let x = this.array[ index * this.itemSize ];
  5845. if ( this.normalized ) x = denormalize( x, this.array );
  5846. return x;
  5847. }
  5848. setX( index, x ) {
  5849. if ( this.normalized ) x = normalize( x, this.array );
  5850. this.array[ index * this.itemSize ] = x;
  5851. return this;
  5852. }
  5853. getY( index ) {
  5854. let y = this.array[ index * this.itemSize + 1 ];
  5855. if ( this.normalized ) y = denormalize( y, this.array );
  5856. return y;
  5857. }
  5858. setY( index, y ) {
  5859. if ( this.normalized ) y = normalize( y, this.array );
  5860. this.array[ index * this.itemSize + 1 ] = y;
  5861. return this;
  5862. }
  5863. getZ( index ) {
  5864. let z = this.array[ index * this.itemSize + 2 ];
  5865. if ( this.normalized ) z = denormalize( z, this.array );
  5866. return z;
  5867. }
  5868. setZ( index, z ) {
  5869. if ( this.normalized ) z = normalize( z, this.array );
  5870. this.array[ index * this.itemSize + 2 ] = z;
  5871. return this;
  5872. }
  5873. getW( index ) {
  5874. let w = this.array[ index * this.itemSize + 3 ];
  5875. if ( this.normalized ) w = denormalize( w, this.array );
  5876. return w;
  5877. }
  5878. setW( index, w ) {
  5879. if ( this.normalized ) w = normalize( w, this.array );
  5880. this.array[ index * this.itemSize + 3 ] = w;
  5881. return this;
  5882. }
  5883. setXY( index, x, y ) {
  5884. index *= this.itemSize;
  5885. if ( this.normalized ) {
  5886. x = normalize( x, this.array );
  5887. y = normalize( y, this.array );
  5888. }
  5889. this.array[ index + 0 ] = x;
  5890. this.array[ index + 1 ] = y;
  5891. return this;
  5892. }
  5893. setXYZ( index, x, y, z ) {
  5894. index *= this.itemSize;
  5895. if ( this.normalized ) {
  5896. x = normalize( x, this.array );
  5897. y = normalize( y, this.array );
  5898. z = normalize( z, this.array );
  5899. }
  5900. this.array[ index + 0 ] = x;
  5901. this.array[ index + 1 ] = y;
  5902. this.array[ index + 2 ] = z;
  5903. return this;
  5904. }
  5905. setXYZW( index, x, y, z, w ) {
  5906. index *= this.itemSize;
  5907. if ( this.normalized ) {
  5908. x = normalize( x, this.array );
  5909. y = normalize( y, this.array );
  5910. z = normalize( z, this.array );
  5911. w = normalize( w, this.array );
  5912. }
  5913. this.array[ index + 0 ] = x;
  5914. this.array[ index + 1 ] = y;
  5915. this.array[ index + 2 ] = z;
  5916. this.array[ index + 3 ] = w;
  5917. return this;
  5918. }
  5919. onUpload( callback ) {
  5920. this.onUploadCallback = callback;
  5921. return this;
  5922. }
  5923. clone() {
  5924. return new this.constructor( this.array, this.itemSize ).copy( this );
  5925. }
  5926. toJSON() {
  5927. const data = {
  5928. itemSize: this.itemSize,
  5929. type: this.array.constructor.name,
  5930. array: Array.from( this.array ),
  5931. normalized: this.normalized
  5932. };
  5933. if ( this.name !== '' ) data.name = this.name;
  5934. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5935. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5936. return data;
  5937. }
  5938. copyColorsArray() { // @deprecated, r144
  5939. console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );
  5940. }
  5941. copyVector2sArray() { // @deprecated, r144
  5942. console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );
  5943. }
  5944. copyVector3sArray() { // @deprecated, r144
  5945. console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );
  5946. }
  5947. copyVector4sArray() { // @deprecated, r144
  5948. console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );
  5949. }
  5950. }
  5951. //
  5952. class Int8BufferAttribute extends BufferAttribute {
  5953. constructor( array, itemSize, normalized ) {
  5954. super( new Int8Array( array ), itemSize, normalized );
  5955. }
  5956. }
  5957. class Uint8BufferAttribute extends BufferAttribute {
  5958. constructor( array, itemSize, normalized ) {
  5959. super( new Uint8Array( array ), itemSize, normalized );
  5960. }
  5961. }
  5962. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5963. constructor( array, itemSize, normalized ) {
  5964. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5965. }
  5966. }
  5967. class Int16BufferAttribute extends BufferAttribute {
  5968. constructor( array, itemSize, normalized ) {
  5969. super( new Int16Array( array ), itemSize, normalized );
  5970. }
  5971. }
  5972. class Uint16BufferAttribute extends BufferAttribute {
  5973. constructor( array, itemSize, normalized ) {
  5974. super( new Uint16Array( array ), itemSize, normalized );
  5975. }
  5976. }
  5977. class Int32BufferAttribute extends BufferAttribute {
  5978. constructor( array, itemSize, normalized ) {
  5979. super( new Int32Array( array ), itemSize, normalized );
  5980. }
  5981. }
  5982. class Uint32BufferAttribute extends BufferAttribute {
  5983. constructor( array, itemSize, normalized ) {
  5984. super( new Uint32Array( array ), itemSize, normalized );
  5985. }
  5986. }
  5987. class Float16BufferAttribute extends BufferAttribute {
  5988. constructor( array, itemSize, normalized ) {
  5989. super( new Uint16Array( array ), itemSize, normalized );
  5990. this.isFloat16BufferAttribute = true;
  5991. }
  5992. getX( index ) {
  5993. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  5994. if ( this.normalized ) x = denormalize( x, this.array );
  5995. return x;
  5996. }
  5997. setX( index, x ) {
  5998. if ( this.normalized ) x = normalize( x, this.array );
  5999. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6000. return this;
  6001. }
  6002. getY( index ) {
  6003. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6004. if ( this.normalized ) y = denormalize( y, this.array );
  6005. return y;
  6006. }
  6007. setY( index, y ) {
  6008. if ( this.normalized ) y = normalize( y, this.array );
  6009. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6010. return this;
  6011. }
  6012. getZ( index ) {
  6013. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6014. if ( this.normalized ) z = denormalize( z, this.array );
  6015. return z;
  6016. }
  6017. setZ( index, z ) {
  6018. if ( this.normalized ) z = normalize( z, this.array );
  6019. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6020. return this;
  6021. }
  6022. getW( index ) {
  6023. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6024. if ( this.normalized ) w = denormalize( w, this.array );
  6025. return w;
  6026. }
  6027. setW( index, w ) {
  6028. if ( this.normalized ) w = normalize( w, this.array );
  6029. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6030. return this;
  6031. }
  6032. setXY( index, x, y ) {
  6033. index *= this.itemSize;
  6034. if ( this.normalized ) {
  6035. x = normalize( x, this.array );
  6036. y = normalize( y, this.array );
  6037. }
  6038. this.array[ index + 0 ] = toHalfFloat( x );
  6039. this.array[ index + 1 ] = toHalfFloat( y );
  6040. return this;
  6041. }
  6042. setXYZ( index, x, y, z ) {
  6043. index *= this.itemSize;
  6044. if ( this.normalized ) {
  6045. x = normalize( x, this.array );
  6046. y = normalize( y, this.array );
  6047. z = normalize( z, this.array );
  6048. }
  6049. this.array[ index + 0 ] = toHalfFloat( x );
  6050. this.array[ index + 1 ] = toHalfFloat( y );
  6051. this.array[ index + 2 ] = toHalfFloat( z );
  6052. return this;
  6053. }
  6054. setXYZW( index, x, y, z, w ) {
  6055. index *= this.itemSize;
  6056. if ( this.normalized ) {
  6057. x = normalize( x, this.array );
  6058. y = normalize( y, this.array );
  6059. z = normalize( z, this.array );
  6060. w = normalize( w, this.array );
  6061. }
  6062. this.array[ index + 0 ] = toHalfFloat( x );
  6063. this.array[ index + 1 ] = toHalfFloat( y );
  6064. this.array[ index + 2 ] = toHalfFloat( z );
  6065. this.array[ index + 3 ] = toHalfFloat( w );
  6066. return this;
  6067. }
  6068. }
  6069. class Float32BufferAttribute extends BufferAttribute {
  6070. constructor( array, itemSize, normalized ) {
  6071. super( new Float32Array( array ), itemSize, normalized );
  6072. }
  6073. }
  6074. class Float64BufferAttribute extends BufferAttribute {
  6075. constructor( array, itemSize, normalized ) {
  6076. super( new Float64Array( array ), itemSize, normalized );
  6077. }
  6078. }
  6079. let _id$1 = 0;
  6080. const _m1 = /*@__PURE__*/ new Matrix4();
  6081. const _obj = /*@__PURE__*/ new Object3D();
  6082. const _offset = /*@__PURE__*/ new Vector3();
  6083. const _box$1 = /*@__PURE__*/ new Box3();
  6084. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6085. const _vector$7 = /*@__PURE__*/ new Vector3();
  6086. class BufferGeometry extends EventDispatcher {
  6087. constructor() {
  6088. super();
  6089. this.isBufferGeometry = true;
  6090. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  6091. this.uuid = generateUUID();
  6092. this.name = '';
  6093. this.type = 'BufferGeometry';
  6094. this.index = null;
  6095. this.attributes = {};
  6096. this.morphAttributes = {};
  6097. this.morphTargetsRelative = false;
  6098. this.groups = [];
  6099. this.boundingBox = null;
  6100. this.boundingSphere = null;
  6101. this.drawRange = { start: 0, count: Infinity };
  6102. this.userData = {};
  6103. }
  6104. getIndex() {
  6105. return this.index;
  6106. }
  6107. setIndex( index ) {
  6108. if ( Array.isArray( index ) ) {
  6109. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6110. } else {
  6111. this.index = index;
  6112. }
  6113. return this;
  6114. }
  6115. getAttribute( name ) {
  6116. return this.attributes[ name ];
  6117. }
  6118. setAttribute( name, attribute ) {
  6119. this.attributes[ name ] = attribute;
  6120. return this;
  6121. }
  6122. deleteAttribute( name ) {
  6123. delete this.attributes[ name ];
  6124. return this;
  6125. }
  6126. hasAttribute( name ) {
  6127. return this.attributes[ name ] !== undefined;
  6128. }
  6129. addGroup( start, count, materialIndex = 0 ) {
  6130. this.groups.push( {
  6131. start: start,
  6132. count: count,
  6133. materialIndex: materialIndex
  6134. } );
  6135. }
  6136. clearGroups() {
  6137. this.groups = [];
  6138. }
  6139. setDrawRange( start, count ) {
  6140. this.drawRange.start = start;
  6141. this.drawRange.count = count;
  6142. }
  6143. applyMatrix4( matrix ) {
  6144. const position = this.attributes.position;
  6145. if ( position !== undefined ) {
  6146. position.applyMatrix4( matrix );
  6147. position.needsUpdate = true;
  6148. }
  6149. const normal = this.attributes.normal;
  6150. if ( normal !== undefined ) {
  6151. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6152. normal.applyNormalMatrix( normalMatrix );
  6153. normal.needsUpdate = true;
  6154. }
  6155. const tangent = this.attributes.tangent;
  6156. if ( tangent !== undefined ) {
  6157. tangent.transformDirection( matrix );
  6158. tangent.needsUpdate = true;
  6159. }
  6160. if ( this.boundingBox !== null ) {
  6161. this.computeBoundingBox();
  6162. }
  6163. if ( this.boundingSphere !== null ) {
  6164. this.computeBoundingSphere();
  6165. }
  6166. return this;
  6167. }
  6168. applyQuaternion( q ) {
  6169. _m1.makeRotationFromQuaternion( q );
  6170. this.applyMatrix4( _m1 );
  6171. return this;
  6172. }
  6173. rotateX( angle ) {
  6174. // rotate geometry around world x-axis
  6175. _m1.makeRotationX( angle );
  6176. this.applyMatrix4( _m1 );
  6177. return this;
  6178. }
  6179. rotateY( angle ) {
  6180. // rotate geometry around world y-axis
  6181. _m1.makeRotationY( angle );
  6182. this.applyMatrix4( _m1 );
  6183. return this;
  6184. }
  6185. rotateZ( angle ) {
  6186. // rotate geometry around world z-axis
  6187. _m1.makeRotationZ( angle );
  6188. this.applyMatrix4( _m1 );
  6189. return this;
  6190. }
  6191. translate( x, y, z ) {
  6192. // translate geometry
  6193. _m1.makeTranslation( x, y, z );
  6194. this.applyMatrix4( _m1 );
  6195. return this;
  6196. }
  6197. scale( x, y, z ) {
  6198. // scale geometry
  6199. _m1.makeScale( x, y, z );
  6200. this.applyMatrix4( _m1 );
  6201. return this;
  6202. }
  6203. lookAt( vector ) {
  6204. _obj.lookAt( vector );
  6205. _obj.updateMatrix();
  6206. this.applyMatrix4( _obj.matrix );
  6207. return this;
  6208. }
  6209. center() {
  6210. this.computeBoundingBox();
  6211. this.boundingBox.getCenter( _offset ).negate();
  6212. this.translate( _offset.x, _offset.y, _offset.z );
  6213. return this;
  6214. }
  6215. setFromPoints( points ) {
  6216. const position = [];
  6217. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6218. const point = points[ i ];
  6219. position.push( point.x, point.y, point.z || 0 );
  6220. }
  6221. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6222. return this;
  6223. }
  6224. computeBoundingBox() {
  6225. if ( this.boundingBox === null ) {
  6226. this.boundingBox = new Box3();
  6227. }
  6228. const position = this.attributes.position;
  6229. const morphAttributesPosition = this.morphAttributes.position;
  6230. if ( position && position.isGLBufferAttribute ) {
  6231. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6232. this.boundingBox.set(
  6233. new Vector3( - Infinity, - Infinity, - Infinity ),
  6234. new Vector3( + Infinity, + Infinity, + Infinity )
  6235. );
  6236. return;
  6237. }
  6238. if ( position !== undefined ) {
  6239. this.boundingBox.setFromBufferAttribute( position );
  6240. // process morph attributes if present
  6241. if ( morphAttributesPosition ) {
  6242. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6243. const morphAttribute = morphAttributesPosition[ i ];
  6244. _box$1.setFromBufferAttribute( morphAttribute );
  6245. if ( this.morphTargetsRelative ) {
  6246. _vector$7.addVectors( this.boundingBox.min, _box$1.min );
  6247. this.boundingBox.expandByPoint( _vector$7 );
  6248. _vector$7.addVectors( this.boundingBox.max, _box$1.max );
  6249. this.boundingBox.expandByPoint( _vector$7 );
  6250. } else {
  6251. this.boundingBox.expandByPoint( _box$1.min );
  6252. this.boundingBox.expandByPoint( _box$1.max );
  6253. }
  6254. }
  6255. }
  6256. } else {
  6257. this.boundingBox.makeEmpty();
  6258. }
  6259. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6260. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6261. }
  6262. }
  6263. computeBoundingSphere() {
  6264. if ( this.boundingSphere === null ) {
  6265. this.boundingSphere = new Sphere();
  6266. }
  6267. const position = this.attributes.position;
  6268. const morphAttributesPosition = this.morphAttributes.position;
  6269. if ( position && position.isGLBufferAttribute ) {
  6270. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6271. this.boundingSphere.set( new Vector3(), Infinity );
  6272. return;
  6273. }
  6274. if ( position ) {
  6275. // first, find the center of the bounding sphere
  6276. const center = this.boundingSphere.center;
  6277. _box$1.setFromBufferAttribute( position );
  6278. // process morph attributes if present
  6279. if ( morphAttributesPosition ) {
  6280. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6281. const morphAttribute = morphAttributesPosition[ i ];
  6282. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6283. if ( this.morphTargetsRelative ) {
  6284. _vector$7.addVectors( _box$1.min, _boxMorphTargets.min );
  6285. _box$1.expandByPoint( _vector$7 );
  6286. _vector$7.addVectors( _box$1.max, _boxMorphTargets.max );
  6287. _box$1.expandByPoint( _vector$7 );
  6288. } else {
  6289. _box$1.expandByPoint( _boxMorphTargets.min );
  6290. _box$1.expandByPoint( _boxMorphTargets.max );
  6291. }
  6292. }
  6293. }
  6294. _box$1.getCenter( center );
  6295. // second, try to find a boundingSphere with a radius smaller than the
  6296. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6297. let maxRadiusSq = 0;
  6298. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6299. _vector$7.fromBufferAttribute( position, i );
  6300. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6301. }
  6302. // process morph attributes if present
  6303. if ( morphAttributesPosition ) {
  6304. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6305. const morphAttribute = morphAttributesPosition[ i ];
  6306. const morphTargetsRelative = this.morphTargetsRelative;
  6307. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6308. _vector$7.fromBufferAttribute( morphAttribute, j );
  6309. if ( morphTargetsRelative ) {
  6310. _offset.fromBufferAttribute( position, j );
  6311. _vector$7.add( _offset );
  6312. }
  6313. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6314. }
  6315. }
  6316. }
  6317. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6318. if ( isNaN( this.boundingSphere.radius ) ) {
  6319. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6320. }
  6321. }
  6322. }
  6323. computeTangents() {
  6324. const index = this.index;
  6325. const attributes = this.attributes;
  6326. // based on http://www.terathon.com/code/tangent.html
  6327. // (per vertex tangents)
  6328. if ( index === null ||
  6329. attributes.position === undefined ||
  6330. attributes.normal === undefined ||
  6331. attributes.uv === undefined ) {
  6332. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6333. return;
  6334. }
  6335. const indices = index.array;
  6336. const positions = attributes.position.array;
  6337. const normals = attributes.normal.array;
  6338. const uvs = attributes.uv.array;
  6339. const nVertices = positions.length / 3;
  6340. if ( this.hasAttribute( 'tangent' ) === false ) {
  6341. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6342. }
  6343. const tangents = this.getAttribute( 'tangent' ).array;
  6344. const tan1 = [], tan2 = [];
  6345. for ( let i = 0; i < nVertices; i ++ ) {
  6346. tan1[ i ] = new Vector3();
  6347. tan2[ i ] = new Vector3();
  6348. }
  6349. const vA = new Vector3(),
  6350. vB = new Vector3(),
  6351. vC = new Vector3(),
  6352. uvA = new Vector2(),
  6353. uvB = new Vector2(),
  6354. uvC = new Vector2(),
  6355. sdir = new Vector3(),
  6356. tdir = new Vector3();
  6357. function handleTriangle( a, b, c ) {
  6358. vA.fromArray( positions, a * 3 );
  6359. vB.fromArray( positions, b * 3 );
  6360. vC.fromArray( positions, c * 3 );
  6361. uvA.fromArray( uvs, a * 2 );
  6362. uvB.fromArray( uvs, b * 2 );
  6363. uvC.fromArray( uvs, c * 2 );
  6364. vB.sub( vA );
  6365. vC.sub( vA );
  6366. uvB.sub( uvA );
  6367. uvC.sub( uvA );
  6368. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6369. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6370. if ( ! isFinite( r ) ) return;
  6371. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6372. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6373. tan1[ a ].add( sdir );
  6374. tan1[ b ].add( sdir );
  6375. tan1[ c ].add( sdir );
  6376. tan2[ a ].add( tdir );
  6377. tan2[ b ].add( tdir );
  6378. tan2[ c ].add( tdir );
  6379. }
  6380. let groups = this.groups;
  6381. if ( groups.length === 0 ) {
  6382. groups = [ {
  6383. start: 0,
  6384. count: indices.length
  6385. } ];
  6386. }
  6387. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6388. const group = groups[ i ];
  6389. const start = group.start;
  6390. const count = group.count;
  6391. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6392. handleTriangle(
  6393. indices[ j + 0 ],
  6394. indices[ j + 1 ],
  6395. indices[ j + 2 ]
  6396. );
  6397. }
  6398. }
  6399. const tmp = new Vector3(), tmp2 = new Vector3();
  6400. const n = new Vector3(), n2 = new Vector3();
  6401. function handleVertex( v ) {
  6402. n.fromArray( normals, v * 3 );
  6403. n2.copy( n );
  6404. const t = tan1[ v ];
  6405. // Gram-Schmidt orthogonalize
  6406. tmp.copy( t );
  6407. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6408. // Calculate handedness
  6409. tmp2.crossVectors( n2, t );
  6410. const test = tmp2.dot( tan2[ v ] );
  6411. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6412. tangents[ v * 4 ] = tmp.x;
  6413. tangents[ v * 4 + 1 ] = tmp.y;
  6414. tangents[ v * 4 + 2 ] = tmp.z;
  6415. tangents[ v * 4 + 3 ] = w;
  6416. }
  6417. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6418. const group = groups[ i ];
  6419. const start = group.start;
  6420. const count = group.count;
  6421. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6422. handleVertex( indices[ j + 0 ] );
  6423. handleVertex( indices[ j + 1 ] );
  6424. handleVertex( indices[ j + 2 ] );
  6425. }
  6426. }
  6427. }
  6428. computeVertexNormals() {
  6429. const index = this.index;
  6430. const positionAttribute = this.getAttribute( 'position' );
  6431. if ( positionAttribute !== undefined ) {
  6432. let normalAttribute = this.getAttribute( 'normal' );
  6433. if ( normalAttribute === undefined ) {
  6434. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6435. this.setAttribute( 'normal', normalAttribute );
  6436. } else {
  6437. // reset existing normals to zero
  6438. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6439. normalAttribute.setXYZ( i, 0, 0, 0 );
  6440. }
  6441. }
  6442. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6443. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6444. const cb = new Vector3(), ab = new Vector3();
  6445. // indexed elements
  6446. if ( index ) {
  6447. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6448. const vA = index.getX( i + 0 );
  6449. const vB = index.getX( i + 1 );
  6450. const vC = index.getX( i + 2 );
  6451. pA.fromBufferAttribute( positionAttribute, vA );
  6452. pB.fromBufferAttribute( positionAttribute, vB );
  6453. pC.fromBufferAttribute( positionAttribute, vC );
  6454. cb.subVectors( pC, pB );
  6455. ab.subVectors( pA, pB );
  6456. cb.cross( ab );
  6457. nA.fromBufferAttribute( normalAttribute, vA );
  6458. nB.fromBufferAttribute( normalAttribute, vB );
  6459. nC.fromBufferAttribute( normalAttribute, vC );
  6460. nA.add( cb );
  6461. nB.add( cb );
  6462. nC.add( cb );
  6463. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6464. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6465. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6466. }
  6467. } else {
  6468. // non-indexed elements (unconnected triangle soup)
  6469. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6470. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6471. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6472. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6473. cb.subVectors( pC, pB );
  6474. ab.subVectors( pA, pB );
  6475. cb.cross( ab );
  6476. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6477. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6478. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6479. }
  6480. }
  6481. this.normalizeNormals();
  6482. normalAttribute.needsUpdate = true;
  6483. }
  6484. }
  6485. merge() { // @deprecated, r144
  6486. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeGeometries() instead.' );
  6487. return this;
  6488. }
  6489. normalizeNormals() {
  6490. const normals = this.attributes.normal;
  6491. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6492. _vector$7.fromBufferAttribute( normals, i );
  6493. _vector$7.normalize();
  6494. normals.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  6495. }
  6496. }
  6497. toNonIndexed() {
  6498. function convertBufferAttribute( attribute, indices ) {
  6499. const array = attribute.array;
  6500. const itemSize = attribute.itemSize;
  6501. const normalized = attribute.normalized;
  6502. const array2 = new array.constructor( indices.length * itemSize );
  6503. let index = 0, index2 = 0;
  6504. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6505. if ( attribute.isInterleavedBufferAttribute ) {
  6506. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6507. } else {
  6508. index = indices[ i ] * itemSize;
  6509. }
  6510. for ( let j = 0; j < itemSize; j ++ ) {
  6511. array2[ index2 ++ ] = array[ index ++ ];
  6512. }
  6513. }
  6514. return new BufferAttribute( array2, itemSize, normalized );
  6515. }
  6516. //
  6517. if ( this.index === null ) {
  6518. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6519. return this;
  6520. }
  6521. const geometry2 = new BufferGeometry();
  6522. const indices = this.index.array;
  6523. const attributes = this.attributes;
  6524. // attributes
  6525. for ( const name in attributes ) {
  6526. const attribute = attributes[ name ];
  6527. const newAttribute = convertBufferAttribute( attribute, indices );
  6528. geometry2.setAttribute( name, newAttribute );
  6529. }
  6530. // morph attributes
  6531. const morphAttributes = this.morphAttributes;
  6532. for ( const name in morphAttributes ) {
  6533. const morphArray = [];
  6534. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6535. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6536. const attribute = morphAttribute[ i ];
  6537. const newAttribute = convertBufferAttribute( attribute, indices );
  6538. morphArray.push( newAttribute );
  6539. }
  6540. geometry2.morphAttributes[ name ] = morphArray;
  6541. }
  6542. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6543. // groups
  6544. const groups = this.groups;
  6545. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6546. const group = groups[ i ];
  6547. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6548. }
  6549. return geometry2;
  6550. }
  6551. toJSON() {
  6552. const data = {
  6553. metadata: {
  6554. version: 4.5,
  6555. type: 'BufferGeometry',
  6556. generator: 'BufferGeometry.toJSON'
  6557. }
  6558. };
  6559. // standard BufferGeometry serialization
  6560. data.uuid = this.uuid;
  6561. data.type = this.type;
  6562. if ( this.name !== '' ) data.name = this.name;
  6563. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6564. if ( this.parameters !== undefined ) {
  6565. const parameters = this.parameters;
  6566. for ( const key in parameters ) {
  6567. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6568. }
  6569. return data;
  6570. }
  6571. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6572. data.data = { attributes: {} };
  6573. const index = this.index;
  6574. if ( index !== null ) {
  6575. data.data.index = {
  6576. type: index.array.constructor.name,
  6577. array: Array.prototype.slice.call( index.array )
  6578. };
  6579. }
  6580. const attributes = this.attributes;
  6581. for ( const key in attributes ) {
  6582. const attribute = attributes[ key ];
  6583. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6584. }
  6585. const morphAttributes = {};
  6586. let hasMorphAttributes = false;
  6587. for ( const key in this.morphAttributes ) {
  6588. const attributeArray = this.morphAttributes[ key ];
  6589. const array = [];
  6590. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6591. const attribute = attributeArray[ i ];
  6592. array.push( attribute.toJSON( data.data ) );
  6593. }
  6594. if ( array.length > 0 ) {
  6595. morphAttributes[ key ] = array;
  6596. hasMorphAttributes = true;
  6597. }
  6598. }
  6599. if ( hasMorphAttributes ) {
  6600. data.data.morphAttributes = morphAttributes;
  6601. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6602. }
  6603. const groups = this.groups;
  6604. if ( groups.length > 0 ) {
  6605. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6606. }
  6607. const boundingSphere = this.boundingSphere;
  6608. if ( boundingSphere !== null ) {
  6609. data.data.boundingSphere = {
  6610. center: boundingSphere.center.toArray(),
  6611. radius: boundingSphere.radius
  6612. };
  6613. }
  6614. return data;
  6615. }
  6616. clone() {
  6617. return new this.constructor().copy( this );
  6618. }
  6619. copy( source ) {
  6620. // reset
  6621. this.index = null;
  6622. this.attributes = {};
  6623. this.morphAttributes = {};
  6624. this.groups = [];
  6625. this.boundingBox = null;
  6626. this.boundingSphere = null;
  6627. // used for storing cloned, shared data
  6628. const data = {};
  6629. // name
  6630. this.name = source.name;
  6631. // index
  6632. const index = source.index;
  6633. if ( index !== null ) {
  6634. this.setIndex( index.clone( data ) );
  6635. }
  6636. // attributes
  6637. const attributes = source.attributes;
  6638. for ( const name in attributes ) {
  6639. const attribute = attributes[ name ];
  6640. this.setAttribute( name, attribute.clone( data ) );
  6641. }
  6642. // morph attributes
  6643. const morphAttributes = source.morphAttributes;
  6644. for ( const name in morphAttributes ) {
  6645. const array = [];
  6646. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6647. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6648. array.push( morphAttribute[ i ].clone( data ) );
  6649. }
  6650. this.morphAttributes[ name ] = array;
  6651. }
  6652. this.morphTargetsRelative = source.morphTargetsRelative;
  6653. // groups
  6654. const groups = source.groups;
  6655. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6656. const group = groups[ i ];
  6657. this.addGroup( group.start, group.count, group.materialIndex );
  6658. }
  6659. // bounding box
  6660. const boundingBox = source.boundingBox;
  6661. if ( boundingBox !== null ) {
  6662. this.boundingBox = boundingBox.clone();
  6663. }
  6664. // bounding sphere
  6665. const boundingSphere = source.boundingSphere;
  6666. if ( boundingSphere !== null ) {
  6667. this.boundingSphere = boundingSphere.clone();
  6668. }
  6669. // draw range
  6670. this.drawRange.start = source.drawRange.start;
  6671. this.drawRange.count = source.drawRange.count;
  6672. // user data
  6673. this.userData = deepClone( source.userData );
  6674. return this;
  6675. }
  6676. dispose() {
  6677. this.dispatchEvent( { type: 'dispose' } );
  6678. }
  6679. }
  6680. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6681. const _ray$2 = /*@__PURE__*/ new Ray();
  6682. const _sphere$4 = /*@__PURE__*/ new Sphere();
  6683. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6684. const _vA$1 = /*@__PURE__*/ new Vector3();
  6685. const _vB$1 = /*@__PURE__*/ new Vector3();
  6686. const _vC$1 = /*@__PURE__*/ new Vector3();
  6687. const _tempA = /*@__PURE__*/ new Vector3();
  6688. const _morphA = /*@__PURE__*/ new Vector3();
  6689. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6690. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6691. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6692. const _normalA = /*@__PURE__*/ new Vector3();
  6693. const _normalB = /*@__PURE__*/ new Vector3();
  6694. const _normalC = /*@__PURE__*/ new Vector3();
  6695. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6696. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6697. class Mesh extends Object3D {
  6698. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6699. super();
  6700. this.isMesh = true;
  6701. this.type = 'Mesh';
  6702. this.geometry = geometry;
  6703. this.material = material;
  6704. this.updateMorphTargets();
  6705. }
  6706. copy( source, recursive ) {
  6707. super.copy( source, recursive );
  6708. if ( source.morphTargetInfluences !== undefined ) {
  6709. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6710. }
  6711. if ( source.morphTargetDictionary !== undefined ) {
  6712. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6713. }
  6714. this.material = source.material;
  6715. this.geometry = source.geometry;
  6716. return this;
  6717. }
  6718. updateMorphTargets() {
  6719. const geometry = this.geometry;
  6720. const morphAttributes = geometry.morphAttributes;
  6721. const keys = Object.keys( morphAttributes );
  6722. if ( keys.length > 0 ) {
  6723. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6724. if ( morphAttribute !== undefined ) {
  6725. this.morphTargetInfluences = [];
  6726. this.morphTargetDictionary = {};
  6727. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6728. const name = morphAttribute[ m ].name || String( m );
  6729. this.morphTargetInfluences.push( 0 );
  6730. this.morphTargetDictionary[ name ] = m;
  6731. }
  6732. }
  6733. }
  6734. }
  6735. getVertexPosition( index, target ) {
  6736. const geometry = this.geometry;
  6737. const position = geometry.attributes.position;
  6738. const morphPosition = geometry.morphAttributes.position;
  6739. const morphTargetsRelative = geometry.morphTargetsRelative;
  6740. target.fromBufferAttribute( position, index );
  6741. const morphInfluences = this.morphTargetInfluences;
  6742. if ( morphPosition && morphInfluences ) {
  6743. _morphA.set( 0, 0, 0 );
  6744. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6745. const influence = morphInfluences[ i ];
  6746. const morphAttribute = morphPosition[ i ];
  6747. if ( influence === 0 ) continue;
  6748. _tempA.fromBufferAttribute( morphAttribute, index );
  6749. if ( morphTargetsRelative ) {
  6750. _morphA.addScaledVector( _tempA, influence );
  6751. } else {
  6752. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6753. }
  6754. }
  6755. target.add( _morphA );
  6756. }
  6757. if ( this.isSkinnedMesh ) {
  6758. this.applyBoneTransform( index, target );
  6759. }
  6760. return target;
  6761. }
  6762. raycast( raycaster, intersects ) {
  6763. const geometry = this.geometry;
  6764. const material = this.material;
  6765. const matrixWorld = this.matrixWorld;
  6766. if ( material === undefined ) return;
  6767. // Checking boundingSphere distance to ray
  6768. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6769. _sphere$4.copy( geometry.boundingSphere );
  6770. _sphere$4.applyMatrix4( matrixWorld );
  6771. _ray$2.copy( raycaster.ray ).recast( raycaster.near );
  6772. if ( _sphere$4.containsPoint( _ray$2.origin ) === false ) {
  6773. if ( _ray$2.intersectSphere( _sphere$4, _sphereHitAt ) === null ) return;
  6774. if ( _ray$2.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6775. }
  6776. //
  6777. _inverseMatrix$2.copy( matrixWorld ).invert();
  6778. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6779. // Check boundingBox before continuing
  6780. if ( geometry.boundingBox !== null ) {
  6781. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6782. }
  6783. let intersection;
  6784. const index = geometry.index;
  6785. const position = geometry.attributes.position;
  6786. const uv = geometry.attributes.uv;
  6787. const uv2 = geometry.attributes.uv2;
  6788. const normal = geometry.attributes.normal;
  6789. const groups = geometry.groups;
  6790. const drawRange = geometry.drawRange;
  6791. if ( index !== null ) {
  6792. // indexed buffer geometry
  6793. if ( Array.isArray( material ) ) {
  6794. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6795. const group = groups[ i ];
  6796. const groupMaterial = material[ group.materialIndex ];
  6797. const start = Math.max( group.start, drawRange.start );
  6798. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6799. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6800. const a = index.getX( j );
  6801. const b = index.getX( j + 1 );
  6802. const c = index.getX( j + 2 );
  6803. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, normal, a, b, c );
  6804. if ( intersection ) {
  6805. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6806. intersection.face.materialIndex = group.materialIndex;
  6807. intersects.push( intersection );
  6808. }
  6809. }
  6810. }
  6811. } else {
  6812. const start = Math.max( 0, drawRange.start );
  6813. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6814. for ( let i = start, il = end; i < il; i += 3 ) {
  6815. const a = index.getX( i );
  6816. const b = index.getX( i + 1 );
  6817. const c = index.getX( i + 2 );
  6818. intersection = checkGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, normal, a, b, c );
  6819. if ( intersection ) {
  6820. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6821. intersects.push( intersection );
  6822. }
  6823. }
  6824. }
  6825. } else if ( position !== undefined ) {
  6826. // non-indexed buffer geometry
  6827. if ( Array.isArray( material ) ) {
  6828. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6829. const group = groups[ i ];
  6830. const groupMaterial = material[ group.materialIndex ];
  6831. const start = Math.max( group.start, drawRange.start );
  6832. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6833. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6834. const a = j;
  6835. const b = j + 1;
  6836. const c = j + 2;
  6837. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, normal, a, b, c );
  6838. if ( intersection ) {
  6839. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6840. intersection.face.materialIndex = group.materialIndex;
  6841. intersects.push( intersection );
  6842. }
  6843. }
  6844. }
  6845. } else {
  6846. const start = Math.max( 0, drawRange.start );
  6847. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6848. for ( let i = start, il = end; i < il; i += 3 ) {
  6849. const a = i;
  6850. const b = i + 1;
  6851. const c = i + 2;
  6852. intersection = checkGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, normal, a, b, c );
  6853. if ( intersection ) {
  6854. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6855. intersects.push( intersection );
  6856. }
  6857. }
  6858. }
  6859. }
  6860. }
  6861. }
  6862. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6863. let intersect;
  6864. if ( material.side === BackSide ) {
  6865. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6866. } else {
  6867. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6868. }
  6869. if ( intersect === null ) return null;
  6870. _intersectionPointWorld.copy( point );
  6871. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6872. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6873. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6874. return {
  6875. distance: distance,
  6876. point: _intersectionPointWorld.clone(),
  6877. object: object
  6878. };
  6879. }
  6880. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv2, normal, a, b, c ) {
  6881. object.getVertexPosition( a, _vA$1 );
  6882. object.getVertexPosition( b, _vB$1 );
  6883. object.getVertexPosition( c, _vC$1 );
  6884. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6885. if ( intersection ) {
  6886. if ( uv ) {
  6887. _uvA$1.fromBufferAttribute( uv, a );
  6888. _uvB$1.fromBufferAttribute( uv, b );
  6889. _uvC$1.fromBufferAttribute( uv, c );
  6890. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6891. }
  6892. if ( uv2 ) {
  6893. _uvA$1.fromBufferAttribute( uv2, a );
  6894. _uvB$1.fromBufferAttribute( uv2, b );
  6895. _uvC$1.fromBufferAttribute( uv2, c );
  6896. intersection.uv2 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6897. }
  6898. if ( normal ) {
  6899. _normalA.fromBufferAttribute( normal, a );
  6900. _normalB.fromBufferAttribute( normal, b );
  6901. _normalC.fromBufferAttribute( normal, c );
  6902. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  6903. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  6904. intersection.normal.multiplyScalar( - 1 );
  6905. }
  6906. }
  6907. const face = {
  6908. a: a,
  6909. b: b,
  6910. c: c,
  6911. normal: new Vector3(),
  6912. materialIndex: 0
  6913. };
  6914. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6915. intersection.face = face;
  6916. }
  6917. return intersection;
  6918. }
  6919. class BoxGeometry extends BufferGeometry {
  6920. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6921. super();
  6922. this.type = 'BoxGeometry';
  6923. this.parameters = {
  6924. width: width,
  6925. height: height,
  6926. depth: depth,
  6927. widthSegments: widthSegments,
  6928. heightSegments: heightSegments,
  6929. depthSegments: depthSegments
  6930. };
  6931. const scope = this;
  6932. // segments
  6933. widthSegments = Math.floor( widthSegments );
  6934. heightSegments = Math.floor( heightSegments );
  6935. depthSegments = Math.floor( depthSegments );
  6936. // buffers
  6937. const indices = [];
  6938. const vertices = [];
  6939. const normals = [];
  6940. const uvs = [];
  6941. // helper variables
  6942. let numberOfVertices = 0;
  6943. let groupStart = 0;
  6944. // build each side of the box geometry
  6945. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6946. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6947. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6948. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6949. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6950. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6951. // build geometry
  6952. this.setIndex( indices );
  6953. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6954. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6955. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6956. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6957. const segmentWidth = width / gridX;
  6958. const segmentHeight = height / gridY;
  6959. const widthHalf = width / 2;
  6960. const heightHalf = height / 2;
  6961. const depthHalf = depth / 2;
  6962. const gridX1 = gridX + 1;
  6963. const gridY1 = gridY + 1;
  6964. let vertexCounter = 0;
  6965. let groupCount = 0;
  6966. const vector = new Vector3();
  6967. // generate vertices, normals and uvs
  6968. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6969. const y = iy * segmentHeight - heightHalf;
  6970. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6971. const x = ix * segmentWidth - widthHalf;
  6972. // set values to correct vector component
  6973. vector[ u ] = x * udir;
  6974. vector[ v ] = y * vdir;
  6975. vector[ w ] = depthHalf;
  6976. // now apply vector to vertex buffer
  6977. vertices.push( vector.x, vector.y, vector.z );
  6978. // set values to correct vector component
  6979. vector[ u ] = 0;
  6980. vector[ v ] = 0;
  6981. vector[ w ] = depth > 0 ? 1 : - 1;
  6982. // now apply vector to normal buffer
  6983. normals.push( vector.x, vector.y, vector.z );
  6984. // uvs
  6985. uvs.push( ix / gridX );
  6986. uvs.push( 1 - ( iy / gridY ) );
  6987. // counters
  6988. vertexCounter += 1;
  6989. }
  6990. }
  6991. // indices
  6992. // 1. you need three indices to draw a single face
  6993. // 2. a single segment consists of two faces
  6994. // 3. so we need to generate six (2*3) indices per segment
  6995. for ( let iy = 0; iy < gridY; iy ++ ) {
  6996. for ( let ix = 0; ix < gridX; ix ++ ) {
  6997. const a = numberOfVertices + ix + gridX1 * iy;
  6998. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6999. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7000. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7001. // faces
  7002. indices.push( a, b, d );
  7003. indices.push( b, c, d );
  7004. // increase counter
  7005. groupCount += 6;
  7006. }
  7007. }
  7008. // add a group to the geometry. this will ensure multi material support
  7009. scope.addGroup( groupStart, groupCount, materialIndex );
  7010. // calculate new start value for groups
  7011. groupStart += groupCount;
  7012. // update total number of vertices
  7013. numberOfVertices += vertexCounter;
  7014. }
  7015. }
  7016. copy( source ) {
  7017. super.copy( source );
  7018. this.parameters = Object.assign( {}, source.parameters );
  7019. return this;
  7020. }
  7021. static fromJSON( data ) {
  7022. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7023. }
  7024. }
  7025. /**
  7026. * Uniform Utilities
  7027. */
  7028. function cloneUniforms( src ) {
  7029. const dst = {};
  7030. for ( const u in src ) {
  7031. dst[ u ] = {};
  7032. for ( const p in src[ u ] ) {
  7033. const property = src[ u ][ p ];
  7034. if ( property && ( property.isColor ||
  7035. property.isMatrix3 || property.isMatrix4 ||
  7036. property.isVector2 || property.isVector3 || property.isVector4 ||
  7037. property.isTexture || property.isQuaternion ) ) {
  7038. if ( property.isRenderTargetTexture ) {
  7039. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7040. dst[ u ][ p ] = null;
  7041. } else {
  7042. dst[ u ][ p ] = property.clone();
  7043. }
  7044. } else if ( Array.isArray( property ) ) {
  7045. dst[ u ][ p ] = property.slice();
  7046. } else {
  7047. dst[ u ][ p ] = property;
  7048. }
  7049. }
  7050. }
  7051. return dst;
  7052. }
  7053. function mergeUniforms( uniforms ) {
  7054. const merged = {};
  7055. for ( let u = 0; u < uniforms.length; u ++ ) {
  7056. const tmp = cloneUniforms( uniforms[ u ] );
  7057. for ( const p in tmp ) {
  7058. merged[ p ] = tmp[ p ];
  7059. }
  7060. }
  7061. return merged;
  7062. }
  7063. function cloneUniformsGroups( src ) {
  7064. const dst = [];
  7065. for ( let u = 0; u < src.length; u ++ ) {
  7066. dst.push( src[ u ].clone() );
  7067. }
  7068. return dst;
  7069. }
  7070. function getUnlitUniformColorSpace( renderer ) {
  7071. if ( renderer.getRenderTarget() === null ) {
  7072. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7073. return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  7074. }
  7075. return LinearSRGBColorSpace;
  7076. }
  7077. // Legacy
  7078. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7079. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7080. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7081. class ShaderMaterial extends Material {
  7082. constructor( parameters ) {
  7083. super();
  7084. this.isShaderMaterial = true;
  7085. this.type = 'ShaderMaterial';
  7086. this.defines = {};
  7087. this.uniforms = {};
  7088. this.uniformsGroups = [];
  7089. this.vertexShader = default_vertex;
  7090. this.fragmentShader = default_fragment;
  7091. this.linewidth = 1;
  7092. this.wireframe = false;
  7093. this.wireframeLinewidth = 1;
  7094. this.fog = false; // set to use scene fog
  7095. this.lights = false; // set to use scene lights
  7096. this.clipping = false; // set to use user-defined clipping planes
  7097. this.forceSinglePass = true;
  7098. this.extensions = {
  7099. derivatives: false, // set to use derivatives
  7100. fragDepth: false, // set to use fragment depth values
  7101. drawBuffers: false, // set to use draw buffers
  7102. shaderTextureLOD: false // set to use shader texture LOD
  7103. };
  7104. // When rendered geometry doesn't include these attributes but the material does,
  7105. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7106. this.defaultAttributeValues = {
  7107. 'color': [ 1, 1, 1 ],
  7108. 'uv': [ 0, 0 ],
  7109. 'uv2': [ 0, 0 ]
  7110. };
  7111. this.index0AttributeName = undefined;
  7112. this.uniformsNeedUpdate = false;
  7113. this.glslVersion = null;
  7114. if ( parameters !== undefined ) {
  7115. this.setValues( parameters );
  7116. }
  7117. }
  7118. copy( source ) {
  7119. super.copy( source );
  7120. this.fragmentShader = source.fragmentShader;
  7121. this.vertexShader = source.vertexShader;
  7122. this.uniforms = cloneUniforms( source.uniforms );
  7123. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7124. this.defines = Object.assign( {}, source.defines );
  7125. this.wireframe = source.wireframe;
  7126. this.wireframeLinewidth = source.wireframeLinewidth;
  7127. this.fog = source.fog;
  7128. this.lights = source.lights;
  7129. this.clipping = source.clipping;
  7130. this.extensions = Object.assign( {}, source.extensions );
  7131. this.glslVersion = source.glslVersion;
  7132. return this;
  7133. }
  7134. toJSON( meta ) {
  7135. const data = super.toJSON( meta );
  7136. data.glslVersion = this.glslVersion;
  7137. data.uniforms = {};
  7138. for ( const name in this.uniforms ) {
  7139. const uniform = this.uniforms[ name ];
  7140. const value = uniform.value;
  7141. if ( value && value.isTexture ) {
  7142. data.uniforms[ name ] = {
  7143. type: 't',
  7144. value: value.toJSON( meta ).uuid
  7145. };
  7146. } else if ( value && value.isColor ) {
  7147. data.uniforms[ name ] = {
  7148. type: 'c',
  7149. value: value.getHex()
  7150. };
  7151. } else if ( value && value.isVector2 ) {
  7152. data.uniforms[ name ] = {
  7153. type: 'v2',
  7154. value: value.toArray()
  7155. };
  7156. } else if ( value && value.isVector3 ) {
  7157. data.uniforms[ name ] = {
  7158. type: 'v3',
  7159. value: value.toArray()
  7160. };
  7161. } else if ( value && value.isVector4 ) {
  7162. data.uniforms[ name ] = {
  7163. type: 'v4',
  7164. value: value.toArray()
  7165. };
  7166. } else if ( value && value.isMatrix3 ) {
  7167. data.uniforms[ name ] = {
  7168. type: 'm3',
  7169. value: value.toArray()
  7170. };
  7171. } else if ( value && value.isMatrix4 ) {
  7172. data.uniforms[ name ] = {
  7173. type: 'm4',
  7174. value: value.toArray()
  7175. };
  7176. } else {
  7177. data.uniforms[ name ] = {
  7178. value: value
  7179. };
  7180. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7181. }
  7182. }
  7183. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7184. data.vertexShader = this.vertexShader;
  7185. data.fragmentShader = this.fragmentShader;
  7186. const extensions = {};
  7187. for ( const key in this.extensions ) {
  7188. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7189. }
  7190. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7191. return data;
  7192. }
  7193. }
  7194. class Camera extends Object3D {
  7195. constructor() {
  7196. super();
  7197. this.isCamera = true;
  7198. this.type = 'Camera';
  7199. this.matrixWorldInverse = new Matrix4();
  7200. this.projectionMatrix = new Matrix4();
  7201. this.projectionMatrixInverse = new Matrix4();
  7202. }
  7203. copy( source, recursive ) {
  7204. super.copy( source, recursive );
  7205. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7206. this.projectionMatrix.copy( source.projectionMatrix );
  7207. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7208. return this;
  7209. }
  7210. getWorldDirection( target ) {
  7211. this.updateWorldMatrix( true, false );
  7212. const e = this.matrixWorld.elements;
  7213. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7214. }
  7215. updateMatrixWorld( force ) {
  7216. super.updateMatrixWorld( force );
  7217. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7218. }
  7219. updateWorldMatrix( updateParents, updateChildren ) {
  7220. super.updateWorldMatrix( updateParents, updateChildren );
  7221. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7222. }
  7223. clone() {
  7224. return new this.constructor().copy( this );
  7225. }
  7226. }
  7227. class PerspectiveCamera extends Camera {
  7228. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7229. super();
  7230. this.isPerspectiveCamera = true;
  7231. this.type = 'PerspectiveCamera';
  7232. this.fov = fov;
  7233. this.zoom = 1;
  7234. this.near = near;
  7235. this.far = far;
  7236. this.focus = 10;
  7237. this.aspect = aspect;
  7238. this.view = null;
  7239. this.filmGauge = 35; // width of the film (default in millimeters)
  7240. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7241. this.updateProjectionMatrix();
  7242. }
  7243. copy( source, recursive ) {
  7244. super.copy( source, recursive );
  7245. this.fov = source.fov;
  7246. this.zoom = source.zoom;
  7247. this.near = source.near;
  7248. this.far = source.far;
  7249. this.focus = source.focus;
  7250. this.aspect = source.aspect;
  7251. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7252. this.filmGauge = source.filmGauge;
  7253. this.filmOffset = source.filmOffset;
  7254. return this;
  7255. }
  7256. /**
  7257. * Sets the FOV by focal length in respect to the current .filmGauge.
  7258. *
  7259. * The default film gauge is 35, so that the focal length can be specified for
  7260. * a 35mm (full frame) camera.
  7261. *
  7262. * Values for focal length and film gauge must have the same unit.
  7263. */
  7264. setFocalLength( focalLength ) {
  7265. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7266. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7267. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7268. this.updateProjectionMatrix();
  7269. }
  7270. /**
  7271. * Calculates the focal length from the current .fov and .filmGauge.
  7272. */
  7273. getFocalLength() {
  7274. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7275. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7276. }
  7277. getEffectiveFOV() {
  7278. return RAD2DEG * 2 * Math.atan(
  7279. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7280. }
  7281. getFilmWidth() {
  7282. // film not completely covered in portrait format (aspect < 1)
  7283. return this.filmGauge * Math.min( this.aspect, 1 );
  7284. }
  7285. getFilmHeight() {
  7286. // film not completely covered in landscape format (aspect > 1)
  7287. return this.filmGauge / Math.max( this.aspect, 1 );
  7288. }
  7289. /**
  7290. * Sets an offset in a larger frustum. This is useful for multi-window or
  7291. * multi-monitor/multi-machine setups.
  7292. *
  7293. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7294. * the monitors are in grid like this
  7295. *
  7296. * +---+---+---+
  7297. * | A | B | C |
  7298. * +---+---+---+
  7299. * | D | E | F |
  7300. * +---+---+---+
  7301. *
  7302. * then for each monitor you would call it like this
  7303. *
  7304. * const w = 1920;
  7305. * const h = 1080;
  7306. * const fullWidth = w * 3;
  7307. * const fullHeight = h * 2;
  7308. *
  7309. * --A--
  7310. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7311. * --B--
  7312. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7313. * --C--
  7314. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7315. * --D--
  7316. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7317. * --E--
  7318. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7319. * --F--
  7320. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7321. *
  7322. * Note there is no reason monitors have to be the same size or in a grid.
  7323. */
  7324. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7325. this.aspect = fullWidth / fullHeight;
  7326. if ( this.view === null ) {
  7327. this.view = {
  7328. enabled: true,
  7329. fullWidth: 1,
  7330. fullHeight: 1,
  7331. offsetX: 0,
  7332. offsetY: 0,
  7333. width: 1,
  7334. height: 1
  7335. };
  7336. }
  7337. this.view.enabled = true;
  7338. this.view.fullWidth = fullWidth;
  7339. this.view.fullHeight = fullHeight;
  7340. this.view.offsetX = x;
  7341. this.view.offsetY = y;
  7342. this.view.width = width;
  7343. this.view.height = height;
  7344. this.updateProjectionMatrix();
  7345. }
  7346. clearViewOffset() {
  7347. if ( this.view !== null ) {
  7348. this.view.enabled = false;
  7349. }
  7350. this.updateProjectionMatrix();
  7351. }
  7352. updateProjectionMatrix() {
  7353. const near = this.near;
  7354. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7355. let height = 2 * top;
  7356. let width = this.aspect * height;
  7357. let left = - 0.5 * width;
  7358. const view = this.view;
  7359. if ( this.view !== null && this.view.enabled ) {
  7360. const fullWidth = view.fullWidth,
  7361. fullHeight = view.fullHeight;
  7362. left += view.offsetX * width / fullWidth;
  7363. top -= view.offsetY * height / fullHeight;
  7364. width *= view.width / fullWidth;
  7365. height *= view.height / fullHeight;
  7366. }
  7367. const skew = this.filmOffset;
  7368. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7369. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7370. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7371. }
  7372. toJSON( meta ) {
  7373. const data = super.toJSON( meta );
  7374. data.object.fov = this.fov;
  7375. data.object.zoom = this.zoom;
  7376. data.object.near = this.near;
  7377. data.object.far = this.far;
  7378. data.object.focus = this.focus;
  7379. data.object.aspect = this.aspect;
  7380. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7381. data.object.filmGauge = this.filmGauge;
  7382. data.object.filmOffset = this.filmOffset;
  7383. return data;
  7384. }
  7385. }
  7386. const fov = - 90; // negative fov is not an error
  7387. const aspect = 1;
  7388. class CubeCamera extends Object3D {
  7389. constructor( near, far, renderTarget ) {
  7390. super();
  7391. this.type = 'CubeCamera';
  7392. this.renderTarget = renderTarget;
  7393. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7394. cameraPX.layers = this.layers;
  7395. cameraPX.up.set( 0, 1, 0 );
  7396. cameraPX.lookAt( 1, 0, 0 );
  7397. this.add( cameraPX );
  7398. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7399. cameraNX.layers = this.layers;
  7400. cameraNX.up.set( 0, 1, 0 );
  7401. cameraNX.lookAt( - 1, 0, 0 );
  7402. this.add( cameraNX );
  7403. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7404. cameraPY.layers = this.layers;
  7405. cameraPY.up.set( 0, 0, - 1 );
  7406. cameraPY.lookAt( 0, 1, 0 );
  7407. this.add( cameraPY );
  7408. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7409. cameraNY.layers = this.layers;
  7410. cameraNY.up.set( 0, 0, 1 );
  7411. cameraNY.lookAt( 0, - 1, 0 );
  7412. this.add( cameraNY );
  7413. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7414. cameraPZ.layers = this.layers;
  7415. cameraPZ.up.set( 0, 1, 0 );
  7416. cameraPZ.lookAt( 0, 0, 1 );
  7417. this.add( cameraPZ );
  7418. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7419. cameraNZ.layers = this.layers;
  7420. cameraNZ.up.set( 0, 1, 0 );
  7421. cameraNZ.lookAt( 0, 0, - 1 );
  7422. this.add( cameraNZ );
  7423. }
  7424. update( renderer, scene ) {
  7425. if ( this.parent === null ) this.updateMatrixWorld();
  7426. const renderTarget = this.renderTarget;
  7427. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7428. const currentRenderTarget = renderer.getRenderTarget();
  7429. const currentToneMapping = renderer.toneMapping;
  7430. const currentXrEnabled = renderer.xr.enabled;
  7431. renderer.toneMapping = NoToneMapping;
  7432. renderer.xr.enabled = false;
  7433. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7434. renderTarget.texture.generateMipmaps = false;
  7435. renderer.setRenderTarget( renderTarget, 0 );
  7436. renderer.render( scene, cameraPX );
  7437. renderer.setRenderTarget( renderTarget, 1 );
  7438. renderer.render( scene, cameraNX );
  7439. renderer.setRenderTarget( renderTarget, 2 );
  7440. renderer.render( scene, cameraPY );
  7441. renderer.setRenderTarget( renderTarget, 3 );
  7442. renderer.render( scene, cameraNY );
  7443. renderer.setRenderTarget( renderTarget, 4 );
  7444. renderer.render( scene, cameraPZ );
  7445. renderTarget.texture.generateMipmaps = generateMipmaps;
  7446. renderer.setRenderTarget( renderTarget, 5 );
  7447. renderer.render( scene, cameraNZ );
  7448. renderer.setRenderTarget( currentRenderTarget );
  7449. renderer.toneMapping = currentToneMapping;
  7450. renderer.xr.enabled = currentXrEnabled;
  7451. renderTarget.texture.needsPMREMUpdate = true;
  7452. }
  7453. }
  7454. class CubeTexture extends Texture {
  7455. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7456. images = images !== undefined ? images : [];
  7457. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7458. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7459. this.isCubeTexture = true;
  7460. this.flipY = false;
  7461. }
  7462. get images() {
  7463. return this.image;
  7464. }
  7465. set images( value ) {
  7466. this.image = value;
  7467. }
  7468. }
  7469. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7470. constructor( size = 1, options = {} ) {
  7471. super( size, size, options );
  7472. this.isWebGLCubeRenderTarget = true;
  7473. const image = { width: size, height: size, depth: 1 };
  7474. const images = [ image, image, image, image, image, image ];
  7475. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7476. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7477. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7478. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7479. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7480. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7481. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7482. this.texture.isRenderTargetTexture = true;
  7483. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7484. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7485. }
  7486. fromEquirectangularTexture( renderer, texture ) {
  7487. this.texture.type = texture.type;
  7488. this.texture.encoding = texture.encoding;
  7489. this.texture.generateMipmaps = texture.generateMipmaps;
  7490. this.texture.minFilter = texture.minFilter;
  7491. this.texture.magFilter = texture.magFilter;
  7492. const shader = {
  7493. uniforms: {
  7494. tEquirect: { value: null },
  7495. },
  7496. vertexShader: /* glsl */`
  7497. varying vec3 vWorldDirection;
  7498. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7499. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7500. }
  7501. void main() {
  7502. vWorldDirection = transformDirection( position, modelMatrix );
  7503. #include <begin_vertex>
  7504. #include <project_vertex>
  7505. }
  7506. `,
  7507. fragmentShader: /* glsl */`
  7508. uniform sampler2D tEquirect;
  7509. varying vec3 vWorldDirection;
  7510. #include <common>
  7511. void main() {
  7512. vec3 direction = normalize( vWorldDirection );
  7513. vec2 sampleUV = equirectUv( direction );
  7514. gl_FragColor = texture2D( tEquirect, sampleUV );
  7515. }
  7516. `
  7517. };
  7518. const geometry = new BoxGeometry( 5, 5, 5 );
  7519. const material = new ShaderMaterial( {
  7520. name: 'CubemapFromEquirect',
  7521. uniforms: cloneUniforms( shader.uniforms ),
  7522. vertexShader: shader.vertexShader,
  7523. fragmentShader: shader.fragmentShader,
  7524. side: BackSide,
  7525. blending: NoBlending
  7526. } );
  7527. material.uniforms.tEquirect.value = texture;
  7528. const mesh = new Mesh( geometry, material );
  7529. const currentMinFilter = texture.minFilter;
  7530. // Avoid blurred poles
  7531. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7532. const camera = new CubeCamera( 1, 10, this );
  7533. camera.update( renderer, mesh );
  7534. texture.minFilter = currentMinFilter;
  7535. mesh.geometry.dispose();
  7536. mesh.material.dispose();
  7537. return this;
  7538. }
  7539. clear( renderer, color, depth, stencil ) {
  7540. const currentRenderTarget = renderer.getRenderTarget();
  7541. for ( let i = 0; i < 6; i ++ ) {
  7542. renderer.setRenderTarget( this, i );
  7543. renderer.clear( color, depth, stencil );
  7544. }
  7545. renderer.setRenderTarget( currentRenderTarget );
  7546. }
  7547. }
  7548. const _vector1 = /*@__PURE__*/ new Vector3();
  7549. const _vector2 = /*@__PURE__*/ new Vector3();
  7550. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7551. class Plane {
  7552. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7553. this.isPlane = true;
  7554. // normal is assumed to be normalized
  7555. this.normal = normal;
  7556. this.constant = constant;
  7557. }
  7558. set( normal, constant ) {
  7559. this.normal.copy( normal );
  7560. this.constant = constant;
  7561. return this;
  7562. }
  7563. setComponents( x, y, z, w ) {
  7564. this.normal.set( x, y, z );
  7565. this.constant = w;
  7566. return this;
  7567. }
  7568. setFromNormalAndCoplanarPoint( normal, point ) {
  7569. this.normal.copy( normal );
  7570. this.constant = - point.dot( this.normal );
  7571. return this;
  7572. }
  7573. setFromCoplanarPoints( a, b, c ) {
  7574. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7575. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7576. this.setFromNormalAndCoplanarPoint( normal, a );
  7577. return this;
  7578. }
  7579. copy( plane ) {
  7580. this.normal.copy( plane.normal );
  7581. this.constant = plane.constant;
  7582. return this;
  7583. }
  7584. normalize() {
  7585. // Note: will lead to a divide by zero if the plane is invalid.
  7586. const inverseNormalLength = 1.0 / this.normal.length();
  7587. this.normal.multiplyScalar( inverseNormalLength );
  7588. this.constant *= inverseNormalLength;
  7589. return this;
  7590. }
  7591. negate() {
  7592. this.constant *= - 1;
  7593. this.normal.negate();
  7594. return this;
  7595. }
  7596. distanceToPoint( point ) {
  7597. return this.normal.dot( point ) + this.constant;
  7598. }
  7599. distanceToSphere( sphere ) {
  7600. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7601. }
  7602. projectPoint( point, target ) {
  7603. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7604. }
  7605. intersectLine( line, target ) {
  7606. const direction = line.delta( _vector1 );
  7607. const denominator = this.normal.dot( direction );
  7608. if ( denominator === 0 ) {
  7609. // line is coplanar, return origin
  7610. if ( this.distanceToPoint( line.start ) === 0 ) {
  7611. return target.copy( line.start );
  7612. }
  7613. // Unsure if this is the correct method to handle this case.
  7614. return null;
  7615. }
  7616. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7617. if ( t < 0 || t > 1 ) {
  7618. return null;
  7619. }
  7620. return target.copy( line.start ).addScaledVector( direction, t );
  7621. }
  7622. intersectsLine( line ) {
  7623. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7624. const startSign = this.distanceToPoint( line.start );
  7625. const endSign = this.distanceToPoint( line.end );
  7626. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7627. }
  7628. intersectsBox( box ) {
  7629. return box.intersectsPlane( this );
  7630. }
  7631. intersectsSphere( sphere ) {
  7632. return sphere.intersectsPlane( this );
  7633. }
  7634. coplanarPoint( target ) {
  7635. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7636. }
  7637. applyMatrix4( matrix, optionalNormalMatrix ) {
  7638. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7639. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7640. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7641. this.constant = - referencePoint.dot( normal );
  7642. return this;
  7643. }
  7644. translate( offset ) {
  7645. this.constant -= offset.dot( this.normal );
  7646. return this;
  7647. }
  7648. equals( plane ) {
  7649. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7650. }
  7651. clone() {
  7652. return new this.constructor().copy( this );
  7653. }
  7654. }
  7655. const _sphere$3 = /*@__PURE__*/ new Sphere();
  7656. const _vector$6 = /*@__PURE__*/ new Vector3();
  7657. class Frustum {
  7658. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7659. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7660. }
  7661. set( p0, p1, p2, p3, p4, p5 ) {
  7662. const planes = this.planes;
  7663. planes[ 0 ].copy( p0 );
  7664. planes[ 1 ].copy( p1 );
  7665. planes[ 2 ].copy( p2 );
  7666. planes[ 3 ].copy( p3 );
  7667. planes[ 4 ].copy( p4 );
  7668. planes[ 5 ].copy( p5 );
  7669. return this;
  7670. }
  7671. copy( frustum ) {
  7672. const planes = this.planes;
  7673. for ( let i = 0; i < 6; i ++ ) {
  7674. planes[ i ].copy( frustum.planes[ i ] );
  7675. }
  7676. return this;
  7677. }
  7678. setFromProjectionMatrix( m ) {
  7679. const planes = this.planes;
  7680. const me = m.elements;
  7681. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7682. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7683. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7684. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7685. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7686. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7687. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7688. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7689. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7690. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7691. return this;
  7692. }
  7693. intersectsObject( object ) {
  7694. if ( object.boundingSphere !== undefined ) {
  7695. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7696. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7697. } else {
  7698. const geometry = object.geometry;
  7699. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7700. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7701. }
  7702. return this.intersectsSphere( _sphere$3 );
  7703. }
  7704. intersectsSprite( sprite ) {
  7705. _sphere$3.center.set( 0, 0, 0 );
  7706. _sphere$3.radius = 0.7071067811865476;
  7707. _sphere$3.applyMatrix4( sprite.matrixWorld );
  7708. return this.intersectsSphere( _sphere$3 );
  7709. }
  7710. intersectsSphere( sphere ) {
  7711. const planes = this.planes;
  7712. const center = sphere.center;
  7713. const negRadius = - sphere.radius;
  7714. for ( let i = 0; i < 6; i ++ ) {
  7715. const distance = planes[ i ].distanceToPoint( center );
  7716. if ( distance < negRadius ) {
  7717. return false;
  7718. }
  7719. }
  7720. return true;
  7721. }
  7722. intersectsBox( box ) {
  7723. const planes = this.planes;
  7724. for ( let i = 0; i < 6; i ++ ) {
  7725. const plane = planes[ i ];
  7726. // corner at max distance
  7727. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7728. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7729. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7730. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  7731. return false;
  7732. }
  7733. }
  7734. return true;
  7735. }
  7736. containsPoint( point ) {
  7737. const planes = this.planes;
  7738. for ( let i = 0; i < 6; i ++ ) {
  7739. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7740. return false;
  7741. }
  7742. }
  7743. return true;
  7744. }
  7745. clone() {
  7746. return new this.constructor().copy( this );
  7747. }
  7748. }
  7749. function WebGLAnimation() {
  7750. let context = null;
  7751. let isAnimating = false;
  7752. let animationLoop = null;
  7753. let requestId = null;
  7754. function onAnimationFrame( time, frame ) {
  7755. animationLoop( time, frame );
  7756. requestId = context.requestAnimationFrame( onAnimationFrame );
  7757. }
  7758. return {
  7759. start: function () {
  7760. if ( isAnimating === true ) return;
  7761. if ( animationLoop === null ) return;
  7762. requestId = context.requestAnimationFrame( onAnimationFrame );
  7763. isAnimating = true;
  7764. },
  7765. stop: function () {
  7766. context.cancelAnimationFrame( requestId );
  7767. isAnimating = false;
  7768. },
  7769. setAnimationLoop: function ( callback ) {
  7770. animationLoop = callback;
  7771. },
  7772. setContext: function ( value ) {
  7773. context = value;
  7774. }
  7775. };
  7776. }
  7777. function WebGLAttributes( gl, capabilities ) {
  7778. const isWebGL2 = capabilities.isWebGL2;
  7779. const buffers = new WeakMap();
  7780. function createBuffer( attribute, bufferType ) {
  7781. const array = attribute.array;
  7782. const usage = attribute.usage;
  7783. const buffer = gl.createBuffer();
  7784. gl.bindBuffer( bufferType, buffer );
  7785. gl.bufferData( bufferType, array, usage );
  7786. attribute.onUploadCallback();
  7787. let type;
  7788. if ( array instanceof Float32Array ) {
  7789. type = 5126;
  7790. } else if ( array instanceof Uint16Array ) {
  7791. if ( attribute.isFloat16BufferAttribute ) {
  7792. if ( isWebGL2 ) {
  7793. type = 5131;
  7794. } else {
  7795. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7796. }
  7797. } else {
  7798. type = 5123;
  7799. }
  7800. } else if ( array instanceof Int16Array ) {
  7801. type = 5122;
  7802. } else if ( array instanceof Uint32Array ) {
  7803. type = 5125;
  7804. } else if ( array instanceof Int32Array ) {
  7805. type = 5124;
  7806. } else if ( array instanceof Int8Array ) {
  7807. type = 5120;
  7808. } else if ( array instanceof Uint8Array ) {
  7809. type = 5121;
  7810. } else if ( array instanceof Uint8ClampedArray ) {
  7811. type = 5121;
  7812. } else {
  7813. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7814. }
  7815. return {
  7816. buffer: buffer,
  7817. type: type,
  7818. bytesPerElement: array.BYTES_PER_ELEMENT,
  7819. version: attribute.version
  7820. };
  7821. }
  7822. function updateBuffer( buffer, attribute, bufferType ) {
  7823. const array = attribute.array;
  7824. const updateRange = attribute.updateRange;
  7825. gl.bindBuffer( bufferType, buffer );
  7826. if ( updateRange.count === - 1 ) {
  7827. // Not using update ranges
  7828. gl.bufferSubData( bufferType, 0, array );
  7829. } else {
  7830. if ( isWebGL2 ) {
  7831. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7832. array, updateRange.offset, updateRange.count );
  7833. } else {
  7834. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7835. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7836. }
  7837. updateRange.count = - 1; // reset range
  7838. }
  7839. attribute.onUploadCallback();
  7840. }
  7841. //
  7842. function get( attribute ) {
  7843. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7844. return buffers.get( attribute );
  7845. }
  7846. function remove( attribute ) {
  7847. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7848. const data = buffers.get( attribute );
  7849. if ( data ) {
  7850. gl.deleteBuffer( data.buffer );
  7851. buffers.delete( attribute );
  7852. }
  7853. }
  7854. function update( attribute, bufferType ) {
  7855. if ( attribute.isGLBufferAttribute ) {
  7856. const cached = buffers.get( attribute );
  7857. if ( ! cached || cached.version < attribute.version ) {
  7858. buffers.set( attribute, {
  7859. buffer: attribute.buffer,
  7860. type: attribute.type,
  7861. bytesPerElement: attribute.elementSize,
  7862. version: attribute.version
  7863. } );
  7864. }
  7865. return;
  7866. }
  7867. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7868. const data = buffers.get( attribute );
  7869. if ( data === undefined ) {
  7870. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7871. } else if ( data.version < attribute.version ) {
  7872. updateBuffer( data.buffer, attribute, bufferType );
  7873. data.version = attribute.version;
  7874. }
  7875. }
  7876. return {
  7877. get: get,
  7878. remove: remove,
  7879. update: update
  7880. };
  7881. }
  7882. class PlaneGeometry extends BufferGeometry {
  7883. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7884. super();
  7885. this.type = 'PlaneGeometry';
  7886. this.parameters = {
  7887. width: width,
  7888. height: height,
  7889. widthSegments: widthSegments,
  7890. heightSegments: heightSegments
  7891. };
  7892. const width_half = width / 2;
  7893. const height_half = height / 2;
  7894. const gridX = Math.floor( widthSegments );
  7895. const gridY = Math.floor( heightSegments );
  7896. const gridX1 = gridX + 1;
  7897. const gridY1 = gridY + 1;
  7898. const segment_width = width / gridX;
  7899. const segment_height = height / gridY;
  7900. //
  7901. const indices = [];
  7902. const vertices = [];
  7903. const normals = [];
  7904. const uvs = [];
  7905. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7906. const y = iy * segment_height - height_half;
  7907. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7908. const x = ix * segment_width - width_half;
  7909. vertices.push( x, - y, 0 );
  7910. normals.push( 0, 0, 1 );
  7911. uvs.push( ix / gridX );
  7912. uvs.push( 1 - ( iy / gridY ) );
  7913. }
  7914. }
  7915. for ( let iy = 0; iy < gridY; iy ++ ) {
  7916. for ( let ix = 0; ix < gridX; ix ++ ) {
  7917. const a = ix + gridX1 * iy;
  7918. const b = ix + gridX1 * ( iy + 1 );
  7919. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7920. const d = ( ix + 1 ) + gridX1 * iy;
  7921. indices.push( a, b, d );
  7922. indices.push( b, c, d );
  7923. }
  7924. }
  7925. this.setIndex( indices );
  7926. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7927. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7928. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7929. }
  7930. copy( source ) {
  7931. super.copy( source );
  7932. this.parameters = Object.assign( {}, source.parameters );
  7933. return this;
  7934. }
  7935. static fromJSON( data ) {
  7936. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7937. }
  7938. }
  7939. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  7940. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7941. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7942. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7943. 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_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7944. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7945. var begin_vertex = "vec3 transformed = vec3( position );";
  7946. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7947. 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";
  7948. 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\t return 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 R21 = R12;\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";
  7949. 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 = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = 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";
  7950. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  7951. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7952. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7953. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7954. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7955. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7956. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7957. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_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";
  7958. 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};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\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}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\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";
  7959. 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_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\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";
  7960. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  7961. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7962. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  7963. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7964. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7965. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7966. var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( 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}";
  7967. 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, 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";
  7968. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\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";
  7969. 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";
  7970. 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";
  7971. 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";
  7972. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7973. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7974. 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";
  7975. 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";
  7976. 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}";
  7977. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7978. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7979. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7980. 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 GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, 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 GeometricContext geometry, 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";
  7981. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\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\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\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, const in GeometricContext geometry, 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 GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\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 GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\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";
  7982. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, 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#if defined( 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, 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#endif";
  7983. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7984. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, 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";
  7985. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7986. 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 GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, 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";
  7987. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\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_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";
  7988. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\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};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = 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_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\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\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 GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\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 GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, 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 GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, 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( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, 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}";
  7989. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\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, geometry, 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.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, 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, geometry, 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.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, 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, geometry, 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.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, 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, geometry, 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\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\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 ], geometry.normal );\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";
  7990. 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( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7991. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  7992. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  7993. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  7994. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  7995. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  7996. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  7997. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7998. 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";
  7999. 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";
  8000. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8001. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8002. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\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";
  8003. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  8004. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  8005. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  8006. 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#ifdef USE_NORMALMAP_TANGENTSPACE\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, vNormalMapUv );\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 geometryNormal = normal;";
  8007. 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";
  8008. 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";
  8009. 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";
  8010. 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";
  8011. 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 ) )\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";
  8012. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8013. 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";
  8014. 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";
  8015. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8016. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  8017. 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.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( 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( 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}";
  8018. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8019. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  8020. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8021. 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";
  8022. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8023. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8024. 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 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 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 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 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 shadow;\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 shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  8025. 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 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 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 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";
  8026. 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";
  8027. 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.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.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.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}";
  8028. 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";
  8029. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif";
  8030. 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";
  8031. 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";
  8032. 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";
  8033. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8034. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8035. 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 toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( 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}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8036. 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 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif";
  8037. 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, vec2 fullSize, 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\t\n\t\tvec2 lodFudge = pow( 1.95, lod ) / fullSize;\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\tvec2 fullSize = vec2( textureSize( sampler, 0 ) );\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), fullSize, floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), fullSize, 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 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\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 ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  8038. var uv_pars_fragment = "#ifdef USE_UV\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_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";
  8039. var uv_pars_vertex = "#ifdef USE_UV\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_UV2\n\tattribute vec2 uv2;\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_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";
  8040. var uv_vertex = "#ifdef USE_UV\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_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";
  8041. 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_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  8042. 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}";
  8043. 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 <encodings_fragment>\n}";
  8044. 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}";
  8045. 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;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, 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 <encodings_fragment>\n}";
  8046. 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}";
  8047. 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 <encodings_fragment>\n}";
  8048. const vertex$e = "#include <common>\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 <skinbase_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}";
  8049. 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 <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\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 <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#endif\n}";
  8050. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\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 <skinbase_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}";
  8051. 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 <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8052. 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}";
  8053. 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 <encodings_fragment>\n}";
  8054. 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 <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}";
  8055. 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\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8056. const vertex$a = "#include <common>\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 <morphcolor_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}";
  8057. 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 <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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8058. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\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 <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}";
  8059. 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 <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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8060. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\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 <morphcolor_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}";
  8061. 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 <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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8062. 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 <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 <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#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8063. 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\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 ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8064. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\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 <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}";
  8065. 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 <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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8066. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\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 <morphcolor_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}";
  8067. 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_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\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 <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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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 <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 + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8068. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\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 <morphcolor_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}";
  8069. 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 <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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8070. 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 <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}";
  8071. 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 <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8072. const vertex$2 = "#include <common>\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 <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 <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}";
  8073. 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 <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8074. 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 * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\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}";
  8075. 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 <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8076. const ShaderChunk = {
  8077. alphamap_fragment: alphamap_fragment,
  8078. alphamap_pars_fragment: alphamap_pars_fragment,
  8079. alphatest_fragment: alphatest_fragment,
  8080. alphatest_pars_fragment: alphatest_pars_fragment,
  8081. aomap_fragment: aomap_fragment,
  8082. aomap_pars_fragment: aomap_pars_fragment,
  8083. begin_vertex: begin_vertex,
  8084. beginnormal_vertex: beginnormal_vertex,
  8085. bsdfs: bsdfs,
  8086. iridescence_fragment: iridescence_fragment,
  8087. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8088. clipping_planes_fragment: clipping_planes_fragment,
  8089. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8090. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8091. clipping_planes_vertex: clipping_planes_vertex,
  8092. color_fragment: color_fragment,
  8093. color_pars_fragment: color_pars_fragment,
  8094. color_pars_vertex: color_pars_vertex,
  8095. color_vertex: color_vertex,
  8096. common: common,
  8097. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8098. defaultnormal_vertex: defaultnormal_vertex,
  8099. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8100. displacementmap_vertex: displacementmap_vertex,
  8101. emissivemap_fragment: emissivemap_fragment,
  8102. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8103. encodings_fragment: encodings_fragment,
  8104. encodings_pars_fragment: encodings_pars_fragment,
  8105. envmap_fragment: envmap_fragment,
  8106. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8107. envmap_pars_fragment: envmap_pars_fragment,
  8108. envmap_pars_vertex: envmap_pars_vertex,
  8109. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8110. envmap_vertex: envmap_vertex,
  8111. fog_vertex: fog_vertex,
  8112. fog_pars_vertex: fog_pars_vertex,
  8113. fog_fragment: fog_fragment,
  8114. fog_pars_fragment: fog_pars_fragment,
  8115. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8116. lightmap_fragment: lightmap_fragment,
  8117. lightmap_pars_fragment: lightmap_pars_fragment,
  8118. lights_lambert_fragment: lights_lambert_fragment,
  8119. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8120. lights_pars_begin: lights_pars_begin,
  8121. lights_toon_fragment: lights_toon_fragment,
  8122. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8123. lights_phong_fragment: lights_phong_fragment,
  8124. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8125. lights_physical_fragment: lights_physical_fragment,
  8126. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8127. lights_fragment_begin: lights_fragment_begin,
  8128. lights_fragment_maps: lights_fragment_maps,
  8129. lights_fragment_end: lights_fragment_end,
  8130. logdepthbuf_fragment: logdepthbuf_fragment,
  8131. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8132. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8133. logdepthbuf_vertex: logdepthbuf_vertex,
  8134. map_fragment: map_fragment,
  8135. map_pars_fragment: map_pars_fragment,
  8136. map_particle_fragment: map_particle_fragment,
  8137. map_particle_pars_fragment: map_particle_pars_fragment,
  8138. metalnessmap_fragment: metalnessmap_fragment,
  8139. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8140. morphcolor_vertex: morphcolor_vertex,
  8141. morphnormal_vertex: morphnormal_vertex,
  8142. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8143. morphtarget_vertex: morphtarget_vertex,
  8144. normal_fragment_begin: normal_fragment_begin,
  8145. normal_fragment_maps: normal_fragment_maps,
  8146. normal_pars_fragment: normal_pars_fragment,
  8147. normal_pars_vertex: normal_pars_vertex,
  8148. normal_vertex: normal_vertex,
  8149. normalmap_pars_fragment: normalmap_pars_fragment,
  8150. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8151. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8152. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8153. iridescence_pars_fragment: iridescence_pars_fragment,
  8154. output_fragment: output_fragment,
  8155. packing: packing,
  8156. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8157. project_vertex: project_vertex,
  8158. dithering_fragment: dithering_fragment,
  8159. dithering_pars_fragment: dithering_pars_fragment,
  8160. roughnessmap_fragment: roughnessmap_fragment,
  8161. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8162. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8163. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8164. shadowmap_vertex: shadowmap_vertex,
  8165. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8166. skinbase_vertex: skinbase_vertex,
  8167. skinning_pars_vertex: skinning_pars_vertex,
  8168. skinning_vertex: skinning_vertex,
  8169. skinnormal_vertex: skinnormal_vertex,
  8170. specularmap_fragment: specularmap_fragment,
  8171. specularmap_pars_fragment: specularmap_pars_fragment,
  8172. tonemapping_fragment: tonemapping_fragment,
  8173. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8174. transmission_fragment: transmission_fragment,
  8175. transmission_pars_fragment: transmission_pars_fragment,
  8176. uv_pars_fragment: uv_pars_fragment,
  8177. uv_pars_vertex: uv_pars_vertex,
  8178. uv_vertex: uv_vertex,
  8179. worldpos_vertex: worldpos_vertex,
  8180. background_vert: vertex$h,
  8181. background_frag: fragment$h,
  8182. backgroundCube_vert: vertex$g,
  8183. backgroundCube_frag: fragment$g,
  8184. cube_vert: vertex$f,
  8185. cube_frag: fragment$f,
  8186. depth_vert: vertex$e,
  8187. depth_frag: fragment$e,
  8188. distanceRGBA_vert: vertex$d,
  8189. distanceRGBA_frag: fragment$d,
  8190. equirect_vert: vertex$c,
  8191. equirect_frag: fragment$c,
  8192. linedashed_vert: vertex$b,
  8193. linedashed_frag: fragment$b,
  8194. meshbasic_vert: vertex$a,
  8195. meshbasic_frag: fragment$a,
  8196. meshlambert_vert: vertex$9,
  8197. meshlambert_frag: fragment$9,
  8198. meshmatcap_vert: vertex$8,
  8199. meshmatcap_frag: fragment$8,
  8200. meshnormal_vert: vertex$7,
  8201. meshnormal_frag: fragment$7,
  8202. meshphong_vert: vertex$6,
  8203. meshphong_frag: fragment$6,
  8204. meshphysical_vert: vertex$5,
  8205. meshphysical_frag: fragment$5,
  8206. meshtoon_vert: vertex$4,
  8207. meshtoon_frag: fragment$4,
  8208. points_vert: vertex$3,
  8209. points_frag: fragment$3,
  8210. shadow_vert: vertex$2,
  8211. shadow_frag: fragment$2,
  8212. sprite_vert: vertex$1,
  8213. sprite_frag: fragment$1
  8214. };
  8215. /**
  8216. * Uniforms library for shared webgl shaders
  8217. */
  8218. const UniformsLib = {
  8219. common: {
  8220. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8221. opacity: { value: 1.0 },
  8222. map: { value: null },
  8223. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8224. alphaMap: { value: null },
  8225. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8226. alphaTest: { value: 0 }
  8227. },
  8228. specularmap: {
  8229. specularMap: { value: null },
  8230. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8231. },
  8232. envmap: {
  8233. envMap: { value: null },
  8234. flipEnvMap: { value: - 1 },
  8235. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8236. ior: { value: 1.5 }, // physical
  8237. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8238. },
  8239. aomap: {
  8240. aoMap: { value: null },
  8241. aoMapIntensity: { value: 1 },
  8242. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8243. },
  8244. lightmap: {
  8245. lightMap: { value: null },
  8246. lightMapIntensity: { value: 1 },
  8247. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8248. },
  8249. bumpmap: {
  8250. bumpMap: { value: null },
  8251. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8252. bumpScale: { value: 1 }
  8253. },
  8254. normalmap: {
  8255. normalMap: { value: null },
  8256. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8257. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8258. },
  8259. displacementmap: {
  8260. displacementMap: { value: null },
  8261. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8262. displacementScale: { value: 1 },
  8263. displacementBias: { value: 0 }
  8264. },
  8265. emissivemap: {
  8266. emissiveMap: { value: null },
  8267. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8268. },
  8269. metalnessmap: {
  8270. metalnessMap: { value: null },
  8271. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8272. },
  8273. roughnessmap: {
  8274. roughnessMap: { value: null },
  8275. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8276. },
  8277. gradientmap: {
  8278. gradientMap: { value: null }
  8279. },
  8280. fog: {
  8281. fogDensity: { value: 0.00025 },
  8282. fogNear: { value: 1 },
  8283. fogFar: { value: 2000 },
  8284. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8285. },
  8286. lights: {
  8287. ambientLightColor: { value: [] },
  8288. lightProbe: { value: [] },
  8289. directionalLights: { value: [], properties: {
  8290. direction: {},
  8291. color: {}
  8292. } },
  8293. directionalLightShadows: { value: [], properties: {
  8294. shadowBias: {},
  8295. shadowNormalBias: {},
  8296. shadowRadius: {},
  8297. shadowMapSize: {}
  8298. } },
  8299. directionalShadowMap: { value: [] },
  8300. directionalShadowMatrix: { value: [] },
  8301. spotLights: { value: [], properties: {
  8302. color: {},
  8303. position: {},
  8304. direction: {},
  8305. distance: {},
  8306. coneCos: {},
  8307. penumbraCos: {},
  8308. decay: {}
  8309. } },
  8310. spotLightShadows: { value: [], properties: {
  8311. shadowBias: {},
  8312. shadowNormalBias: {},
  8313. shadowRadius: {},
  8314. shadowMapSize: {}
  8315. } },
  8316. spotLightMap: { value: [] },
  8317. spotShadowMap: { value: [] },
  8318. spotLightMatrix: { value: [] },
  8319. pointLights: { value: [], properties: {
  8320. color: {},
  8321. position: {},
  8322. decay: {},
  8323. distance: {}
  8324. } },
  8325. pointLightShadows: { value: [], properties: {
  8326. shadowBias: {},
  8327. shadowNormalBias: {},
  8328. shadowRadius: {},
  8329. shadowMapSize: {},
  8330. shadowCameraNear: {},
  8331. shadowCameraFar: {}
  8332. } },
  8333. pointShadowMap: { value: [] },
  8334. pointShadowMatrix: { value: [] },
  8335. hemisphereLights: { value: [], properties: {
  8336. direction: {},
  8337. skyColor: {},
  8338. groundColor: {}
  8339. } },
  8340. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8341. rectAreaLights: { value: [], properties: {
  8342. color: {},
  8343. position: {},
  8344. width: {},
  8345. height: {}
  8346. } },
  8347. ltc_1: { value: null },
  8348. ltc_2: { value: null }
  8349. },
  8350. points: {
  8351. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8352. opacity: { value: 1.0 },
  8353. size: { value: 1.0 },
  8354. scale: { value: 1.0 },
  8355. map: { value: null },
  8356. alphaMap: { value: null },
  8357. alphaTest: { value: 0 },
  8358. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8359. },
  8360. sprite: {
  8361. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8362. opacity: { value: 1.0 },
  8363. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8364. rotation: { value: 0.0 },
  8365. map: { value: null },
  8366. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8367. alphaMap: { value: null },
  8368. alphaTest: { value: 0 }
  8369. }
  8370. };
  8371. const ShaderLib = {
  8372. basic: {
  8373. uniforms: /*@__PURE__*/ mergeUniforms( [
  8374. UniformsLib.common,
  8375. UniformsLib.specularmap,
  8376. UniformsLib.envmap,
  8377. UniformsLib.aomap,
  8378. UniformsLib.lightmap,
  8379. UniformsLib.fog
  8380. ] ),
  8381. vertexShader: ShaderChunk.meshbasic_vert,
  8382. fragmentShader: ShaderChunk.meshbasic_frag
  8383. },
  8384. lambert: {
  8385. uniforms: /*@__PURE__*/ mergeUniforms( [
  8386. UniformsLib.common,
  8387. UniformsLib.specularmap,
  8388. UniformsLib.envmap,
  8389. UniformsLib.aomap,
  8390. UniformsLib.lightmap,
  8391. UniformsLib.emissivemap,
  8392. UniformsLib.bumpmap,
  8393. UniformsLib.normalmap,
  8394. UniformsLib.displacementmap,
  8395. UniformsLib.fog,
  8396. UniformsLib.lights,
  8397. {
  8398. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8399. }
  8400. ] ),
  8401. vertexShader: ShaderChunk.meshlambert_vert,
  8402. fragmentShader: ShaderChunk.meshlambert_frag
  8403. },
  8404. phong: {
  8405. uniforms: /*@__PURE__*/ mergeUniforms( [
  8406. UniformsLib.common,
  8407. UniformsLib.specularmap,
  8408. UniformsLib.envmap,
  8409. UniformsLib.aomap,
  8410. UniformsLib.lightmap,
  8411. UniformsLib.emissivemap,
  8412. UniformsLib.bumpmap,
  8413. UniformsLib.normalmap,
  8414. UniformsLib.displacementmap,
  8415. UniformsLib.fog,
  8416. UniformsLib.lights,
  8417. {
  8418. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8419. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8420. shininess: { value: 30 }
  8421. }
  8422. ] ),
  8423. vertexShader: ShaderChunk.meshphong_vert,
  8424. fragmentShader: ShaderChunk.meshphong_frag
  8425. },
  8426. standard: {
  8427. uniforms: /*@__PURE__*/ mergeUniforms( [
  8428. UniformsLib.common,
  8429. UniformsLib.envmap,
  8430. UniformsLib.aomap,
  8431. UniformsLib.lightmap,
  8432. UniformsLib.emissivemap,
  8433. UniformsLib.bumpmap,
  8434. UniformsLib.normalmap,
  8435. UniformsLib.displacementmap,
  8436. UniformsLib.roughnessmap,
  8437. UniformsLib.metalnessmap,
  8438. UniformsLib.fog,
  8439. UniformsLib.lights,
  8440. {
  8441. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8442. roughness: { value: 1.0 },
  8443. metalness: { value: 0.0 },
  8444. envMapIntensity: { value: 1 } // temporary
  8445. }
  8446. ] ),
  8447. vertexShader: ShaderChunk.meshphysical_vert,
  8448. fragmentShader: ShaderChunk.meshphysical_frag
  8449. },
  8450. toon: {
  8451. uniforms: /*@__PURE__*/ mergeUniforms( [
  8452. UniformsLib.common,
  8453. UniformsLib.aomap,
  8454. UniformsLib.lightmap,
  8455. UniformsLib.emissivemap,
  8456. UniformsLib.bumpmap,
  8457. UniformsLib.normalmap,
  8458. UniformsLib.displacementmap,
  8459. UniformsLib.gradientmap,
  8460. UniformsLib.fog,
  8461. UniformsLib.lights,
  8462. {
  8463. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8464. }
  8465. ] ),
  8466. vertexShader: ShaderChunk.meshtoon_vert,
  8467. fragmentShader: ShaderChunk.meshtoon_frag
  8468. },
  8469. matcap: {
  8470. uniforms: /*@__PURE__*/ mergeUniforms( [
  8471. UniformsLib.common,
  8472. UniformsLib.bumpmap,
  8473. UniformsLib.normalmap,
  8474. UniformsLib.displacementmap,
  8475. UniformsLib.fog,
  8476. {
  8477. matcap: { value: null }
  8478. }
  8479. ] ),
  8480. vertexShader: ShaderChunk.meshmatcap_vert,
  8481. fragmentShader: ShaderChunk.meshmatcap_frag
  8482. },
  8483. points: {
  8484. uniforms: /*@__PURE__*/ mergeUniforms( [
  8485. UniformsLib.points,
  8486. UniformsLib.fog
  8487. ] ),
  8488. vertexShader: ShaderChunk.points_vert,
  8489. fragmentShader: ShaderChunk.points_frag
  8490. },
  8491. dashed: {
  8492. uniforms: /*@__PURE__*/ mergeUniforms( [
  8493. UniformsLib.common,
  8494. UniformsLib.fog,
  8495. {
  8496. scale: { value: 1 },
  8497. dashSize: { value: 1 },
  8498. totalSize: { value: 2 }
  8499. }
  8500. ] ),
  8501. vertexShader: ShaderChunk.linedashed_vert,
  8502. fragmentShader: ShaderChunk.linedashed_frag
  8503. },
  8504. depth: {
  8505. uniforms: /*@__PURE__*/ mergeUniforms( [
  8506. UniformsLib.common,
  8507. UniformsLib.displacementmap
  8508. ] ),
  8509. vertexShader: ShaderChunk.depth_vert,
  8510. fragmentShader: ShaderChunk.depth_frag
  8511. },
  8512. normal: {
  8513. uniforms: /*@__PURE__*/ mergeUniforms( [
  8514. UniformsLib.common,
  8515. UniformsLib.bumpmap,
  8516. UniformsLib.normalmap,
  8517. UniformsLib.displacementmap,
  8518. {
  8519. opacity: { value: 1.0 }
  8520. }
  8521. ] ),
  8522. vertexShader: ShaderChunk.meshnormal_vert,
  8523. fragmentShader: ShaderChunk.meshnormal_frag
  8524. },
  8525. sprite: {
  8526. uniforms: /*@__PURE__*/ mergeUniforms( [
  8527. UniformsLib.sprite,
  8528. UniformsLib.fog
  8529. ] ),
  8530. vertexShader: ShaderChunk.sprite_vert,
  8531. fragmentShader: ShaderChunk.sprite_frag
  8532. },
  8533. background: {
  8534. uniforms: {
  8535. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8536. t2D: { value: null },
  8537. backgroundIntensity: { value: 1 }
  8538. },
  8539. vertexShader: ShaderChunk.background_vert,
  8540. fragmentShader: ShaderChunk.background_frag
  8541. },
  8542. backgroundCube: {
  8543. uniforms: {
  8544. envMap: { value: null },
  8545. flipEnvMap: { value: - 1 },
  8546. backgroundBlurriness: { value: 0 },
  8547. backgroundIntensity: { value: 1 }
  8548. },
  8549. vertexShader: ShaderChunk.backgroundCube_vert,
  8550. fragmentShader: ShaderChunk.backgroundCube_frag
  8551. },
  8552. cube: {
  8553. uniforms: {
  8554. tCube: { value: null },
  8555. tFlip: { value: - 1 },
  8556. opacity: { value: 1.0 }
  8557. },
  8558. vertexShader: ShaderChunk.cube_vert,
  8559. fragmentShader: ShaderChunk.cube_frag
  8560. },
  8561. equirect: {
  8562. uniforms: {
  8563. tEquirect: { value: null },
  8564. },
  8565. vertexShader: ShaderChunk.equirect_vert,
  8566. fragmentShader: ShaderChunk.equirect_frag
  8567. },
  8568. distanceRGBA: {
  8569. uniforms: /*@__PURE__*/ mergeUniforms( [
  8570. UniformsLib.common,
  8571. UniformsLib.displacementmap,
  8572. {
  8573. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8574. nearDistance: { value: 1 },
  8575. farDistance: { value: 1000 }
  8576. }
  8577. ] ),
  8578. vertexShader: ShaderChunk.distanceRGBA_vert,
  8579. fragmentShader: ShaderChunk.distanceRGBA_frag
  8580. },
  8581. shadow: {
  8582. uniforms: /*@__PURE__*/ mergeUniforms( [
  8583. UniformsLib.lights,
  8584. UniformsLib.fog,
  8585. {
  8586. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8587. opacity: { value: 1.0 }
  8588. },
  8589. ] ),
  8590. vertexShader: ShaderChunk.shadow_vert,
  8591. fragmentShader: ShaderChunk.shadow_frag
  8592. }
  8593. };
  8594. ShaderLib.physical = {
  8595. uniforms: /*@__PURE__*/ mergeUniforms( [
  8596. ShaderLib.standard.uniforms,
  8597. {
  8598. clearcoat: { value: 0 },
  8599. clearcoatMap: { value: null },
  8600. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8601. clearcoatNormalMap: { value: null },
  8602. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8603. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8604. clearcoatRoughness: { value: 0 },
  8605. clearcoatRoughnessMap: { value: null },
  8606. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8607. iridescence: { value: 0 },
  8608. iridescenceMap: { value: null },
  8609. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8610. iridescenceIOR: { value: 1.3 },
  8611. iridescenceThicknessMinimum: { value: 100 },
  8612. iridescenceThicknessMaximum: { value: 400 },
  8613. iridescenceThicknessMap: { value: null },
  8614. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8615. sheen: { value: 0 },
  8616. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8617. sheenColorMap: { value: null },
  8618. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8619. sheenRoughness: { value: 1 },
  8620. sheenRoughnessMap: { value: null },
  8621. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8622. transmission: { value: 0 },
  8623. transmissionMap: { value: null },
  8624. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8625. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8626. transmissionSamplerMap: { value: null },
  8627. thickness: { value: 0 },
  8628. thicknessMap: { value: null },
  8629. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8630. attenuationDistance: { value: 0 },
  8631. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8632. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8633. specularColorMap: { value: null },
  8634. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8635. specularIntensity: { value: 1 },
  8636. specularIntensityMap: { value: null },
  8637. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8638. }
  8639. ] ),
  8640. vertexShader: ShaderChunk.meshphysical_vert,
  8641. fragmentShader: ShaderChunk.meshphysical_frag
  8642. };
  8643. const _rgb = { r: 0, b: 0, g: 0 };
  8644. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8645. const clearColor = new Color( 0x000000 );
  8646. let clearAlpha = alpha === true ? 0 : 1;
  8647. let planeMesh;
  8648. let boxMesh;
  8649. let currentBackground = null;
  8650. let currentBackgroundVersion = 0;
  8651. let currentTonemapping = null;
  8652. function render( renderList, scene ) {
  8653. let forceClear = false;
  8654. let background = scene.isScene === true ? scene.background : null;
  8655. if ( background && background.isTexture ) {
  8656. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8657. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8658. }
  8659. // Ignore background in AR
  8660. // TODO: Reconsider this.
  8661. const xr = renderer.xr;
  8662. const session = xr.getSession && xr.getSession();
  8663. if ( session && session.environmentBlendMode === 'additive' ) {
  8664. background = null;
  8665. }
  8666. if ( background === null ) {
  8667. setClear( clearColor, clearAlpha );
  8668. } else if ( background && background.isColor ) {
  8669. setClear( background, 1 );
  8670. forceClear = true;
  8671. }
  8672. if ( renderer.autoClear || forceClear ) {
  8673. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8674. }
  8675. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8676. if ( boxMesh === undefined ) {
  8677. boxMesh = new Mesh(
  8678. new BoxGeometry( 1, 1, 1 ),
  8679. new ShaderMaterial( {
  8680. name: 'BackgroundCubeMaterial',
  8681. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8682. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8683. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8684. side: BackSide,
  8685. depthTest: false,
  8686. depthWrite: false,
  8687. fog: false
  8688. } )
  8689. );
  8690. boxMesh.geometry.deleteAttribute( 'normal' );
  8691. boxMesh.geometry.deleteAttribute( 'uv' );
  8692. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8693. this.matrixWorld.copyPosition( camera.matrixWorld );
  8694. };
  8695. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8696. Object.defineProperty( boxMesh.material, 'envMap', {
  8697. get: function () {
  8698. return this.uniforms.envMap.value;
  8699. }
  8700. } );
  8701. objects.update( boxMesh );
  8702. }
  8703. boxMesh.material.uniforms.envMap.value = background;
  8704. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8705. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8706. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8707. boxMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8708. if ( currentBackground !== background ||
  8709. currentBackgroundVersion !== background.version ||
  8710. currentTonemapping !== renderer.toneMapping ) {
  8711. boxMesh.material.needsUpdate = true;
  8712. currentBackground = background;
  8713. currentBackgroundVersion = background.version;
  8714. currentTonemapping = renderer.toneMapping;
  8715. }
  8716. boxMesh.layers.enableAll();
  8717. // push to the pre-sorted opaque render list
  8718. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8719. } else if ( background && background.isTexture ) {
  8720. if ( planeMesh === undefined ) {
  8721. planeMesh = new Mesh(
  8722. new PlaneGeometry( 2, 2 ),
  8723. new ShaderMaterial( {
  8724. name: 'BackgroundMaterial',
  8725. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8726. vertexShader: ShaderLib.background.vertexShader,
  8727. fragmentShader: ShaderLib.background.fragmentShader,
  8728. side: FrontSide,
  8729. depthTest: false,
  8730. depthWrite: false,
  8731. fog: false
  8732. } )
  8733. );
  8734. planeMesh.geometry.deleteAttribute( 'normal' );
  8735. // add "map" material property so the renderer can evaluate it like for built-in materials
  8736. Object.defineProperty( planeMesh.material, 'map', {
  8737. get: function () {
  8738. return this.uniforms.t2D.value;
  8739. }
  8740. } );
  8741. objects.update( planeMesh );
  8742. }
  8743. planeMesh.material.uniforms.t2D.value = background;
  8744. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8745. planeMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8746. if ( background.matrixAutoUpdate === true ) {
  8747. background.updateMatrix();
  8748. }
  8749. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8750. if ( currentBackground !== background ||
  8751. currentBackgroundVersion !== background.version ||
  8752. currentTonemapping !== renderer.toneMapping ) {
  8753. planeMesh.material.needsUpdate = true;
  8754. currentBackground = background;
  8755. currentBackgroundVersion = background.version;
  8756. currentTonemapping = renderer.toneMapping;
  8757. }
  8758. planeMesh.layers.enableAll();
  8759. // push to the pre-sorted opaque render list
  8760. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8761. }
  8762. }
  8763. function setClear( color, alpha ) {
  8764. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8765. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8766. }
  8767. return {
  8768. getClearColor: function () {
  8769. return clearColor;
  8770. },
  8771. setClearColor: function ( color, alpha = 1 ) {
  8772. clearColor.set( color );
  8773. clearAlpha = alpha;
  8774. setClear( clearColor, clearAlpha );
  8775. },
  8776. getClearAlpha: function () {
  8777. return clearAlpha;
  8778. },
  8779. setClearAlpha: function ( alpha ) {
  8780. clearAlpha = alpha;
  8781. setClear( clearColor, clearAlpha );
  8782. },
  8783. render: render
  8784. };
  8785. }
  8786. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8787. const maxVertexAttributes = gl.getParameter( 34921 );
  8788. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8789. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8790. const bindingStates = {};
  8791. const defaultState = createBindingState( null );
  8792. let currentState = defaultState;
  8793. let forceUpdate = false;
  8794. function setup( object, material, program, geometry, index ) {
  8795. let updateBuffers = false;
  8796. if ( vaoAvailable ) {
  8797. const state = getBindingState( geometry, program, material );
  8798. if ( currentState !== state ) {
  8799. currentState = state;
  8800. bindVertexArrayObject( currentState.object );
  8801. }
  8802. updateBuffers = needsUpdate( object, geometry, program, index );
  8803. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8804. } else {
  8805. const wireframe = ( material.wireframe === true );
  8806. if ( currentState.geometry !== geometry.id ||
  8807. currentState.program !== program.id ||
  8808. currentState.wireframe !== wireframe ) {
  8809. currentState.geometry = geometry.id;
  8810. currentState.program = program.id;
  8811. currentState.wireframe = wireframe;
  8812. updateBuffers = true;
  8813. }
  8814. }
  8815. if ( index !== null ) {
  8816. attributes.update( index, 34963 );
  8817. }
  8818. if ( updateBuffers || forceUpdate ) {
  8819. forceUpdate = false;
  8820. setupVertexAttributes( object, material, program, geometry );
  8821. if ( index !== null ) {
  8822. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8823. }
  8824. }
  8825. }
  8826. function createVertexArrayObject() {
  8827. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8828. return extension.createVertexArrayOES();
  8829. }
  8830. function bindVertexArrayObject( vao ) {
  8831. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8832. return extension.bindVertexArrayOES( vao );
  8833. }
  8834. function deleteVertexArrayObject( vao ) {
  8835. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8836. return extension.deleteVertexArrayOES( vao );
  8837. }
  8838. function getBindingState( geometry, program, material ) {
  8839. const wireframe = ( material.wireframe === true );
  8840. let programMap = bindingStates[ geometry.id ];
  8841. if ( programMap === undefined ) {
  8842. programMap = {};
  8843. bindingStates[ geometry.id ] = programMap;
  8844. }
  8845. let stateMap = programMap[ program.id ];
  8846. if ( stateMap === undefined ) {
  8847. stateMap = {};
  8848. programMap[ program.id ] = stateMap;
  8849. }
  8850. let state = stateMap[ wireframe ];
  8851. if ( state === undefined ) {
  8852. state = createBindingState( createVertexArrayObject() );
  8853. stateMap[ wireframe ] = state;
  8854. }
  8855. return state;
  8856. }
  8857. function createBindingState( vao ) {
  8858. const newAttributes = [];
  8859. const enabledAttributes = [];
  8860. const attributeDivisors = [];
  8861. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8862. newAttributes[ i ] = 0;
  8863. enabledAttributes[ i ] = 0;
  8864. attributeDivisors[ i ] = 0;
  8865. }
  8866. return {
  8867. // for backward compatibility on non-VAO support browser
  8868. geometry: null,
  8869. program: null,
  8870. wireframe: false,
  8871. newAttributes: newAttributes,
  8872. enabledAttributes: enabledAttributes,
  8873. attributeDivisors: attributeDivisors,
  8874. object: vao,
  8875. attributes: {},
  8876. index: null
  8877. };
  8878. }
  8879. function needsUpdate( object, geometry, program, index ) {
  8880. const cachedAttributes = currentState.attributes;
  8881. const geometryAttributes = geometry.attributes;
  8882. let attributesNum = 0;
  8883. const programAttributes = program.getAttributes();
  8884. for ( const name in programAttributes ) {
  8885. const programAttribute = programAttributes[ name ];
  8886. if ( programAttribute.location >= 0 ) {
  8887. const cachedAttribute = cachedAttributes[ name ];
  8888. let geometryAttribute = geometryAttributes[ name ];
  8889. if ( geometryAttribute === undefined ) {
  8890. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8891. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8892. }
  8893. if ( cachedAttribute === undefined ) return true;
  8894. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8895. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8896. attributesNum ++;
  8897. }
  8898. }
  8899. if ( currentState.attributesNum !== attributesNum ) return true;
  8900. if ( currentState.index !== index ) return true;
  8901. return false;
  8902. }
  8903. function saveCache( object, geometry, program, index ) {
  8904. const cache = {};
  8905. const attributes = geometry.attributes;
  8906. let attributesNum = 0;
  8907. const programAttributes = program.getAttributes();
  8908. for ( const name in programAttributes ) {
  8909. const programAttribute = programAttributes[ name ];
  8910. if ( programAttribute.location >= 0 ) {
  8911. let attribute = attributes[ name ];
  8912. if ( attribute === undefined ) {
  8913. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8914. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8915. }
  8916. const data = {};
  8917. data.attribute = attribute;
  8918. if ( attribute && attribute.data ) {
  8919. data.data = attribute.data;
  8920. }
  8921. cache[ name ] = data;
  8922. attributesNum ++;
  8923. }
  8924. }
  8925. currentState.attributes = cache;
  8926. currentState.attributesNum = attributesNum;
  8927. currentState.index = index;
  8928. }
  8929. function initAttributes() {
  8930. const newAttributes = currentState.newAttributes;
  8931. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8932. newAttributes[ i ] = 0;
  8933. }
  8934. }
  8935. function enableAttribute( attribute ) {
  8936. enableAttributeAndDivisor( attribute, 0 );
  8937. }
  8938. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8939. const newAttributes = currentState.newAttributes;
  8940. const enabledAttributes = currentState.enabledAttributes;
  8941. const attributeDivisors = currentState.attributeDivisors;
  8942. newAttributes[ attribute ] = 1;
  8943. if ( enabledAttributes[ attribute ] === 0 ) {
  8944. gl.enableVertexAttribArray( attribute );
  8945. enabledAttributes[ attribute ] = 1;
  8946. }
  8947. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8948. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8949. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8950. attributeDivisors[ attribute ] = meshPerAttribute;
  8951. }
  8952. }
  8953. function disableUnusedAttributes() {
  8954. const newAttributes = currentState.newAttributes;
  8955. const enabledAttributes = currentState.enabledAttributes;
  8956. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8957. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8958. gl.disableVertexAttribArray( i );
  8959. enabledAttributes[ i ] = 0;
  8960. }
  8961. }
  8962. }
  8963. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8964. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8965. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8966. } else {
  8967. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8968. }
  8969. }
  8970. function setupVertexAttributes( object, material, program, geometry ) {
  8971. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8972. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8973. }
  8974. initAttributes();
  8975. const geometryAttributes = geometry.attributes;
  8976. const programAttributes = program.getAttributes();
  8977. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8978. for ( const name in programAttributes ) {
  8979. const programAttribute = programAttributes[ name ];
  8980. if ( programAttribute.location >= 0 ) {
  8981. let geometryAttribute = geometryAttributes[ name ];
  8982. if ( geometryAttribute === undefined ) {
  8983. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8984. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8985. }
  8986. if ( geometryAttribute !== undefined ) {
  8987. const normalized = geometryAttribute.normalized;
  8988. const size = geometryAttribute.itemSize;
  8989. const attribute = attributes.get( geometryAttribute );
  8990. // TODO Attribute may not be available on context restore
  8991. if ( attribute === undefined ) continue;
  8992. const buffer = attribute.buffer;
  8993. const type = attribute.type;
  8994. const bytesPerElement = attribute.bytesPerElement;
  8995. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8996. const data = geometryAttribute.data;
  8997. const stride = data.stride;
  8998. const offset = geometryAttribute.offset;
  8999. if ( data.isInstancedInterleavedBuffer ) {
  9000. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9001. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9002. }
  9003. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9004. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9005. }
  9006. } else {
  9007. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9008. enableAttribute( programAttribute.location + i );
  9009. }
  9010. }
  9011. gl.bindBuffer( 34962, buffer );
  9012. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9013. vertexAttribPointer(
  9014. programAttribute.location + i,
  9015. size / programAttribute.locationSize,
  9016. type,
  9017. normalized,
  9018. stride * bytesPerElement,
  9019. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  9020. );
  9021. }
  9022. } else {
  9023. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9024. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9025. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9026. }
  9027. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9028. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9029. }
  9030. } else {
  9031. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9032. enableAttribute( programAttribute.location + i );
  9033. }
  9034. }
  9035. gl.bindBuffer( 34962, buffer );
  9036. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9037. vertexAttribPointer(
  9038. programAttribute.location + i,
  9039. size / programAttribute.locationSize,
  9040. type,
  9041. normalized,
  9042. size * bytesPerElement,
  9043. ( size / programAttribute.locationSize ) * i * bytesPerElement
  9044. );
  9045. }
  9046. }
  9047. } else if ( materialDefaultAttributeValues !== undefined ) {
  9048. const value = materialDefaultAttributeValues[ name ];
  9049. if ( value !== undefined ) {
  9050. switch ( value.length ) {
  9051. case 2:
  9052. gl.vertexAttrib2fv( programAttribute.location, value );
  9053. break;
  9054. case 3:
  9055. gl.vertexAttrib3fv( programAttribute.location, value );
  9056. break;
  9057. case 4:
  9058. gl.vertexAttrib4fv( programAttribute.location, value );
  9059. break;
  9060. default:
  9061. gl.vertexAttrib1fv( programAttribute.location, value );
  9062. }
  9063. }
  9064. }
  9065. }
  9066. }
  9067. disableUnusedAttributes();
  9068. }
  9069. function dispose() {
  9070. reset();
  9071. for ( const geometryId in bindingStates ) {
  9072. const programMap = bindingStates[ geometryId ];
  9073. for ( const programId in programMap ) {
  9074. const stateMap = programMap[ programId ];
  9075. for ( const wireframe in stateMap ) {
  9076. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9077. delete stateMap[ wireframe ];
  9078. }
  9079. delete programMap[ programId ];
  9080. }
  9081. delete bindingStates[ geometryId ];
  9082. }
  9083. }
  9084. function releaseStatesOfGeometry( geometry ) {
  9085. if ( bindingStates[ geometry.id ] === undefined ) return;
  9086. const programMap = bindingStates[ geometry.id ];
  9087. for ( const programId in programMap ) {
  9088. const stateMap = programMap[ programId ];
  9089. for ( const wireframe in stateMap ) {
  9090. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9091. delete stateMap[ wireframe ];
  9092. }
  9093. delete programMap[ programId ];
  9094. }
  9095. delete bindingStates[ geometry.id ];
  9096. }
  9097. function releaseStatesOfProgram( program ) {
  9098. for ( const geometryId in bindingStates ) {
  9099. const programMap = bindingStates[ geometryId ];
  9100. if ( programMap[ program.id ] === undefined ) continue;
  9101. const stateMap = programMap[ program.id ];
  9102. for ( const wireframe in stateMap ) {
  9103. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9104. delete stateMap[ wireframe ];
  9105. }
  9106. delete programMap[ program.id ];
  9107. }
  9108. }
  9109. function reset() {
  9110. resetDefaultState();
  9111. forceUpdate = true;
  9112. if ( currentState === defaultState ) return;
  9113. currentState = defaultState;
  9114. bindVertexArrayObject( currentState.object );
  9115. }
  9116. // for backward-compatibility
  9117. function resetDefaultState() {
  9118. defaultState.geometry = null;
  9119. defaultState.program = null;
  9120. defaultState.wireframe = false;
  9121. }
  9122. return {
  9123. setup: setup,
  9124. reset: reset,
  9125. resetDefaultState: resetDefaultState,
  9126. dispose: dispose,
  9127. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9128. releaseStatesOfProgram: releaseStatesOfProgram,
  9129. initAttributes: initAttributes,
  9130. enableAttribute: enableAttribute,
  9131. disableUnusedAttributes: disableUnusedAttributes
  9132. };
  9133. }
  9134. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9135. const isWebGL2 = capabilities.isWebGL2;
  9136. let mode;
  9137. function setMode( value ) {
  9138. mode = value;
  9139. }
  9140. function render( start, count ) {
  9141. gl.drawArrays( mode, start, count );
  9142. info.update( count, mode, 1 );
  9143. }
  9144. function renderInstances( start, count, primcount ) {
  9145. if ( primcount === 0 ) return;
  9146. let extension, methodName;
  9147. if ( isWebGL2 ) {
  9148. extension = gl;
  9149. methodName = 'drawArraysInstanced';
  9150. } else {
  9151. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9152. methodName = 'drawArraysInstancedANGLE';
  9153. if ( extension === null ) {
  9154. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9155. return;
  9156. }
  9157. }
  9158. extension[ methodName ]( mode, start, count, primcount );
  9159. info.update( count, mode, primcount );
  9160. }
  9161. //
  9162. this.setMode = setMode;
  9163. this.render = render;
  9164. this.renderInstances = renderInstances;
  9165. }
  9166. function WebGLCapabilities( gl, extensions, parameters ) {
  9167. let maxAnisotropy;
  9168. function getMaxAnisotropy() {
  9169. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9170. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9171. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9172. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9173. } else {
  9174. maxAnisotropy = 0;
  9175. }
  9176. return maxAnisotropy;
  9177. }
  9178. function getMaxPrecision( precision ) {
  9179. if ( precision === 'highp' ) {
  9180. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  9181. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  9182. return 'highp';
  9183. }
  9184. precision = 'mediump';
  9185. }
  9186. if ( precision === 'mediump' ) {
  9187. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  9188. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  9189. return 'mediump';
  9190. }
  9191. }
  9192. return 'lowp';
  9193. }
  9194. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext';
  9195. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9196. const maxPrecision = getMaxPrecision( precision );
  9197. if ( maxPrecision !== precision ) {
  9198. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9199. precision = maxPrecision;
  9200. }
  9201. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  9202. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9203. const maxTextures = gl.getParameter( 34930 );
  9204. const maxVertexTextures = gl.getParameter( 35660 );
  9205. const maxTextureSize = gl.getParameter( 3379 );
  9206. const maxCubemapSize = gl.getParameter( 34076 );
  9207. const maxAttributes = gl.getParameter( 34921 );
  9208. const maxVertexUniforms = gl.getParameter( 36347 );
  9209. const maxVaryings = gl.getParameter( 36348 );
  9210. const maxFragmentUniforms = gl.getParameter( 36349 );
  9211. const vertexTextures = maxVertexTextures > 0;
  9212. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  9213. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9214. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  9215. return {
  9216. isWebGL2: isWebGL2,
  9217. drawBuffers: drawBuffers,
  9218. getMaxAnisotropy: getMaxAnisotropy,
  9219. getMaxPrecision: getMaxPrecision,
  9220. precision: precision,
  9221. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9222. maxTextures: maxTextures,
  9223. maxVertexTextures: maxVertexTextures,
  9224. maxTextureSize: maxTextureSize,
  9225. maxCubemapSize: maxCubemapSize,
  9226. maxAttributes: maxAttributes,
  9227. maxVertexUniforms: maxVertexUniforms,
  9228. maxVaryings: maxVaryings,
  9229. maxFragmentUniforms: maxFragmentUniforms,
  9230. vertexTextures: vertexTextures,
  9231. floatFragmentTextures: floatFragmentTextures,
  9232. floatVertexTextures: floatVertexTextures,
  9233. maxSamples: maxSamples
  9234. };
  9235. }
  9236. function WebGLClipping( properties ) {
  9237. const scope = this;
  9238. let globalState = null,
  9239. numGlobalPlanes = 0,
  9240. localClippingEnabled = false,
  9241. renderingShadows = false;
  9242. const plane = new Plane(),
  9243. viewNormalMatrix = new Matrix3(),
  9244. uniform = { value: null, needsUpdate: false };
  9245. this.uniform = uniform;
  9246. this.numPlanes = 0;
  9247. this.numIntersection = 0;
  9248. this.init = function ( planes, enableLocalClipping ) {
  9249. const enabled =
  9250. planes.length !== 0 ||
  9251. enableLocalClipping ||
  9252. // enable state of previous frame - the clipping code has to
  9253. // run another frame in order to reset the state:
  9254. numGlobalPlanes !== 0 ||
  9255. localClippingEnabled;
  9256. localClippingEnabled = enableLocalClipping;
  9257. numGlobalPlanes = planes.length;
  9258. return enabled;
  9259. };
  9260. this.beginShadows = function () {
  9261. renderingShadows = true;
  9262. projectPlanes( null );
  9263. };
  9264. this.endShadows = function () {
  9265. renderingShadows = false;
  9266. };
  9267. this.setGlobalState = function ( planes, camera ) {
  9268. globalState = projectPlanes( planes, camera, 0 );
  9269. };
  9270. this.setState = function ( material, camera, useCache ) {
  9271. const planes = material.clippingPlanes,
  9272. clipIntersection = material.clipIntersection,
  9273. clipShadows = material.clipShadows;
  9274. const materialProperties = properties.get( material );
  9275. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9276. // there's no local clipping
  9277. if ( renderingShadows ) {
  9278. // there's no global clipping
  9279. projectPlanes( null );
  9280. } else {
  9281. resetGlobalState();
  9282. }
  9283. } else {
  9284. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9285. lGlobal = nGlobal * 4;
  9286. let dstArray = materialProperties.clippingState || null;
  9287. uniform.value = dstArray; // ensure unique state
  9288. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9289. for ( let i = 0; i !== lGlobal; ++ i ) {
  9290. dstArray[ i ] = globalState[ i ];
  9291. }
  9292. materialProperties.clippingState = dstArray;
  9293. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9294. this.numPlanes += nGlobal;
  9295. }
  9296. };
  9297. function resetGlobalState() {
  9298. if ( uniform.value !== globalState ) {
  9299. uniform.value = globalState;
  9300. uniform.needsUpdate = numGlobalPlanes > 0;
  9301. }
  9302. scope.numPlanes = numGlobalPlanes;
  9303. scope.numIntersection = 0;
  9304. }
  9305. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9306. const nPlanes = planes !== null ? planes.length : 0;
  9307. let dstArray = null;
  9308. if ( nPlanes !== 0 ) {
  9309. dstArray = uniform.value;
  9310. if ( skipTransform !== true || dstArray === null ) {
  9311. const flatSize = dstOffset + nPlanes * 4,
  9312. viewMatrix = camera.matrixWorldInverse;
  9313. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9314. if ( dstArray === null || dstArray.length < flatSize ) {
  9315. dstArray = new Float32Array( flatSize );
  9316. }
  9317. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9318. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9319. plane.normal.toArray( dstArray, i4 );
  9320. dstArray[ i4 + 3 ] = plane.constant;
  9321. }
  9322. }
  9323. uniform.value = dstArray;
  9324. uniform.needsUpdate = true;
  9325. }
  9326. scope.numPlanes = nPlanes;
  9327. scope.numIntersection = 0;
  9328. return dstArray;
  9329. }
  9330. }
  9331. function WebGLCubeMaps( renderer ) {
  9332. let cubemaps = new WeakMap();
  9333. function mapTextureMapping( texture, mapping ) {
  9334. if ( mapping === EquirectangularReflectionMapping ) {
  9335. texture.mapping = CubeReflectionMapping;
  9336. } else if ( mapping === EquirectangularRefractionMapping ) {
  9337. texture.mapping = CubeRefractionMapping;
  9338. }
  9339. return texture;
  9340. }
  9341. function get( texture ) {
  9342. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9343. const mapping = texture.mapping;
  9344. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9345. if ( cubemaps.has( texture ) ) {
  9346. const cubemap = cubemaps.get( texture ).texture;
  9347. return mapTextureMapping( cubemap, texture.mapping );
  9348. } else {
  9349. const image = texture.image;
  9350. if ( image && image.height > 0 ) {
  9351. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9352. renderTarget.fromEquirectangularTexture( renderer, texture );
  9353. cubemaps.set( texture, renderTarget );
  9354. texture.addEventListener( 'dispose', onTextureDispose );
  9355. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9356. } else {
  9357. // image not yet ready. try the conversion next frame
  9358. return null;
  9359. }
  9360. }
  9361. }
  9362. }
  9363. return texture;
  9364. }
  9365. function onTextureDispose( event ) {
  9366. const texture = event.target;
  9367. texture.removeEventListener( 'dispose', onTextureDispose );
  9368. const cubemap = cubemaps.get( texture );
  9369. if ( cubemap !== undefined ) {
  9370. cubemaps.delete( texture );
  9371. cubemap.dispose();
  9372. }
  9373. }
  9374. function dispose() {
  9375. cubemaps = new WeakMap();
  9376. }
  9377. return {
  9378. get: get,
  9379. dispose: dispose
  9380. };
  9381. }
  9382. class OrthographicCamera extends Camera {
  9383. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9384. super();
  9385. this.isOrthographicCamera = true;
  9386. this.type = 'OrthographicCamera';
  9387. this.zoom = 1;
  9388. this.view = null;
  9389. this.left = left;
  9390. this.right = right;
  9391. this.top = top;
  9392. this.bottom = bottom;
  9393. this.near = near;
  9394. this.far = far;
  9395. this.updateProjectionMatrix();
  9396. }
  9397. copy( source, recursive ) {
  9398. super.copy( source, recursive );
  9399. this.left = source.left;
  9400. this.right = source.right;
  9401. this.top = source.top;
  9402. this.bottom = source.bottom;
  9403. this.near = source.near;
  9404. this.far = source.far;
  9405. this.zoom = source.zoom;
  9406. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9407. return this;
  9408. }
  9409. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9410. if ( this.view === null ) {
  9411. this.view = {
  9412. enabled: true,
  9413. fullWidth: 1,
  9414. fullHeight: 1,
  9415. offsetX: 0,
  9416. offsetY: 0,
  9417. width: 1,
  9418. height: 1
  9419. };
  9420. }
  9421. this.view.enabled = true;
  9422. this.view.fullWidth = fullWidth;
  9423. this.view.fullHeight = fullHeight;
  9424. this.view.offsetX = x;
  9425. this.view.offsetY = y;
  9426. this.view.width = width;
  9427. this.view.height = height;
  9428. this.updateProjectionMatrix();
  9429. }
  9430. clearViewOffset() {
  9431. if ( this.view !== null ) {
  9432. this.view.enabled = false;
  9433. }
  9434. this.updateProjectionMatrix();
  9435. }
  9436. updateProjectionMatrix() {
  9437. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9438. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9439. const cx = ( this.right + this.left ) / 2;
  9440. const cy = ( this.top + this.bottom ) / 2;
  9441. let left = cx - dx;
  9442. let right = cx + dx;
  9443. let top = cy + dy;
  9444. let bottom = cy - dy;
  9445. if ( this.view !== null && this.view.enabled ) {
  9446. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9447. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9448. left += scaleW * this.view.offsetX;
  9449. right = left + scaleW * this.view.width;
  9450. top -= scaleH * this.view.offsetY;
  9451. bottom = top - scaleH * this.view.height;
  9452. }
  9453. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9454. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9455. }
  9456. toJSON( meta ) {
  9457. const data = super.toJSON( meta );
  9458. data.object.zoom = this.zoom;
  9459. data.object.left = this.left;
  9460. data.object.right = this.right;
  9461. data.object.top = this.top;
  9462. data.object.bottom = this.bottom;
  9463. data.object.near = this.near;
  9464. data.object.far = this.far;
  9465. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9466. return data;
  9467. }
  9468. }
  9469. const LOD_MIN = 4;
  9470. // The standard deviations (radians) associated with the extra mips. These are
  9471. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9472. // geometric shadowing function. These sigma values squared must match the
  9473. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9474. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9475. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9476. // samples and exit early, but not recompile the shader.
  9477. const MAX_SAMPLES = 20;
  9478. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9479. const _clearColor = /*@__PURE__*/ new Color();
  9480. let _oldTarget = null;
  9481. // Golden Ratio
  9482. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9483. const INV_PHI = 1 / PHI;
  9484. // Vertices of a dodecahedron (except the opposites, which represent the
  9485. // same axis), used as axis directions evenly spread on a sphere.
  9486. const _axisDirections = [
  9487. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9488. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9489. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9490. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9491. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9492. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9493. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9494. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9495. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9496. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9497. /**
  9498. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9499. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9500. * blur to be quickly accessed based on material roughness. It is packed into a
  9501. * special CubeUV format that allows us to perform custom interpolation so that
  9502. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9503. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9504. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9505. * higher roughness levels. In this way we maintain resolution to smoothly
  9506. * interpolate diffuse lighting while limiting sampling computation.
  9507. *
  9508. * Paper: Fast, Accurate Image-Based Lighting
  9509. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9510. */
  9511. class PMREMGenerator {
  9512. constructor( renderer ) {
  9513. this._renderer = renderer;
  9514. this._pingPongRenderTarget = null;
  9515. this._lodMax = 0;
  9516. this._cubeSize = 0;
  9517. this._lodPlanes = [];
  9518. this._sizeLods = [];
  9519. this._sigmas = [];
  9520. this._blurMaterial = null;
  9521. this._cubemapMaterial = null;
  9522. this._equirectMaterial = null;
  9523. this._compileMaterial( this._blurMaterial );
  9524. }
  9525. /**
  9526. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9527. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9528. * in radians to be applied to the scene before PMREM generation. Optional near
  9529. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9530. * is placed at the origin).
  9531. */
  9532. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9533. _oldTarget = this._renderer.getRenderTarget();
  9534. this._setSize( 256 );
  9535. const cubeUVRenderTarget = this._allocateTargets();
  9536. cubeUVRenderTarget.depthBuffer = true;
  9537. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9538. if ( sigma > 0 ) {
  9539. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9540. }
  9541. this._applyPMREM( cubeUVRenderTarget );
  9542. this._cleanup( cubeUVRenderTarget );
  9543. return cubeUVRenderTarget;
  9544. }
  9545. /**
  9546. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9547. * or HDR. The ideal input image size is 1k (1024 x 512),
  9548. * as this matches best with the 256 x 256 cubemap output.
  9549. */
  9550. fromEquirectangular( equirectangular, renderTarget = null ) {
  9551. return this._fromTexture( equirectangular, renderTarget );
  9552. }
  9553. /**
  9554. * Generates a PMREM from an cubemap texture, which can be either LDR
  9555. * or HDR. The ideal input cube size is 256 x 256,
  9556. * as this matches best with the 256 x 256 cubemap output.
  9557. */
  9558. fromCubemap( cubemap, renderTarget = null ) {
  9559. return this._fromTexture( cubemap, renderTarget );
  9560. }
  9561. /**
  9562. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9563. * your texture's network fetch for increased concurrency.
  9564. */
  9565. compileCubemapShader() {
  9566. if ( this._cubemapMaterial === null ) {
  9567. this._cubemapMaterial = _getCubemapMaterial();
  9568. this._compileMaterial( this._cubemapMaterial );
  9569. }
  9570. }
  9571. /**
  9572. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9573. * your texture's network fetch for increased concurrency.
  9574. */
  9575. compileEquirectangularShader() {
  9576. if ( this._equirectMaterial === null ) {
  9577. this._equirectMaterial = _getEquirectMaterial();
  9578. this._compileMaterial( this._equirectMaterial );
  9579. }
  9580. }
  9581. /**
  9582. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9583. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9584. * one of them will cause any others to also become unusable.
  9585. */
  9586. dispose() {
  9587. this._dispose();
  9588. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9589. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9590. }
  9591. // private interface
  9592. _setSize( cubeSize ) {
  9593. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9594. this._cubeSize = Math.pow( 2, this._lodMax );
  9595. }
  9596. _dispose() {
  9597. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9598. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9599. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9600. this._lodPlanes[ i ].dispose();
  9601. }
  9602. }
  9603. _cleanup( outputTarget ) {
  9604. this._renderer.setRenderTarget( _oldTarget );
  9605. outputTarget.scissorTest = false;
  9606. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9607. }
  9608. _fromTexture( texture, renderTarget ) {
  9609. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9610. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9611. } else { // Equirectangular
  9612. this._setSize( texture.image.width / 4 );
  9613. }
  9614. _oldTarget = this._renderer.getRenderTarget();
  9615. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9616. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9617. this._applyPMREM( cubeUVRenderTarget );
  9618. this._cleanup( cubeUVRenderTarget );
  9619. return cubeUVRenderTarget;
  9620. }
  9621. _allocateTargets() {
  9622. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9623. const height = 4 * this._cubeSize;
  9624. const params = {
  9625. magFilter: LinearFilter,
  9626. minFilter: LinearFilter,
  9627. generateMipmaps: false,
  9628. type: HalfFloatType,
  9629. format: RGBAFormat,
  9630. encoding: LinearEncoding,
  9631. depthBuffer: false
  9632. };
  9633. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9634. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9635. if ( this._pingPongRenderTarget !== null ) {
  9636. this._dispose();
  9637. }
  9638. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9639. const { _lodMax } = this;
  9640. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9641. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9642. }
  9643. return cubeUVRenderTarget;
  9644. }
  9645. _compileMaterial( material ) {
  9646. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9647. this._renderer.compile( tmpMesh, _flatCamera );
  9648. }
  9649. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9650. const fov = 90;
  9651. const aspect = 1;
  9652. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9653. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9654. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9655. const renderer = this._renderer;
  9656. const originalAutoClear = renderer.autoClear;
  9657. const toneMapping = renderer.toneMapping;
  9658. renderer.getClearColor( _clearColor );
  9659. renderer.toneMapping = NoToneMapping;
  9660. renderer.autoClear = false;
  9661. const backgroundMaterial = new MeshBasicMaterial( {
  9662. name: 'PMREM.Background',
  9663. side: BackSide,
  9664. depthWrite: false,
  9665. depthTest: false,
  9666. } );
  9667. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9668. let useSolidColor = false;
  9669. const background = scene.background;
  9670. if ( background ) {
  9671. if ( background.isColor ) {
  9672. backgroundMaterial.color.copy( background );
  9673. scene.background = null;
  9674. useSolidColor = true;
  9675. }
  9676. } else {
  9677. backgroundMaterial.color.copy( _clearColor );
  9678. useSolidColor = true;
  9679. }
  9680. for ( let i = 0; i < 6; i ++ ) {
  9681. const col = i % 3;
  9682. if ( col === 0 ) {
  9683. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9684. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9685. } else if ( col === 1 ) {
  9686. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9687. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9688. } else {
  9689. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9690. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9691. }
  9692. const size = this._cubeSize;
  9693. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9694. renderer.setRenderTarget( cubeUVRenderTarget );
  9695. if ( useSolidColor ) {
  9696. renderer.render( backgroundBox, cubeCamera );
  9697. }
  9698. renderer.render( scene, cubeCamera );
  9699. }
  9700. backgroundBox.geometry.dispose();
  9701. backgroundBox.material.dispose();
  9702. renderer.toneMapping = toneMapping;
  9703. renderer.autoClear = originalAutoClear;
  9704. scene.background = background;
  9705. }
  9706. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9707. const renderer = this._renderer;
  9708. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9709. if ( isCubeTexture ) {
  9710. if ( this._cubemapMaterial === null ) {
  9711. this._cubemapMaterial = _getCubemapMaterial();
  9712. }
  9713. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9714. } else {
  9715. if ( this._equirectMaterial === null ) {
  9716. this._equirectMaterial = _getEquirectMaterial();
  9717. }
  9718. }
  9719. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9720. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9721. const uniforms = material.uniforms;
  9722. uniforms[ 'envMap' ].value = texture;
  9723. const size = this._cubeSize;
  9724. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9725. renderer.setRenderTarget( cubeUVRenderTarget );
  9726. renderer.render( mesh, _flatCamera );
  9727. }
  9728. _applyPMREM( cubeUVRenderTarget ) {
  9729. const renderer = this._renderer;
  9730. const autoClear = renderer.autoClear;
  9731. renderer.autoClear = false;
  9732. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9733. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9734. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9735. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9736. }
  9737. renderer.autoClear = autoClear;
  9738. }
  9739. /**
  9740. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9741. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9742. * the blur latitudinally (around the poles), and then longitudinally (towards
  9743. * the poles) to approximate the orthogonally-separable blur. It is least
  9744. * accurate at the poles, but still does a decent job.
  9745. */
  9746. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9747. const pingPongRenderTarget = this._pingPongRenderTarget;
  9748. this._halfBlur(
  9749. cubeUVRenderTarget,
  9750. pingPongRenderTarget,
  9751. lodIn,
  9752. lodOut,
  9753. sigma,
  9754. 'latitudinal',
  9755. poleAxis );
  9756. this._halfBlur(
  9757. pingPongRenderTarget,
  9758. cubeUVRenderTarget,
  9759. lodOut,
  9760. lodOut,
  9761. sigma,
  9762. 'longitudinal',
  9763. poleAxis );
  9764. }
  9765. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9766. const renderer = this._renderer;
  9767. const blurMaterial = this._blurMaterial;
  9768. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9769. console.error(
  9770. 'blur direction must be either latitudinal or longitudinal!' );
  9771. }
  9772. // Number of standard deviations at which to cut off the discrete approximation.
  9773. const STANDARD_DEVIATIONS = 3;
  9774. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9775. const blurUniforms = blurMaterial.uniforms;
  9776. const pixels = this._sizeLods[ lodIn ] - 1;
  9777. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9778. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9779. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9780. if ( samples > MAX_SAMPLES ) {
  9781. console.warn( `sigmaRadians, ${
  9782. sigmaRadians}, is too large and will clip, as it requested ${
  9783. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9784. }
  9785. const weights = [];
  9786. let sum = 0;
  9787. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9788. const x = i / sigmaPixels;
  9789. const weight = Math.exp( - x * x / 2 );
  9790. weights.push( weight );
  9791. if ( i === 0 ) {
  9792. sum += weight;
  9793. } else if ( i < samples ) {
  9794. sum += 2 * weight;
  9795. }
  9796. }
  9797. for ( let i = 0; i < weights.length; i ++ ) {
  9798. weights[ i ] = weights[ i ] / sum;
  9799. }
  9800. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9801. blurUniforms[ 'samples' ].value = samples;
  9802. blurUniforms[ 'weights' ].value = weights;
  9803. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9804. if ( poleAxis ) {
  9805. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9806. }
  9807. const { _lodMax } = this;
  9808. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9809. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9810. const outputSize = this._sizeLods[ lodOut ];
  9811. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9812. const y = 4 * ( this._cubeSize - outputSize );
  9813. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9814. renderer.setRenderTarget( targetOut );
  9815. renderer.render( blurMesh, _flatCamera );
  9816. }
  9817. }
  9818. function _createPlanes( lodMax ) {
  9819. const lodPlanes = [];
  9820. const sizeLods = [];
  9821. const sigmas = [];
  9822. let lod = lodMax;
  9823. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9824. for ( let i = 0; i < totalLods; i ++ ) {
  9825. const sizeLod = Math.pow( 2, lod );
  9826. sizeLods.push( sizeLod );
  9827. let sigma = 1.0 / sizeLod;
  9828. if ( i > lodMax - LOD_MIN ) {
  9829. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9830. } else if ( i === 0 ) {
  9831. sigma = 0;
  9832. }
  9833. sigmas.push( sigma );
  9834. const texelSize = 1.0 / ( sizeLod - 2 );
  9835. const min = - texelSize;
  9836. const max = 1 + texelSize;
  9837. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9838. const cubeFaces = 6;
  9839. const vertices = 6;
  9840. const positionSize = 3;
  9841. const uvSize = 2;
  9842. const faceIndexSize = 1;
  9843. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9844. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9845. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9846. for ( let face = 0; face < cubeFaces; face ++ ) {
  9847. const x = ( face % 3 ) * 2 / 3 - 1;
  9848. const y = face > 2 ? 0 : - 1;
  9849. const coordinates = [
  9850. x, y, 0,
  9851. x + 2 / 3, y, 0,
  9852. x + 2 / 3, y + 1, 0,
  9853. x, y, 0,
  9854. x + 2 / 3, y + 1, 0,
  9855. x, y + 1, 0
  9856. ];
  9857. position.set( coordinates, positionSize * vertices * face );
  9858. uv.set( uv1, uvSize * vertices * face );
  9859. const fill = [ face, face, face, face, face, face ];
  9860. faceIndex.set( fill, faceIndexSize * vertices * face );
  9861. }
  9862. const planes = new BufferGeometry();
  9863. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9864. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9865. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9866. lodPlanes.push( planes );
  9867. if ( lod > LOD_MIN ) {
  9868. lod --;
  9869. }
  9870. }
  9871. return { lodPlanes, sizeLods, sigmas };
  9872. }
  9873. function _createRenderTarget( width, height, params ) {
  9874. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9875. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9876. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9877. cubeUVRenderTarget.scissorTest = true;
  9878. return cubeUVRenderTarget;
  9879. }
  9880. function _setViewport( target, x, y, width, height ) {
  9881. target.viewport.set( x, y, width, height );
  9882. target.scissor.set( x, y, width, height );
  9883. }
  9884. function _getBlurShader( lodMax, width, height ) {
  9885. const weights = new Float32Array( MAX_SAMPLES );
  9886. const poleAxis = new Vector3( 0, 1, 0 );
  9887. const shaderMaterial = new ShaderMaterial( {
  9888. name: 'SphericalGaussianBlur',
  9889. defines: {
  9890. 'n': MAX_SAMPLES,
  9891. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9892. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9893. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9894. },
  9895. uniforms: {
  9896. 'envMap': { value: null },
  9897. 'samples': { value: 1 },
  9898. 'weights': { value: weights },
  9899. 'latitudinal': { value: false },
  9900. 'dTheta': { value: 0 },
  9901. 'mipInt': { value: 0 },
  9902. 'poleAxis': { value: poleAxis }
  9903. },
  9904. vertexShader: _getCommonVertexShader(),
  9905. fragmentShader: /* glsl */`
  9906. precision mediump float;
  9907. precision mediump int;
  9908. varying vec3 vOutputDirection;
  9909. uniform sampler2D envMap;
  9910. uniform int samples;
  9911. uniform float weights[ n ];
  9912. uniform bool latitudinal;
  9913. uniform float dTheta;
  9914. uniform float mipInt;
  9915. uniform vec3 poleAxis;
  9916. #define ENVMAP_TYPE_CUBE_UV
  9917. #include <cube_uv_reflection_fragment>
  9918. vec3 getSample( float theta, vec3 axis ) {
  9919. float cosTheta = cos( theta );
  9920. // Rodrigues' axis-angle rotation
  9921. vec3 sampleDirection = vOutputDirection * cosTheta
  9922. + cross( axis, vOutputDirection ) * sin( theta )
  9923. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9924. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9925. }
  9926. void main() {
  9927. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9928. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9929. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9930. }
  9931. axis = normalize( axis );
  9932. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9933. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9934. for ( int i = 1; i < n; i++ ) {
  9935. if ( i >= samples ) {
  9936. break;
  9937. }
  9938. float theta = dTheta * float( i );
  9939. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9940. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9941. }
  9942. }
  9943. `,
  9944. blending: NoBlending,
  9945. depthTest: false,
  9946. depthWrite: false
  9947. } );
  9948. return shaderMaterial;
  9949. }
  9950. function _getEquirectMaterial() {
  9951. return new ShaderMaterial( {
  9952. name: 'EquirectangularToCubeUV',
  9953. uniforms: {
  9954. 'envMap': { value: null }
  9955. },
  9956. vertexShader: _getCommonVertexShader(),
  9957. fragmentShader: /* glsl */`
  9958. precision mediump float;
  9959. precision mediump int;
  9960. varying vec3 vOutputDirection;
  9961. uniform sampler2D envMap;
  9962. #include <common>
  9963. void main() {
  9964. vec3 outputDirection = normalize( vOutputDirection );
  9965. vec2 uv = equirectUv( outputDirection );
  9966. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9967. }
  9968. `,
  9969. blending: NoBlending,
  9970. depthTest: false,
  9971. depthWrite: false
  9972. } );
  9973. }
  9974. function _getCubemapMaterial() {
  9975. return new ShaderMaterial( {
  9976. name: 'CubemapToCubeUV',
  9977. uniforms: {
  9978. 'envMap': { value: null },
  9979. 'flipEnvMap': { value: - 1 }
  9980. },
  9981. vertexShader: _getCommonVertexShader(),
  9982. fragmentShader: /* glsl */`
  9983. precision mediump float;
  9984. precision mediump int;
  9985. uniform float flipEnvMap;
  9986. varying vec3 vOutputDirection;
  9987. uniform samplerCube envMap;
  9988. void main() {
  9989. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9990. }
  9991. `,
  9992. blending: NoBlending,
  9993. depthTest: false,
  9994. depthWrite: false
  9995. } );
  9996. }
  9997. function _getCommonVertexShader() {
  9998. return /* glsl */`
  9999. precision mediump float;
  10000. precision mediump int;
  10001. attribute float faceIndex;
  10002. varying vec3 vOutputDirection;
  10003. // RH coordinate system; PMREM face-indexing convention
  10004. vec3 getDirection( vec2 uv, float face ) {
  10005. uv = 2.0 * uv - 1.0;
  10006. vec3 direction = vec3( uv, 1.0 );
  10007. if ( face == 0.0 ) {
  10008. direction = direction.zyx; // ( 1, v, u ) pos x
  10009. } else if ( face == 1.0 ) {
  10010. direction = direction.xzy;
  10011. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10012. } else if ( face == 2.0 ) {
  10013. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10014. } else if ( face == 3.0 ) {
  10015. direction = direction.zyx;
  10016. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10017. } else if ( face == 4.0 ) {
  10018. direction = direction.xzy;
  10019. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10020. } else if ( face == 5.0 ) {
  10021. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10022. }
  10023. return direction;
  10024. }
  10025. void main() {
  10026. vOutputDirection = getDirection( uv, faceIndex );
  10027. gl_Position = vec4( position, 1.0 );
  10028. }
  10029. `;
  10030. }
  10031. function WebGLCubeUVMaps( renderer ) {
  10032. let cubeUVmaps = new WeakMap();
  10033. let pmremGenerator = null;
  10034. function get( texture ) {
  10035. if ( texture && texture.isTexture ) {
  10036. const mapping = texture.mapping;
  10037. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10038. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10039. // equirect/cube map to cubeUV conversion
  10040. if ( isEquirectMap || isCubeMap ) {
  10041. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  10042. texture.needsPMREMUpdate = false;
  10043. let renderTarget = cubeUVmaps.get( texture );
  10044. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10045. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10046. cubeUVmaps.set( texture, renderTarget );
  10047. return renderTarget.texture;
  10048. } else {
  10049. if ( cubeUVmaps.has( texture ) ) {
  10050. return cubeUVmaps.get( texture ).texture;
  10051. } else {
  10052. const image = texture.image;
  10053. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10054. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10055. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10056. cubeUVmaps.set( texture, renderTarget );
  10057. texture.addEventListener( 'dispose', onTextureDispose );
  10058. return renderTarget.texture;
  10059. } else {
  10060. // image not yet ready. try the conversion next frame
  10061. return null;
  10062. }
  10063. }
  10064. }
  10065. }
  10066. }
  10067. return texture;
  10068. }
  10069. function isCubeTextureComplete( image ) {
  10070. let count = 0;
  10071. const length = 6;
  10072. for ( let i = 0; i < length; i ++ ) {
  10073. if ( image[ i ] !== undefined ) count ++;
  10074. }
  10075. return count === length;
  10076. }
  10077. function onTextureDispose( event ) {
  10078. const texture = event.target;
  10079. texture.removeEventListener( 'dispose', onTextureDispose );
  10080. const cubemapUV = cubeUVmaps.get( texture );
  10081. if ( cubemapUV !== undefined ) {
  10082. cubeUVmaps.delete( texture );
  10083. cubemapUV.dispose();
  10084. }
  10085. }
  10086. function dispose() {
  10087. cubeUVmaps = new WeakMap();
  10088. if ( pmremGenerator !== null ) {
  10089. pmremGenerator.dispose();
  10090. pmremGenerator = null;
  10091. }
  10092. }
  10093. return {
  10094. get: get,
  10095. dispose: dispose
  10096. };
  10097. }
  10098. function WebGLExtensions( gl ) {
  10099. const extensions = {};
  10100. function getExtension( name ) {
  10101. if ( extensions[ name ] !== undefined ) {
  10102. return extensions[ name ];
  10103. }
  10104. let extension;
  10105. switch ( name ) {
  10106. case 'WEBGL_depth_texture':
  10107. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10108. break;
  10109. case 'EXT_texture_filter_anisotropic':
  10110. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10111. break;
  10112. case 'WEBGL_compressed_texture_s3tc':
  10113. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10114. break;
  10115. case 'WEBGL_compressed_texture_pvrtc':
  10116. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10117. break;
  10118. default:
  10119. extension = gl.getExtension( name );
  10120. }
  10121. extensions[ name ] = extension;
  10122. return extension;
  10123. }
  10124. return {
  10125. has: function ( name ) {
  10126. return getExtension( name ) !== null;
  10127. },
  10128. init: function ( capabilities ) {
  10129. if ( capabilities.isWebGL2 ) {
  10130. getExtension( 'EXT_color_buffer_float' );
  10131. } else {
  10132. getExtension( 'WEBGL_depth_texture' );
  10133. getExtension( 'OES_texture_float' );
  10134. getExtension( 'OES_texture_half_float' );
  10135. getExtension( 'OES_texture_half_float_linear' );
  10136. getExtension( 'OES_standard_derivatives' );
  10137. getExtension( 'OES_element_index_uint' );
  10138. getExtension( 'OES_vertex_array_object' );
  10139. getExtension( 'ANGLE_instanced_arrays' );
  10140. }
  10141. getExtension( 'OES_texture_float_linear' );
  10142. getExtension( 'EXT_color_buffer_half_float' );
  10143. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10144. },
  10145. get: function ( name ) {
  10146. const extension = getExtension( name );
  10147. if ( extension === null ) {
  10148. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10149. }
  10150. return extension;
  10151. }
  10152. };
  10153. }
  10154. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10155. const geometries = {};
  10156. const wireframeAttributes = new WeakMap();
  10157. function onGeometryDispose( event ) {
  10158. const geometry = event.target;
  10159. if ( geometry.index !== null ) {
  10160. attributes.remove( geometry.index );
  10161. }
  10162. for ( const name in geometry.attributes ) {
  10163. attributes.remove( geometry.attributes[ name ] );
  10164. }
  10165. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10166. delete geometries[ geometry.id ];
  10167. const attribute = wireframeAttributes.get( geometry );
  10168. if ( attribute ) {
  10169. attributes.remove( attribute );
  10170. wireframeAttributes.delete( geometry );
  10171. }
  10172. bindingStates.releaseStatesOfGeometry( geometry );
  10173. if ( geometry.isInstancedBufferGeometry === true ) {
  10174. delete geometry._maxInstanceCount;
  10175. }
  10176. //
  10177. info.memory.geometries --;
  10178. }
  10179. function get( object, geometry ) {
  10180. if ( geometries[ geometry.id ] === true ) return geometry;
  10181. geometry.addEventListener( 'dispose', onGeometryDispose );
  10182. geometries[ geometry.id ] = true;
  10183. info.memory.geometries ++;
  10184. return geometry;
  10185. }
  10186. function update( geometry ) {
  10187. const geometryAttributes = geometry.attributes;
  10188. // Updating index buffer in VAO now. See WebGLBindingStates.
  10189. for ( const name in geometryAttributes ) {
  10190. attributes.update( geometryAttributes[ name ], 34962 );
  10191. }
  10192. // morph targets
  10193. const morphAttributes = geometry.morphAttributes;
  10194. for ( const name in morphAttributes ) {
  10195. const array = morphAttributes[ name ];
  10196. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10197. attributes.update( array[ i ], 34962 );
  10198. }
  10199. }
  10200. }
  10201. function updateWireframeAttribute( geometry ) {
  10202. const indices = [];
  10203. const geometryIndex = geometry.index;
  10204. const geometryPosition = geometry.attributes.position;
  10205. let version = 0;
  10206. if ( geometryIndex !== null ) {
  10207. const array = geometryIndex.array;
  10208. version = geometryIndex.version;
  10209. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10210. const a = array[ i + 0 ];
  10211. const b = array[ i + 1 ];
  10212. const c = array[ i + 2 ];
  10213. indices.push( a, b, b, c, c, a );
  10214. }
  10215. } else {
  10216. const array = geometryPosition.array;
  10217. version = geometryPosition.version;
  10218. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10219. const a = i + 0;
  10220. const b = i + 1;
  10221. const c = i + 2;
  10222. indices.push( a, b, b, c, c, a );
  10223. }
  10224. }
  10225. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10226. attribute.version = version;
  10227. // Updating index buffer in VAO now. See WebGLBindingStates
  10228. //
  10229. const previousAttribute = wireframeAttributes.get( geometry );
  10230. if ( previousAttribute ) attributes.remove( previousAttribute );
  10231. //
  10232. wireframeAttributes.set( geometry, attribute );
  10233. }
  10234. function getWireframeAttribute( geometry ) {
  10235. const currentAttribute = wireframeAttributes.get( geometry );
  10236. if ( currentAttribute ) {
  10237. const geometryIndex = geometry.index;
  10238. if ( geometryIndex !== null ) {
  10239. // if the attribute is obsolete, create a new one
  10240. if ( currentAttribute.version < geometryIndex.version ) {
  10241. updateWireframeAttribute( geometry );
  10242. }
  10243. }
  10244. } else {
  10245. updateWireframeAttribute( geometry );
  10246. }
  10247. return wireframeAttributes.get( geometry );
  10248. }
  10249. return {
  10250. get: get,
  10251. update: update,
  10252. getWireframeAttribute: getWireframeAttribute
  10253. };
  10254. }
  10255. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10256. const isWebGL2 = capabilities.isWebGL2;
  10257. let mode;
  10258. function setMode( value ) {
  10259. mode = value;
  10260. }
  10261. let type, bytesPerElement;
  10262. function setIndex( value ) {
  10263. type = value.type;
  10264. bytesPerElement = value.bytesPerElement;
  10265. }
  10266. function render( start, count ) {
  10267. gl.drawElements( mode, count, type, start * bytesPerElement );
  10268. info.update( count, mode, 1 );
  10269. }
  10270. function renderInstances( start, count, primcount ) {
  10271. if ( primcount === 0 ) return;
  10272. let extension, methodName;
  10273. if ( isWebGL2 ) {
  10274. extension = gl;
  10275. methodName = 'drawElementsInstanced';
  10276. } else {
  10277. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10278. methodName = 'drawElementsInstancedANGLE';
  10279. if ( extension === null ) {
  10280. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10281. return;
  10282. }
  10283. }
  10284. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10285. info.update( count, mode, primcount );
  10286. }
  10287. //
  10288. this.setMode = setMode;
  10289. this.setIndex = setIndex;
  10290. this.render = render;
  10291. this.renderInstances = renderInstances;
  10292. }
  10293. function WebGLInfo( gl ) {
  10294. const memory = {
  10295. geometries: 0,
  10296. textures: 0
  10297. };
  10298. const render = {
  10299. frame: 0,
  10300. calls: 0,
  10301. triangles: 0,
  10302. points: 0,
  10303. lines: 0
  10304. };
  10305. function update( count, mode, instanceCount ) {
  10306. render.calls ++;
  10307. switch ( mode ) {
  10308. case 4:
  10309. render.triangles += instanceCount * ( count / 3 );
  10310. break;
  10311. case 1:
  10312. render.lines += instanceCount * ( count / 2 );
  10313. break;
  10314. case 3:
  10315. render.lines += instanceCount * ( count - 1 );
  10316. break;
  10317. case 2:
  10318. render.lines += instanceCount * count;
  10319. break;
  10320. case 0:
  10321. render.points += instanceCount * count;
  10322. break;
  10323. default:
  10324. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10325. break;
  10326. }
  10327. }
  10328. function reset() {
  10329. render.frame ++;
  10330. render.calls = 0;
  10331. render.triangles = 0;
  10332. render.points = 0;
  10333. render.lines = 0;
  10334. }
  10335. return {
  10336. memory: memory,
  10337. render: render,
  10338. programs: null,
  10339. autoReset: true,
  10340. reset: reset,
  10341. update: update
  10342. };
  10343. }
  10344. function numericalSort( a, b ) {
  10345. return a[ 0 ] - b[ 0 ];
  10346. }
  10347. function absNumericalSort( a, b ) {
  10348. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10349. }
  10350. function WebGLMorphtargets( gl, capabilities, textures ) {
  10351. const influencesList = {};
  10352. const morphInfluences = new Float32Array( 8 );
  10353. const morphTextures = new WeakMap();
  10354. const morph = new Vector4();
  10355. const workInfluences = [];
  10356. for ( let i = 0; i < 8; i ++ ) {
  10357. workInfluences[ i ] = [ i, 0 ];
  10358. }
  10359. function update( object, geometry, program ) {
  10360. const objectInfluences = object.morphTargetInfluences;
  10361. if ( capabilities.isWebGL2 === true ) {
  10362. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10363. // into an array of data textures. Each layer represents a single morph target.
  10364. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10365. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10366. let entry = morphTextures.get( geometry );
  10367. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10368. if ( entry !== undefined ) entry.texture.dispose();
  10369. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10370. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10371. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10372. const morphTargets = geometry.morphAttributes.position || [];
  10373. const morphNormals = geometry.morphAttributes.normal || [];
  10374. const morphColors = geometry.morphAttributes.color || [];
  10375. let vertexDataCount = 0;
  10376. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10377. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10378. if ( hasMorphColors === true ) vertexDataCount = 3;
  10379. let width = geometry.attributes.position.count * vertexDataCount;
  10380. let height = 1;
  10381. if ( width > capabilities.maxTextureSize ) {
  10382. height = Math.ceil( width / capabilities.maxTextureSize );
  10383. width = capabilities.maxTextureSize;
  10384. }
  10385. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10386. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10387. texture.type = FloatType;
  10388. texture.needsUpdate = true;
  10389. // fill buffer
  10390. const vertexDataStride = vertexDataCount * 4;
  10391. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10392. const morphTarget = morphTargets[ i ];
  10393. const morphNormal = morphNormals[ i ];
  10394. const morphColor = morphColors[ i ];
  10395. const offset = width * height * 4 * i;
  10396. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10397. const stride = j * vertexDataStride;
  10398. if ( hasMorphPosition === true ) {
  10399. morph.fromBufferAttribute( morphTarget, j );
  10400. buffer[ offset + stride + 0 ] = morph.x;
  10401. buffer[ offset + stride + 1 ] = morph.y;
  10402. buffer[ offset + stride + 2 ] = morph.z;
  10403. buffer[ offset + stride + 3 ] = 0;
  10404. }
  10405. if ( hasMorphNormals === true ) {
  10406. morph.fromBufferAttribute( morphNormal, j );
  10407. buffer[ offset + stride + 4 ] = morph.x;
  10408. buffer[ offset + stride + 5 ] = morph.y;
  10409. buffer[ offset + stride + 6 ] = morph.z;
  10410. buffer[ offset + stride + 7 ] = 0;
  10411. }
  10412. if ( hasMorphColors === true ) {
  10413. morph.fromBufferAttribute( morphColor, j );
  10414. buffer[ offset + stride + 8 ] = morph.x;
  10415. buffer[ offset + stride + 9 ] = morph.y;
  10416. buffer[ offset + stride + 10 ] = morph.z;
  10417. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10418. }
  10419. }
  10420. }
  10421. entry = {
  10422. count: morphTargetsCount,
  10423. texture: texture,
  10424. size: new Vector2( width, height )
  10425. };
  10426. morphTextures.set( geometry, entry );
  10427. function disposeTexture() {
  10428. texture.dispose();
  10429. morphTextures.delete( geometry );
  10430. geometry.removeEventListener( 'dispose', disposeTexture );
  10431. }
  10432. geometry.addEventListener( 'dispose', disposeTexture );
  10433. }
  10434. //
  10435. let morphInfluencesSum = 0;
  10436. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10437. morphInfluencesSum += objectInfluences[ i ];
  10438. }
  10439. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10440. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10441. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10442. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10443. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10444. } else {
  10445. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10446. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10447. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10448. let influences = influencesList[ geometry.id ];
  10449. if ( influences === undefined || influences.length !== length ) {
  10450. // initialise list
  10451. influences = [];
  10452. for ( let i = 0; i < length; i ++ ) {
  10453. influences[ i ] = [ i, 0 ];
  10454. }
  10455. influencesList[ geometry.id ] = influences;
  10456. }
  10457. // Collect influences
  10458. for ( let i = 0; i < length; i ++ ) {
  10459. const influence = influences[ i ];
  10460. influence[ 0 ] = i;
  10461. influence[ 1 ] = objectInfluences[ i ];
  10462. }
  10463. influences.sort( absNumericalSort );
  10464. for ( let i = 0; i < 8; i ++ ) {
  10465. if ( i < length && influences[ i ][ 1 ] ) {
  10466. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10467. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10468. } else {
  10469. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10470. workInfluences[ i ][ 1 ] = 0;
  10471. }
  10472. }
  10473. workInfluences.sort( numericalSort );
  10474. const morphTargets = geometry.morphAttributes.position;
  10475. const morphNormals = geometry.morphAttributes.normal;
  10476. let morphInfluencesSum = 0;
  10477. for ( let i = 0; i < 8; i ++ ) {
  10478. const influence = workInfluences[ i ];
  10479. const index = influence[ 0 ];
  10480. const value = influence[ 1 ];
  10481. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10482. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10483. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10484. }
  10485. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10486. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10487. }
  10488. morphInfluences[ i ] = value;
  10489. morphInfluencesSum += value;
  10490. } else {
  10491. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10492. geometry.deleteAttribute( 'morphTarget' + i );
  10493. }
  10494. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10495. geometry.deleteAttribute( 'morphNormal' + i );
  10496. }
  10497. morphInfluences[ i ] = 0;
  10498. }
  10499. }
  10500. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10501. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10502. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10503. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10504. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10505. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10506. }
  10507. }
  10508. return {
  10509. update: update
  10510. };
  10511. }
  10512. function WebGLObjects( gl, geometries, attributes, info ) {
  10513. let updateMap = new WeakMap();
  10514. function update( object ) {
  10515. const frame = info.render.frame;
  10516. const geometry = object.geometry;
  10517. const buffergeometry = geometries.get( object, geometry );
  10518. // Update once per frame
  10519. if ( updateMap.get( buffergeometry ) !== frame ) {
  10520. geometries.update( buffergeometry );
  10521. updateMap.set( buffergeometry, frame );
  10522. }
  10523. if ( object.isInstancedMesh ) {
  10524. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10525. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10526. }
  10527. attributes.update( object.instanceMatrix, 34962 );
  10528. if ( object.instanceColor !== null ) {
  10529. attributes.update( object.instanceColor, 34962 );
  10530. }
  10531. }
  10532. return buffergeometry;
  10533. }
  10534. function dispose() {
  10535. updateMap = new WeakMap();
  10536. }
  10537. function onInstancedMeshDispose( event ) {
  10538. const instancedMesh = event.target;
  10539. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10540. attributes.remove( instancedMesh.instanceMatrix );
  10541. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10542. }
  10543. return {
  10544. update: update,
  10545. dispose: dispose
  10546. };
  10547. }
  10548. /**
  10549. * Uniforms of a program.
  10550. * Those form a tree structure with a special top-level container for the root,
  10551. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10552. *
  10553. *
  10554. * Properties of inner nodes including the top-level container:
  10555. *
  10556. * .seq - array of nested uniforms
  10557. * .map - nested uniforms by name
  10558. *
  10559. *
  10560. * Methods of all nodes except the top-level container:
  10561. *
  10562. * .setValue( gl, value, [textures] )
  10563. *
  10564. * uploads a uniform value(s)
  10565. * the 'textures' parameter is needed for sampler uniforms
  10566. *
  10567. *
  10568. * Static methods of the top-level container (textures factorizations):
  10569. *
  10570. * .upload( gl, seq, values, textures )
  10571. *
  10572. * sets uniforms in 'seq' to 'values[id].value'
  10573. *
  10574. * .seqWithValue( seq, values ) : filteredSeq
  10575. *
  10576. * filters 'seq' entries with corresponding entry in values
  10577. *
  10578. *
  10579. * Methods of the top-level container (textures factorizations):
  10580. *
  10581. * .setValue( gl, name, value, textures )
  10582. *
  10583. * sets uniform with name 'name' to 'value'
  10584. *
  10585. * .setOptional( gl, obj, prop )
  10586. *
  10587. * like .set for an optional property of the object
  10588. *
  10589. */
  10590. const emptyTexture = /*@__PURE__*/ new Texture();
  10591. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10592. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10593. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10594. // --- Utilities ---
  10595. // Array Caches (provide typed arrays for temporary by size)
  10596. const arrayCacheF32 = [];
  10597. const arrayCacheI32 = [];
  10598. // Float32Array caches used for uploading Matrix uniforms
  10599. const mat4array = new Float32Array( 16 );
  10600. const mat3array = new Float32Array( 9 );
  10601. const mat2array = new Float32Array( 4 );
  10602. // Flattening for arrays of vectors and matrices
  10603. function flatten( array, nBlocks, blockSize ) {
  10604. const firstElem = array[ 0 ];
  10605. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10606. // unoptimized: ! isNaN( firstElem )
  10607. // see http://jacksondunstan.com/articles/983
  10608. const n = nBlocks * blockSize;
  10609. let r = arrayCacheF32[ n ];
  10610. if ( r === undefined ) {
  10611. r = new Float32Array( n );
  10612. arrayCacheF32[ n ] = r;
  10613. }
  10614. if ( nBlocks !== 0 ) {
  10615. firstElem.toArray( r, 0 );
  10616. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10617. offset += blockSize;
  10618. array[ i ].toArray( r, offset );
  10619. }
  10620. }
  10621. return r;
  10622. }
  10623. function arraysEqual( a, b ) {
  10624. if ( a.length !== b.length ) return false;
  10625. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10626. if ( a[ i ] !== b[ i ] ) return false;
  10627. }
  10628. return true;
  10629. }
  10630. function copyArray( a, b ) {
  10631. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10632. a[ i ] = b[ i ];
  10633. }
  10634. }
  10635. // Texture unit allocation
  10636. function allocTexUnits( textures, n ) {
  10637. let r = arrayCacheI32[ n ];
  10638. if ( r === undefined ) {
  10639. r = new Int32Array( n );
  10640. arrayCacheI32[ n ] = r;
  10641. }
  10642. for ( let i = 0; i !== n; ++ i ) {
  10643. r[ i ] = textures.allocateTextureUnit();
  10644. }
  10645. return r;
  10646. }
  10647. // --- Setters ---
  10648. // Note: Defining these methods externally, because they come in a bunch
  10649. // and this way their names minify.
  10650. // Single scalar
  10651. function setValueV1f( gl, v ) {
  10652. const cache = this.cache;
  10653. if ( cache[ 0 ] === v ) return;
  10654. gl.uniform1f( this.addr, v );
  10655. cache[ 0 ] = v;
  10656. }
  10657. // Single float vector (from flat array or THREE.VectorN)
  10658. function setValueV2f( gl, v ) {
  10659. const cache = this.cache;
  10660. if ( v.x !== undefined ) {
  10661. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10662. gl.uniform2f( this.addr, v.x, v.y );
  10663. cache[ 0 ] = v.x;
  10664. cache[ 1 ] = v.y;
  10665. }
  10666. } else {
  10667. if ( arraysEqual( cache, v ) ) return;
  10668. gl.uniform2fv( this.addr, v );
  10669. copyArray( cache, v );
  10670. }
  10671. }
  10672. function setValueV3f( gl, v ) {
  10673. const cache = this.cache;
  10674. if ( v.x !== undefined ) {
  10675. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10676. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10677. cache[ 0 ] = v.x;
  10678. cache[ 1 ] = v.y;
  10679. cache[ 2 ] = v.z;
  10680. }
  10681. } else if ( v.r !== undefined ) {
  10682. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10683. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10684. cache[ 0 ] = v.r;
  10685. cache[ 1 ] = v.g;
  10686. cache[ 2 ] = v.b;
  10687. }
  10688. } else {
  10689. if ( arraysEqual( cache, v ) ) return;
  10690. gl.uniform3fv( this.addr, v );
  10691. copyArray( cache, v );
  10692. }
  10693. }
  10694. function setValueV4f( gl, v ) {
  10695. const cache = this.cache;
  10696. if ( v.x !== undefined ) {
  10697. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10698. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10699. cache[ 0 ] = v.x;
  10700. cache[ 1 ] = v.y;
  10701. cache[ 2 ] = v.z;
  10702. cache[ 3 ] = v.w;
  10703. }
  10704. } else {
  10705. if ( arraysEqual( cache, v ) ) return;
  10706. gl.uniform4fv( this.addr, v );
  10707. copyArray( cache, v );
  10708. }
  10709. }
  10710. // Single matrix (from flat array or THREE.MatrixN)
  10711. function setValueM2( gl, v ) {
  10712. const cache = this.cache;
  10713. const elements = v.elements;
  10714. if ( elements === undefined ) {
  10715. if ( arraysEqual( cache, v ) ) return;
  10716. gl.uniformMatrix2fv( this.addr, false, v );
  10717. copyArray( cache, v );
  10718. } else {
  10719. if ( arraysEqual( cache, elements ) ) return;
  10720. mat2array.set( elements );
  10721. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10722. copyArray( cache, elements );
  10723. }
  10724. }
  10725. function setValueM3( gl, v ) {
  10726. const cache = this.cache;
  10727. const elements = v.elements;
  10728. if ( elements === undefined ) {
  10729. if ( arraysEqual( cache, v ) ) return;
  10730. gl.uniformMatrix3fv( this.addr, false, v );
  10731. copyArray( cache, v );
  10732. } else {
  10733. if ( arraysEqual( cache, elements ) ) return;
  10734. mat3array.set( elements );
  10735. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10736. copyArray( cache, elements );
  10737. }
  10738. }
  10739. function setValueM4( gl, v ) {
  10740. const cache = this.cache;
  10741. const elements = v.elements;
  10742. if ( elements === undefined ) {
  10743. if ( arraysEqual( cache, v ) ) return;
  10744. gl.uniformMatrix4fv( this.addr, false, v );
  10745. copyArray( cache, v );
  10746. } else {
  10747. if ( arraysEqual( cache, elements ) ) return;
  10748. mat4array.set( elements );
  10749. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10750. copyArray( cache, elements );
  10751. }
  10752. }
  10753. // Single integer / boolean
  10754. function setValueV1i( gl, v ) {
  10755. const cache = this.cache;
  10756. if ( cache[ 0 ] === v ) return;
  10757. gl.uniform1i( this.addr, v );
  10758. cache[ 0 ] = v;
  10759. }
  10760. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10761. function setValueV2i( gl, v ) {
  10762. const cache = this.cache;
  10763. if ( v.x !== undefined ) {
  10764. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10765. gl.uniform2i( this.addr, v.x, v.y );
  10766. cache[ 0 ] = v.x;
  10767. cache[ 1 ] = v.y;
  10768. }
  10769. } else {
  10770. if ( arraysEqual( cache, v ) ) return;
  10771. gl.uniform2iv( this.addr, v );
  10772. copyArray( cache, v );
  10773. }
  10774. }
  10775. function setValueV3i( gl, v ) {
  10776. const cache = this.cache;
  10777. if ( v.x !== undefined ) {
  10778. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10779. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10780. cache[ 0 ] = v.x;
  10781. cache[ 1 ] = v.y;
  10782. cache[ 2 ] = v.z;
  10783. }
  10784. } else {
  10785. if ( arraysEqual( cache, v ) ) return;
  10786. gl.uniform3iv( this.addr, v );
  10787. copyArray( cache, v );
  10788. }
  10789. }
  10790. function setValueV4i( gl, v ) {
  10791. const cache = this.cache;
  10792. if ( v.x !== undefined ) {
  10793. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10794. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  10795. cache[ 0 ] = v.x;
  10796. cache[ 1 ] = v.y;
  10797. cache[ 2 ] = v.z;
  10798. cache[ 3 ] = v.w;
  10799. }
  10800. } else {
  10801. if ( arraysEqual( cache, v ) ) return;
  10802. gl.uniform4iv( this.addr, v );
  10803. copyArray( cache, v );
  10804. }
  10805. }
  10806. // Single unsigned integer
  10807. function setValueV1ui( gl, v ) {
  10808. const cache = this.cache;
  10809. if ( cache[ 0 ] === v ) return;
  10810. gl.uniform1ui( this.addr, v );
  10811. cache[ 0 ] = v;
  10812. }
  10813. // Single unsigned integer vector (from flat array or THREE.VectorN)
  10814. function setValueV2ui( gl, v ) {
  10815. const cache = this.cache;
  10816. if ( v.x !== undefined ) {
  10817. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10818. gl.uniform2ui( this.addr, v.x, v.y );
  10819. cache[ 0 ] = v.x;
  10820. cache[ 1 ] = v.y;
  10821. }
  10822. } else {
  10823. if ( arraysEqual( cache, v ) ) return;
  10824. gl.uniform2uiv( this.addr, v );
  10825. copyArray( cache, v );
  10826. }
  10827. }
  10828. function setValueV3ui( gl, v ) {
  10829. const cache = this.cache;
  10830. if ( v.x !== undefined ) {
  10831. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10832. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  10833. cache[ 0 ] = v.x;
  10834. cache[ 1 ] = v.y;
  10835. cache[ 2 ] = v.z;
  10836. }
  10837. } else {
  10838. if ( arraysEqual( cache, v ) ) return;
  10839. gl.uniform3uiv( this.addr, v );
  10840. copyArray( cache, v );
  10841. }
  10842. }
  10843. function setValueV4ui( gl, v ) {
  10844. const cache = this.cache;
  10845. if ( v.x !== undefined ) {
  10846. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10847. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  10848. cache[ 0 ] = v.x;
  10849. cache[ 1 ] = v.y;
  10850. cache[ 2 ] = v.z;
  10851. cache[ 3 ] = v.w;
  10852. }
  10853. } else {
  10854. if ( arraysEqual( cache, v ) ) return;
  10855. gl.uniform4uiv( this.addr, v );
  10856. copyArray( cache, v );
  10857. }
  10858. }
  10859. // Single texture (2D / Cube)
  10860. function setValueT1( gl, v, textures ) {
  10861. const cache = this.cache;
  10862. const unit = textures.allocateTextureUnit();
  10863. if ( cache[ 0 ] !== unit ) {
  10864. gl.uniform1i( this.addr, unit );
  10865. cache[ 0 ] = unit;
  10866. }
  10867. textures.setTexture2D( v || emptyTexture, unit );
  10868. }
  10869. function setValueT3D1( gl, v, textures ) {
  10870. const cache = this.cache;
  10871. const unit = textures.allocateTextureUnit();
  10872. if ( cache[ 0 ] !== unit ) {
  10873. gl.uniform1i( this.addr, unit );
  10874. cache[ 0 ] = unit;
  10875. }
  10876. textures.setTexture3D( v || empty3dTexture, unit );
  10877. }
  10878. function setValueT6( gl, v, textures ) {
  10879. const cache = this.cache;
  10880. const unit = textures.allocateTextureUnit();
  10881. if ( cache[ 0 ] !== unit ) {
  10882. gl.uniform1i( this.addr, unit );
  10883. cache[ 0 ] = unit;
  10884. }
  10885. textures.setTextureCube( v || emptyCubeTexture, unit );
  10886. }
  10887. function setValueT2DArray1( gl, v, textures ) {
  10888. const cache = this.cache;
  10889. const unit = textures.allocateTextureUnit();
  10890. if ( cache[ 0 ] !== unit ) {
  10891. gl.uniform1i( this.addr, unit );
  10892. cache[ 0 ] = unit;
  10893. }
  10894. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10895. }
  10896. // Helper to pick the right setter for the singular case
  10897. function getSingularSetter( type ) {
  10898. switch ( type ) {
  10899. case 0x1406: return setValueV1f; // FLOAT
  10900. case 0x8b50: return setValueV2f; // _VEC2
  10901. case 0x8b51: return setValueV3f; // _VEC3
  10902. case 0x8b52: return setValueV4f; // _VEC4
  10903. case 0x8b5a: return setValueM2; // _MAT2
  10904. case 0x8b5b: return setValueM3; // _MAT3
  10905. case 0x8b5c: return setValueM4; // _MAT4
  10906. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10907. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10908. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10909. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10910. case 0x1405: return setValueV1ui; // UINT
  10911. case 0x8dc6: return setValueV2ui; // _VEC2
  10912. case 0x8dc7: return setValueV3ui; // _VEC3
  10913. case 0x8dc8: return setValueV4ui; // _VEC4
  10914. case 0x8b5e: // SAMPLER_2D
  10915. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10916. case 0x8dca: // INT_SAMPLER_2D
  10917. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10918. case 0x8b62: // SAMPLER_2D_SHADOW
  10919. return setValueT1;
  10920. case 0x8b5f: // SAMPLER_3D
  10921. case 0x8dcb: // INT_SAMPLER_3D
  10922. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10923. return setValueT3D1;
  10924. case 0x8b60: // SAMPLER_CUBE
  10925. case 0x8dcc: // INT_SAMPLER_CUBE
  10926. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10927. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10928. return setValueT6;
  10929. case 0x8dc1: // SAMPLER_2D_ARRAY
  10930. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10931. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10932. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10933. return setValueT2DArray1;
  10934. }
  10935. }
  10936. // Array of scalars
  10937. function setValueV1fArray( gl, v ) {
  10938. gl.uniform1fv( this.addr, v );
  10939. }
  10940. // Array of vectors (from flat array or array of THREE.VectorN)
  10941. function setValueV2fArray( gl, v ) {
  10942. const data = flatten( v, this.size, 2 );
  10943. gl.uniform2fv( this.addr, data );
  10944. }
  10945. function setValueV3fArray( gl, v ) {
  10946. const data = flatten( v, this.size, 3 );
  10947. gl.uniform3fv( this.addr, data );
  10948. }
  10949. function setValueV4fArray( gl, v ) {
  10950. const data = flatten( v, this.size, 4 );
  10951. gl.uniform4fv( this.addr, data );
  10952. }
  10953. // Array of matrices (from flat array or array of THREE.MatrixN)
  10954. function setValueM2Array( gl, v ) {
  10955. const data = flatten( v, this.size, 4 );
  10956. gl.uniformMatrix2fv( this.addr, false, data );
  10957. }
  10958. function setValueM3Array( gl, v ) {
  10959. const data = flatten( v, this.size, 9 );
  10960. gl.uniformMatrix3fv( this.addr, false, data );
  10961. }
  10962. function setValueM4Array( gl, v ) {
  10963. const data = flatten( v, this.size, 16 );
  10964. gl.uniformMatrix4fv( this.addr, false, data );
  10965. }
  10966. // Array of integer / boolean
  10967. function setValueV1iArray( gl, v ) {
  10968. gl.uniform1iv( this.addr, v );
  10969. }
  10970. // Array of integer / boolean vectors (from flat array)
  10971. function setValueV2iArray( gl, v ) {
  10972. gl.uniform2iv( this.addr, v );
  10973. }
  10974. function setValueV3iArray( gl, v ) {
  10975. gl.uniform3iv( this.addr, v );
  10976. }
  10977. function setValueV4iArray( gl, v ) {
  10978. gl.uniform4iv( this.addr, v );
  10979. }
  10980. // Array of unsigned integer
  10981. function setValueV1uiArray( gl, v ) {
  10982. gl.uniform1uiv( this.addr, v );
  10983. }
  10984. // Array of unsigned integer vectors (from flat array)
  10985. function setValueV2uiArray( gl, v ) {
  10986. gl.uniform2uiv( this.addr, v );
  10987. }
  10988. function setValueV3uiArray( gl, v ) {
  10989. gl.uniform3uiv( this.addr, v );
  10990. }
  10991. function setValueV4uiArray( gl, v ) {
  10992. gl.uniform4uiv( this.addr, v );
  10993. }
  10994. // Array of textures (2D / 3D / Cube / 2DArray)
  10995. function setValueT1Array( gl, v, textures ) {
  10996. const cache = this.cache;
  10997. const n = v.length;
  10998. const units = allocTexUnits( textures, n );
  10999. if ( ! arraysEqual( cache, units ) ) {
  11000. gl.uniform1iv( this.addr, units );
  11001. copyArray( cache, units );
  11002. }
  11003. for ( let i = 0; i !== n; ++ i ) {
  11004. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11005. }
  11006. }
  11007. function setValueT3DArray( gl, v, textures ) {
  11008. const cache = this.cache;
  11009. const n = v.length;
  11010. const units = allocTexUnits( textures, n );
  11011. if ( ! arraysEqual( cache, units ) ) {
  11012. gl.uniform1iv( this.addr, units );
  11013. copyArray( cache, units );
  11014. }
  11015. for ( let i = 0; i !== n; ++ i ) {
  11016. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11017. }
  11018. }
  11019. function setValueT6Array( gl, v, textures ) {
  11020. const cache = this.cache;
  11021. const n = v.length;
  11022. const units = allocTexUnits( textures, n );
  11023. if ( ! arraysEqual( cache, units ) ) {
  11024. gl.uniform1iv( this.addr, units );
  11025. copyArray( cache, units );
  11026. }
  11027. for ( let i = 0; i !== n; ++ i ) {
  11028. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11029. }
  11030. }
  11031. function setValueT2DArrayArray( gl, v, textures ) {
  11032. const cache = this.cache;
  11033. const n = v.length;
  11034. const units = allocTexUnits( textures, n );
  11035. if ( ! arraysEqual( cache, units ) ) {
  11036. gl.uniform1iv( this.addr, units );
  11037. copyArray( cache, units );
  11038. }
  11039. for ( let i = 0; i !== n; ++ i ) {
  11040. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11041. }
  11042. }
  11043. // Helper to pick the right setter for a pure (bottom-level) array
  11044. function getPureArraySetter( type ) {
  11045. switch ( type ) {
  11046. case 0x1406: return setValueV1fArray; // FLOAT
  11047. case 0x8b50: return setValueV2fArray; // _VEC2
  11048. case 0x8b51: return setValueV3fArray; // _VEC3
  11049. case 0x8b52: return setValueV4fArray; // _VEC4
  11050. case 0x8b5a: return setValueM2Array; // _MAT2
  11051. case 0x8b5b: return setValueM3Array; // _MAT3
  11052. case 0x8b5c: return setValueM4Array; // _MAT4
  11053. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11054. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11055. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11056. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11057. case 0x1405: return setValueV1uiArray; // UINT
  11058. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11059. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11060. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11061. case 0x8b5e: // SAMPLER_2D
  11062. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11063. case 0x8dca: // INT_SAMPLER_2D
  11064. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11065. case 0x8b62: // SAMPLER_2D_SHADOW
  11066. return setValueT1Array;
  11067. case 0x8b5f: // SAMPLER_3D
  11068. case 0x8dcb: // INT_SAMPLER_3D
  11069. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11070. return setValueT3DArray;
  11071. case 0x8b60: // SAMPLER_CUBE
  11072. case 0x8dcc: // INT_SAMPLER_CUBE
  11073. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11074. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11075. return setValueT6Array;
  11076. case 0x8dc1: // SAMPLER_2D_ARRAY
  11077. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11078. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11079. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11080. return setValueT2DArrayArray;
  11081. }
  11082. }
  11083. // --- Uniform Classes ---
  11084. class SingleUniform {
  11085. constructor( id, activeInfo, addr ) {
  11086. this.id = id;
  11087. this.addr = addr;
  11088. this.cache = [];
  11089. this.setValue = getSingularSetter( activeInfo.type );
  11090. // this.path = activeInfo.name; // DEBUG
  11091. }
  11092. }
  11093. class PureArrayUniform {
  11094. constructor( id, activeInfo, addr ) {
  11095. this.id = id;
  11096. this.addr = addr;
  11097. this.cache = [];
  11098. this.size = activeInfo.size;
  11099. this.setValue = getPureArraySetter( activeInfo.type );
  11100. // this.path = activeInfo.name; // DEBUG
  11101. }
  11102. }
  11103. class StructuredUniform {
  11104. constructor( id ) {
  11105. this.id = id;
  11106. this.seq = [];
  11107. this.map = {};
  11108. }
  11109. setValue( gl, value, textures ) {
  11110. const seq = this.seq;
  11111. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11112. const u = seq[ i ];
  11113. u.setValue( gl, value[ u.id ], textures );
  11114. }
  11115. }
  11116. }
  11117. // --- Top-level ---
  11118. // Parser - builds up the property tree from the path strings
  11119. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11120. // extracts
  11121. // - the identifier (member name or array index)
  11122. // - followed by an optional right bracket (found when array index)
  11123. // - followed by an optional left bracket or dot (type of subscript)
  11124. //
  11125. // Note: These portions can be read in a non-overlapping fashion and
  11126. // allow straightforward parsing of the hierarchy that WebGL encodes
  11127. // in the uniform names.
  11128. function addUniform( container, uniformObject ) {
  11129. container.seq.push( uniformObject );
  11130. container.map[ uniformObject.id ] = uniformObject;
  11131. }
  11132. function parseUniform( activeInfo, addr, container ) {
  11133. const path = activeInfo.name,
  11134. pathLength = path.length;
  11135. // reset RegExp object, because of the early exit of a previous run
  11136. RePathPart.lastIndex = 0;
  11137. while ( true ) {
  11138. const match = RePathPart.exec( path ),
  11139. matchEnd = RePathPart.lastIndex;
  11140. let id = match[ 1 ];
  11141. const idIsIndex = match[ 2 ] === ']',
  11142. subscript = match[ 3 ];
  11143. if ( idIsIndex ) id = id | 0; // convert to integer
  11144. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11145. // bare name or "pure" bottom-level array "[0]" suffix
  11146. addUniform( container, subscript === undefined ?
  11147. new SingleUniform( id, activeInfo, addr ) :
  11148. new PureArrayUniform( id, activeInfo, addr ) );
  11149. break;
  11150. } else {
  11151. // step into inner node / create it in case it doesn't exist
  11152. const map = container.map;
  11153. let next = map[ id ];
  11154. if ( next === undefined ) {
  11155. next = new StructuredUniform( id );
  11156. addUniform( container, next );
  11157. }
  11158. container = next;
  11159. }
  11160. }
  11161. }
  11162. // Root Container
  11163. class WebGLUniforms {
  11164. constructor( gl, program ) {
  11165. this.seq = [];
  11166. this.map = {};
  11167. const n = gl.getProgramParameter( program, 35718 );
  11168. for ( let i = 0; i < n; ++ i ) {
  11169. const info = gl.getActiveUniform( program, i ),
  11170. addr = gl.getUniformLocation( program, info.name );
  11171. parseUniform( info, addr, this );
  11172. }
  11173. }
  11174. setValue( gl, name, value, textures ) {
  11175. const u = this.map[ name ];
  11176. if ( u !== undefined ) u.setValue( gl, value, textures );
  11177. }
  11178. setOptional( gl, object, name ) {
  11179. const v = object[ name ];
  11180. if ( v !== undefined ) this.setValue( gl, name, v );
  11181. }
  11182. static upload( gl, seq, values, textures ) {
  11183. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11184. const u = seq[ i ],
  11185. v = values[ u.id ];
  11186. if ( v.needsUpdate !== false ) {
  11187. // note: always updating when .needsUpdate is undefined
  11188. u.setValue( gl, v.value, textures );
  11189. }
  11190. }
  11191. }
  11192. static seqWithValue( seq, values ) {
  11193. const r = [];
  11194. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11195. const u = seq[ i ];
  11196. if ( u.id in values ) r.push( u );
  11197. }
  11198. return r;
  11199. }
  11200. }
  11201. function WebGLShader( gl, type, string ) {
  11202. const shader = gl.createShader( type );
  11203. gl.shaderSource( shader, string );
  11204. gl.compileShader( shader );
  11205. return shader;
  11206. }
  11207. let programIdCount = 0;
  11208. function handleSource( string, errorLine ) {
  11209. const lines = string.split( '\n' );
  11210. const lines2 = [];
  11211. const from = Math.max( errorLine - 6, 0 );
  11212. const to = Math.min( errorLine + 6, lines.length );
  11213. for ( let i = from; i < to; i ++ ) {
  11214. const line = i + 1;
  11215. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11216. }
  11217. return lines2.join( '\n' );
  11218. }
  11219. function getEncodingComponents( encoding ) {
  11220. switch ( encoding ) {
  11221. case LinearEncoding:
  11222. return [ 'Linear', '( value )' ];
  11223. case sRGBEncoding:
  11224. return [ 'sRGB', '( value )' ];
  11225. default:
  11226. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  11227. return [ 'Linear', '( value )' ];
  11228. }
  11229. }
  11230. function getShaderErrors( gl, shader, type ) {
  11231. const status = gl.getShaderParameter( shader, 35713 );
  11232. const errors = gl.getShaderInfoLog( shader ).trim();
  11233. if ( status && errors === '' ) return '';
  11234. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11235. if ( errorMatches ) {
  11236. // --enable-privileged-webgl-extension
  11237. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11238. const errorLine = parseInt( errorMatches[ 1 ] );
  11239. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11240. } else {
  11241. return errors;
  11242. }
  11243. }
  11244. function getTexelEncodingFunction( functionName, encoding ) {
  11245. const components = getEncodingComponents( encoding );
  11246. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  11247. }
  11248. function getToneMappingFunction( functionName, toneMapping ) {
  11249. let toneMappingName;
  11250. switch ( toneMapping ) {
  11251. case LinearToneMapping:
  11252. toneMappingName = 'Linear';
  11253. break;
  11254. case ReinhardToneMapping:
  11255. toneMappingName = 'Reinhard';
  11256. break;
  11257. case CineonToneMapping:
  11258. toneMappingName = 'OptimizedCineon';
  11259. break;
  11260. case ACESFilmicToneMapping:
  11261. toneMappingName = 'ACESFilmic';
  11262. break;
  11263. case CustomToneMapping:
  11264. toneMappingName = 'Custom';
  11265. break;
  11266. default:
  11267. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11268. toneMappingName = 'Linear';
  11269. }
  11270. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11271. }
  11272. function generateExtensions( parameters ) {
  11273. const chunks = [
  11274. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11275. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11276. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11277. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11278. ];
  11279. return chunks.filter( filterEmptyLine ).join( '\n' );
  11280. }
  11281. function generateDefines( defines ) {
  11282. const chunks = [];
  11283. for ( const name in defines ) {
  11284. const value = defines[ name ];
  11285. if ( value === false ) continue;
  11286. chunks.push( '#define ' + name + ' ' + value );
  11287. }
  11288. return chunks.join( '\n' );
  11289. }
  11290. function fetchAttributeLocations( gl, program ) {
  11291. const attributes = {};
  11292. const n = gl.getProgramParameter( program, 35721 );
  11293. for ( let i = 0; i < n; i ++ ) {
  11294. const info = gl.getActiveAttrib( program, i );
  11295. const name = info.name;
  11296. let locationSize = 1;
  11297. if ( info.type === 35674 ) locationSize = 2;
  11298. if ( info.type === 35675 ) locationSize = 3;
  11299. if ( info.type === 35676 ) locationSize = 4;
  11300. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11301. attributes[ name ] = {
  11302. type: info.type,
  11303. location: gl.getAttribLocation( program, name ),
  11304. locationSize: locationSize
  11305. };
  11306. }
  11307. return attributes;
  11308. }
  11309. function filterEmptyLine( string ) {
  11310. return string !== '';
  11311. }
  11312. function replaceLightNums( string, parameters ) {
  11313. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11314. return string
  11315. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11316. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11317. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11318. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11319. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11320. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11321. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11322. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11323. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11324. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11325. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11326. }
  11327. function replaceClippingPlaneNums( string, parameters ) {
  11328. return string
  11329. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11330. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11331. }
  11332. // Resolve Includes
  11333. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11334. function resolveIncludes( string ) {
  11335. return string.replace( includePattern, includeReplacer );
  11336. }
  11337. function includeReplacer( match, include ) {
  11338. const string = ShaderChunk[ include ];
  11339. if ( string === undefined ) {
  11340. throw new Error( 'Can not resolve #include <' + include + '>' );
  11341. }
  11342. return resolveIncludes( string );
  11343. }
  11344. // Unroll Loops
  11345. 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;
  11346. function unrollLoops( string ) {
  11347. return string.replace( unrollLoopPattern, loopReplacer );
  11348. }
  11349. function loopReplacer( match, start, end, snippet ) {
  11350. let string = '';
  11351. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11352. string += snippet
  11353. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11354. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11355. }
  11356. return string;
  11357. }
  11358. //
  11359. function generatePrecision( parameters ) {
  11360. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11361. if ( parameters.precision === 'highp' ) {
  11362. precisionstring += '\n#define HIGH_PRECISION';
  11363. } else if ( parameters.precision === 'mediump' ) {
  11364. precisionstring += '\n#define MEDIUM_PRECISION';
  11365. } else if ( parameters.precision === 'lowp' ) {
  11366. precisionstring += '\n#define LOW_PRECISION';
  11367. }
  11368. return precisionstring;
  11369. }
  11370. function generateShadowMapTypeDefine( parameters ) {
  11371. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11372. if ( parameters.shadowMapType === PCFShadowMap ) {
  11373. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11374. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11375. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11376. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11377. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11378. }
  11379. return shadowMapTypeDefine;
  11380. }
  11381. function generateEnvMapTypeDefine( parameters ) {
  11382. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11383. if ( parameters.envMap ) {
  11384. switch ( parameters.envMapMode ) {
  11385. case CubeReflectionMapping:
  11386. case CubeRefractionMapping:
  11387. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11388. break;
  11389. case CubeUVReflectionMapping:
  11390. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11391. break;
  11392. }
  11393. }
  11394. return envMapTypeDefine;
  11395. }
  11396. function generateEnvMapModeDefine( parameters ) {
  11397. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11398. if ( parameters.envMap ) {
  11399. switch ( parameters.envMapMode ) {
  11400. case CubeRefractionMapping:
  11401. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11402. break;
  11403. }
  11404. }
  11405. return envMapModeDefine;
  11406. }
  11407. function generateEnvMapBlendingDefine( parameters ) {
  11408. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11409. if ( parameters.envMap ) {
  11410. switch ( parameters.combine ) {
  11411. case MultiplyOperation:
  11412. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11413. break;
  11414. case MixOperation:
  11415. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11416. break;
  11417. case AddOperation:
  11418. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11419. break;
  11420. }
  11421. }
  11422. return envMapBlendingDefine;
  11423. }
  11424. function generateCubeUVSize( parameters ) {
  11425. const imageHeight = parameters.envMapCubeUVHeight;
  11426. if ( imageHeight === null ) return null;
  11427. const maxMip = Math.log2( imageHeight ) - 2;
  11428. const texelHeight = 1.0 / imageHeight;
  11429. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11430. return { texelWidth, texelHeight, maxMip };
  11431. }
  11432. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11433. // TODO Send this event to Three.js DevTools
  11434. // console.log( 'WebGLProgram', cacheKey );
  11435. const gl = renderer.getContext();
  11436. const defines = parameters.defines;
  11437. let vertexShader = parameters.vertexShader;
  11438. let fragmentShader = parameters.fragmentShader;
  11439. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11440. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11441. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11442. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11443. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11444. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11445. const customDefines = generateDefines( defines );
  11446. const program = gl.createProgram();
  11447. let prefixVertex, prefixFragment;
  11448. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11449. if ( parameters.isRawShaderMaterial ) {
  11450. prefixVertex = [
  11451. customDefines
  11452. ].filter( filterEmptyLine ).join( '\n' );
  11453. if ( prefixVertex.length > 0 ) {
  11454. prefixVertex += '\n';
  11455. }
  11456. prefixFragment = [
  11457. customExtensions,
  11458. customDefines
  11459. ].filter( filterEmptyLine ).join( '\n' );
  11460. if ( prefixFragment.length > 0 ) {
  11461. prefixFragment += '\n';
  11462. }
  11463. } else {
  11464. prefixVertex = [
  11465. generatePrecision( parameters ),
  11466. '#define SHADER_NAME ' + parameters.shaderName,
  11467. customDefines,
  11468. parameters.instancing ? '#define USE_INSTANCING' : '',
  11469. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11470. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11471. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11472. parameters.map ? '#define USE_MAP' : '',
  11473. parameters.envMap ? '#define USE_ENVMAP' : '',
  11474. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11475. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11476. parameters.aoMap ? '#define USE_AOMAP' : '',
  11477. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11478. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11479. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11480. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11481. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11482. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11483. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11484. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11485. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11486. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11487. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11488. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11489. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11490. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11491. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11492. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11493. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11494. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11495. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11496. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11497. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11498. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11499. //
  11500. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11501. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11502. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11503. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11504. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11505. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11506. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11507. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11508. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11509. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11510. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11511. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11512. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11513. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11514. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11515. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11516. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11517. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11518. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11519. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11520. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11521. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11522. //
  11523. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11524. parameters.vertexColors ? '#define USE_COLOR' : '',
  11525. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11526. parameters.vertexUvs ? '#define USE_UV' : '',
  11527. parameters.vertexUvs2 ? '#define USE_UV2' : '',
  11528. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11529. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11530. parameters.skinning ? '#define USE_SKINNING' : '',
  11531. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11532. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11533. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11534. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11535. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11536. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11537. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11538. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11539. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11540. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11541. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11542. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11543. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11544. 'uniform mat4 modelMatrix;',
  11545. 'uniform mat4 modelViewMatrix;',
  11546. 'uniform mat4 projectionMatrix;',
  11547. 'uniform mat4 viewMatrix;',
  11548. 'uniform mat3 normalMatrix;',
  11549. 'uniform vec3 cameraPosition;',
  11550. 'uniform bool isOrthographic;',
  11551. '#ifdef USE_INSTANCING',
  11552. ' attribute mat4 instanceMatrix;',
  11553. '#endif',
  11554. '#ifdef USE_INSTANCING_COLOR',
  11555. ' attribute vec3 instanceColor;',
  11556. '#endif',
  11557. 'attribute vec3 position;',
  11558. 'attribute vec3 normal;',
  11559. 'attribute vec2 uv;',
  11560. '#ifdef USE_TANGENT',
  11561. ' attribute vec4 tangent;',
  11562. '#endif',
  11563. '#if defined( USE_COLOR_ALPHA )',
  11564. ' attribute vec4 color;',
  11565. '#elif defined( USE_COLOR )',
  11566. ' attribute vec3 color;',
  11567. '#endif',
  11568. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11569. ' attribute vec3 morphTarget0;',
  11570. ' attribute vec3 morphTarget1;',
  11571. ' attribute vec3 morphTarget2;',
  11572. ' attribute vec3 morphTarget3;',
  11573. ' #ifdef USE_MORPHNORMALS',
  11574. ' attribute vec3 morphNormal0;',
  11575. ' attribute vec3 morphNormal1;',
  11576. ' attribute vec3 morphNormal2;',
  11577. ' attribute vec3 morphNormal3;',
  11578. ' #else',
  11579. ' attribute vec3 morphTarget4;',
  11580. ' attribute vec3 morphTarget5;',
  11581. ' attribute vec3 morphTarget6;',
  11582. ' attribute vec3 morphTarget7;',
  11583. ' #endif',
  11584. '#endif',
  11585. '#ifdef USE_SKINNING',
  11586. ' attribute vec4 skinIndex;',
  11587. ' attribute vec4 skinWeight;',
  11588. '#endif',
  11589. '\n'
  11590. ].filter( filterEmptyLine ).join( '\n' );
  11591. prefixFragment = [
  11592. customExtensions,
  11593. generatePrecision( parameters ),
  11594. '#define SHADER_NAME ' + parameters.shaderName,
  11595. customDefines,
  11596. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11597. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11598. parameters.map ? '#define USE_MAP' : '',
  11599. parameters.matcap ? '#define USE_MATCAP' : '',
  11600. parameters.envMap ? '#define USE_ENVMAP' : '',
  11601. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11602. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11603. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11604. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11605. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11606. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11607. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11608. parameters.aoMap ? '#define USE_AOMAP' : '',
  11609. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11610. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11611. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11612. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11613. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11614. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11615. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11616. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11617. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11618. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11619. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11620. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11621. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11622. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11623. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11624. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11625. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11626. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11627. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11628. parameters.sheen ? '#define USE_SHEEN' : '',
  11629. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11630. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11631. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11632. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11633. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11634. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11635. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11636. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11637. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11638. parameters.vertexUvs2 ? '#define USE_UV2' : '',
  11639. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11640. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11641. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11642. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11643. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11644. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11645. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11646. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11647. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11648. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11649. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11650. 'uniform mat4 viewMatrix;',
  11651. 'uniform vec3 cameraPosition;',
  11652. 'uniform bool isOrthographic;',
  11653. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11654. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11655. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11656. parameters.dithering ? '#define DITHERING' : '',
  11657. parameters.opaque ? '#define OPAQUE' : '',
  11658. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11659. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11660. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11661. '\n'
  11662. ].filter( filterEmptyLine ).join( '\n' );
  11663. }
  11664. vertexShader = resolveIncludes( vertexShader );
  11665. vertexShader = replaceLightNums( vertexShader, parameters );
  11666. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11667. fragmentShader = resolveIncludes( fragmentShader );
  11668. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11669. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11670. vertexShader = unrollLoops( vertexShader );
  11671. fragmentShader = unrollLoops( fragmentShader );
  11672. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11673. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11674. versionString = '#version 300 es\n';
  11675. prefixVertex = [
  11676. 'precision mediump sampler2DArray;',
  11677. '#define attribute in',
  11678. '#define varying out',
  11679. '#define texture2D texture'
  11680. ].join( '\n' ) + '\n' + prefixVertex;
  11681. prefixFragment = [
  11682. '#define varying in',
  11683. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11684. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11685. '#define gl_FragDepthEXT gl_FragDepth',
  11686. '#define texture2D texture',
  11687. '#define textureCube texture',
  11688. '#define texture2DProj textureProj',
  11689. '#define texture2DLodEXT textureLod',
  11690. '#define texture2DProjLodEXT textureProjLod',
  11691. '#define textureCubeLodEXT textureLod',
  11692. '#define texture2DGradEXT textureGrad',
  11693. '#define texture2DProjGradEXT textureProjGrad',
  11694. '#define textureCubeGradEXT textureGrad'
  11695. ].join( '\n' ) + '\n' + prefixFragment;
  11696. }
  11697. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11698. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11699. // console.log( '*VERTEX*', vertexGlsl );
  11700. // console.log( '*FRAGMENT*', fragmentGlsl );
  11701. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11702. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11703. gl.attachShader( program, glVertexShader );
  11704. gl.attachShader( program, glFragmentShader );
  11705. // Force a particular attribute to index 0.
  11706. if ( parameters.index0AttributeName !== undefined ) {
  11707. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11708. } else if ( parameters.morphTargets === true ) {
  11709. // programs with morphTargets displace position out of attribute 0
  11710. gl.bindAttribLocation( program, 0, 'position' );
  11711. }
  11712. gl.linkProgram( program );
  11713. // check for link errors
  11714. if ( renderer.debug.checkShaderErrors ) {
  11715. const programLog = gl.getProgramInfoLog( program ).trim();
  11716. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11717. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11718. let runnable = true;
  11719. let haveDiagnostics = true;
  11720. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11721. runnable = false;
  11722. if ( typeof renderer.debug.onShaderError === 'function' ) {
  11723. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  11724. } else {
  11725. // default error reporting
  11726. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11727. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11728. console.error(
  11729. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11730. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11731. 'Program Info Log: ' + programLog + '\n' +
  11732. vertexErrors + '\n' +
  11733. fragmentErrors
  11734. );
  11735. }
  11736. } else if ( programLog !== '' ) {
  11737. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11738. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11739. haveDiagnostics = false;
  11740. }
  11741. if ( haveDiagnostics ) {
  11742. this.diagnostics = {
  11743. runnable: runnable,
  11744. programLog: programLog,
  11745. vertexShader: {
  11746. log: vertexLog,
  11747. prefix: prefixVertex
  11748. },
  11749. fragmentShader: {
  11750. log: fragmentLog,
  11751. prefix: prefixFragment
  11752. }
  11753. };
  11754. }
  11755. }
  11756. // Clean up
  11757. // Crashes in iOS9 and iOS10. #18402
  11758. // gl.detachShader( program, glVertexShader );
  11759. // gl.detachShader( program, glFragmentShader );
  11760. gl.deleteShader( glVertexShader );
  11761. gl.deleteShader( glFragmentShader );
  11762. // set up caching for uniform locations
  11763. let cachedUniforms;
  11764. this.getUniforms = function () {
  11765. if ( cachedUniforms === undefined ) {
  11766. cachedUniforms = new WebGLUniforms( gl, program );
  11767. }
  11768. return cachedUniforms;
  11769. };
  11770. // set up caching for attribute locations
  11771. let cachedAttributes;
  11772. this.getAttributes = function () {
  11773. if ( cachedAttributes === undefined ) {
  11774. cachedAttributes = fetchAttributeLocations( gl, program );
  11775. }
  11776. return cachedAttributes;
  11777. };
  11778. // free resource
  11779. this.destroy = function () {
  11780. bindingStates.releaseStatesOfProgram( this );
  11781. gl.deleteProgram( program );
  11782. this.program = undefined;
  11783. };
  11784. //
  11785. this.name = parameters.shaderName;
  11786. this.id = programIdCount ++;
  11787. this.cacheKey = cacheKey;
  11788. this.usedTimes = 1;
  11789. this.program = program;
  11790. this.vertexShader = glVertexShader;
  11791. this.fragmentShader = glFragmentShader;
  11792. return this;
  11793. }
  11794. let _id = 0;
  11795. class WebGLShaderCache {
  11796. constructor() {
  11797. this.shaderCache = new Map();
  11798. this.materialCache = new Map();
  11799. }
  11800. update( material ) {
  11801. const vertexShader = material.vertexShader;
  11802. const fragmentShader = material.fragmentShader;
  11803. const vertexShaderStage = this._getShaderStage( vertexShader );
  11804. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11805. const materialShaders = this._getShaderCacheForMaterial( material );
  11806. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11807. materialShaders.add( vertexShaderStage );
  11808. vertexShaderStage.usedTimes ++;
  11809. }
  11810. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11811. materialShaders.add( fragmentShaderStage );
  11812. fragmentShaderStage.usedTimes ++;
  11813. }
  11814. return this;
  11815. }
  11816. remove( material ) {
  11817. const materialShaders = this.materialCache.get( material );
  11818. for ( const shaderStage of materialShaders ) {
  11819. shaderStage.usedTimes --;
  11820. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11821. }
  11822. this.materialCache.delete( material );
  11823. return this;
  11824. }
  11825. getVertexShaderID( material ) {
  11826. return this._getShaderStage( material.vertexShader ).id;
  11827. }
  11828. getFragmentShaderID( material ) {
  11829. return this._getShaderStage( material.fragmentShader ).id;
  11830. }
  11831. dispose() {
  11832. this.shaderCache.clear();
  11833. this.materialCache.clear();
  11834. }
  11835. _getShaderCacheForMaterial( material ) {
  11836. const cache = this.materialCache;
  11837. let set = cache.get( material );
  11838. if ( set === undefined ) {
  11839. set = new Set();
  11840. cache.set( material, set );
  11841. }
  11842. return set;
  11843. }
  11844. _getShaderStage( code ) {
  11845. const cache = this.shaderCache;
  11846. let stage = cache.get( code );
  11847. if ( stage === undefined ) {
  11848. stage = new WebGLShaderStage( code );
  11849. cache.set( code, stage );
  11850. }
  11851. return stage;
  11852. }
  11853. }
  11854. class WebGLShaderStage {
  11855. constructor( code ) {
  11856. this.id = _id ++;
  11857. this.code = code;
  11858. this.usedTimes = 0;
  11859. }
  11860. }
  11861. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11862. const _programLayers = new Layers();
  11863. const _customShaders = new WebGLShaderCache();
  11864. const programs = [];
  11865. const IS_WEBGL2 = capabilities.isWebGL2;
  11866. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11867. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  11868. let precision = capabilities.precision;
  11869. const shaderIDs = {
  11870. MeshDepthMaterial: 'depth',
  11871. MeshDistanceMaterial: 'distanceRGBA',
  11872. MeshNormalMaterial: 'normal',
  11873. MeshBasicMaterial: 'basic',
  11874. MeshLambertMaterial: 'lambert',
  11875. MeshPhongMaterial: 'phong',
  11876. MeshToonMaterial: 'toon',
  11877. MeshStandardMaterial: 'physical',
  11878. MeshPhysicalMaterial: 'physical',
  11879. MeshMatcapMaterial: 'matcap',
  11880. LineBasicMaterial: 'basic',
  11881. LineDashedMaterial: 'dashed',
  11882. PointsMaterial: 'points',
  11883. ShadowMaterial: 'shadow',
  11884. SpriteMaterial: 'sprite'
  11885. };
  11886. function getChannel( value ) {
  11887. if ( value === 1 ) return 'uv2';
  11888. return 'uv';
  11889. }
  11890. function getParameters( material, lights, shadows, scene, object ) {
  11891. const fog = scene.fog;
  11892. const geometry = object.geometry;
  11893. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11894. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11895. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11896. const shaderID = shaderIDs[ material.type ];
  11897. // heuristics to create shader parameters according to lights in the scene
  11898. // (not to blow over maxLights budget)
  11899. if ( material.precision !== null ) {
  11900. precision = capabilities.getMaxPrecision( material.precision );
  11901. if ( precision !== material.precision ) {
  11902. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11903. }
  11904. }
  11905. //
  11906. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11907. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11908. let morphTextureStride = 0;
  11909. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11910. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11911. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11912. //
  11913. let vertexShader, fragmentShader;
  11914. let customVertexShaderID, customFragmentShaderID;
  11915. if ( shaderID ) {
  11916. const shader = ShaderLib[ shaderID ];
  11917. vertexShader = shader.vertexShader;
  11918. fragmentShader = shader.fragmentShader;
  11919. } else {
  11920. vertexShader = material.vertexShader;
  11921. fragmentShader = material.fragmentShader;
  11922. _customShaders.update( material );
  11923. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11924. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11925. }
  11926. const currentRenderTarget = renderer.getRenderTarget();
  11927. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  11928. const HAS_MAP = !! material.map;
  11929. const HAS_MATCAP = !! material.matcap;
  11930. const HAS_ENVMAP = !! envMap;
  11931. const HAS_AOMAP = !! material.aoMap;
  11932. const HAS_LIGHTMAP = !! material.lightMap;
  11933. const HAS_BUMPMAP = !! material.bumpMap;
  11934. const HAS_NORMALMAP = !! material.normalMap;
  11935. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  11936. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  11937. const HAS_METALNESSMAP = !! material.metalnessMap;
  11938. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  11939. const HAS_CLEARCOAT = material.clearcoat > 0;
  11940. const HAS_IRIDESCENCE = material.iridescence > 0;
  11941. const HAS_SHEEN = material.sheen > 0;
  11942. const HAS_TRANSMISSION = material.transmission > 0;
  11943. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  11944. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  11945. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  11946. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  11947. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  11948. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  11949. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  11950. const HAS_SPECULARMAP = !! material.specularMap;
  11951. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  11952. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  11953. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  11954. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  11955. const HAS_GRADIENTMAP = !! material.gradientMap;
  11956. const HAS_ALPHAMAP = !! material.alphaMap;
  11957. const HAS_ALPHATEST = material.alphaTest > 0;
  11958. const HAS_EXTENSIONS = !! material.extensions;
  11959. const HAS_ATTRIBUTE_UV = !! geometry.attributes.uv;
  11960. const HAS_ATTRIBUTE_UV2 = !! geometry.attributes.uv2;
  11961. const parameters = {
  11962. isWebGL2: IS_WEBGL2,
  11963. shaderID: shaderID,
  11964. shaderName: material.type,
  11965. vertexShader: vertexShader,
  11966. fragmentShader: fragmentShader,
  11967. defines: material.defines,
  11968. customVertexShaderID: customVertexShaderID,
  11969. customFragmentShaderID: customFragmentShaderID,
  11970. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11971. glslVersion: material.glslVersion,
  11972. precision: precision,
  11973. instancing: IS_INSTANCEDMESH,
  11974. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  11975. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  11976. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11977. map: HAS_MAP,
  11978. matcap: HAS_MATCAP,
  11979. envMap: HAS_ENVMAP,
  11980. envMapMode: HAS_ENVMAP && envMap.mapping,
  11981. envMapCubeUVHeight: envMapCubeUVHeight,
  11982. aoMap: HAS_AOMAP,
  11983. lightMap: HAS_LIGHTMAP,
  11984. bumpMap: HAS_BUMPMAP,
  11985. normalMap: HAS_NORMALMAP,
  11986. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  11987. emissiveMap: HAS_EMISSIVEMAP,
  11988. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  11989. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  11990. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11991. metalnessMap: HAS_METALNESSMAP,
  11992. roughnessMap: HAS_ROUGHNESSMAP,
  11993. clearcoat: HAS_CLEARCOAT,
  11994. clearcoatMap: HAS_CLEARCOATMAP,
  11995. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  11996. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  11997. iridescence: HAS_IRIDESCENCE,
  11998. iridescenceMap: HAS_IRIDESCENCEMAP,
  11999. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  12000. sheen: HAS_SHEEN,
  12001. sheenColorMap: HAS_SHEEN_COLORMAP,
  12002. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  12003. specularMap: HAS_SPECULARMAP,
  12004. specularColorMap: HAS_SPECULAR_COLORMAP,
  12005. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  12006. transmission: HAS_TRANSMISSION,
  12007. transmissionMap: HAS_TRANSMISSIONMAP,
  12008. thicknessMap: HAS_THICKNESSMAP,
  12009. gradientMap: HAS_GRADIENTMAP,
  12010. opaque: material.transparent === false && material.blending === NormalBlending,
  12011. alphaMap: HAS_ALPHAMAP,
  12012. alphaTest: HAS_ALPHATEST,
  12013. combine: material.combine,
  12014. //
  12015. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12016. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12017. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12018. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12019. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12020. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12021. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12022. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12023. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12024. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12025. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12026. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12027. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12028. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12029. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12030. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12031. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12032. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12033. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12034. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12035. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12036. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12037. //
  12038. vertexTangents: HAS_NORMALMAP && !! geometry.attributes.tangent,
  12039. vertexColors: material.vertexColors,
  12040. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12041. vertexUvs: HAS_ATTRIBUTE_UV,
  12042. vertexUvs2: HAS_ATTRIBUTE_UV2,
  12043. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12044. fog: !! fog,
  12045. useFog: material.fog === true,
  12046. fogExp2: ( fog && fog.isFogExp2 ),
  12047. flatShading: material.flatShading === true,
  12048. sizeAttenuation: material.sizeAttenuation === true,
  12049. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12050. skinning: object.isSkinnedMesh === true,
  12051. morphTargets: geometry.morphAttributes.position !== undefined,
  12052. morphNormals: geometry.morphAttributes.normal !== undefined,
  12053. morphColors: geometry.morphAttributes.color !== undefined,
  12054. morphTargetsCount: morphTargetsCount,
  12055. morphTextureStride: morphTextureStride,
  12056. numDirLights: lights.directional.length,
  12057. numPointLights: lights.point.length,
  12058. numSpotLights: lights.spot.length,
  12059. numSpotLightMaps: lights.spotLightMap.length,
  12060. numRectAreaLights: lights.rectArea.length,
  12061. numHemiLights: lights.hemi.length,
  12062. numDirLightShadows: lights.directionalShadowMap.length,
  12063. numPointLightShadows: lights.pointShadowMap.length,
  12064. numSpotLightShadows: lights.spotShadowMap.length,
  12065. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12066. numClippingPlanes: clipping.numPlanes,
  12067. numClipIntersection: clipping.numIntersection,
  12068. dithering: material.dithering,
  12069. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12070. shadowMapType: renderer.shadowMap.type,
  12071. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12072. useLegacyLights: renderer.useLegacyLights,
  12073. premultipliedAlpha: material.premultipliedAlpha,
  12074. doubleSided: material.side === DoubleSide,
  12075. flipSided: material.side === BackSide,
  12076. useDepthPacking: material.depthPacking >= 0,
  12077. depthPacking: material.depthPacking || 0,
  12078. index0AttributeName: material.index0AttributeName,
  12079. extensionDerivatives: HAS_EXTENSIONS && material.extensions.derivatives === true,
  12080. extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true,
  12081. extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true,
  12082. extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true,
  12083. rendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ),
  12084. rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  12085. rendererExtensionShaderTextureLod: IS_WEBGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  12086. customProgramCacheKey: material.customProgramCacheKey()
  12087. };
  12088. return parameters;
  12089. }
  12090. function getProgramCacheKey( parameters ) {
  12091. const array = [];
  12092. if ( parameters.shaderID ) {
  12093. array.push( parameters.shaderID );
  12094. } else {
  12095. array.push( parameters.customVertexShaderID );
  12096. array.push( parameters.customFragmentShaderID );
  12097. }
  12098. if ( parameters.defines !== undefined ) {
  12099. for ( const name in parameters.defines ) {
  12100. array.push( name );
  12101. array.push( parameters.defines[ name ] );
  12102. }
  12103. }
  12104. if ( parameters.isRawShaderMaterial === false ) {
  12105. getProgramCacheKeyParameters( array, parameters );
  12106. getProgramCacheKeyBooleans( array, parameters );
  12107. array.push( renderer.outputEncoding );
  12108. }
  12109. array.push( parameters.customProgramCacheKey );
  12110. return array.join();
  12111. }
  12112. function getProgramCacheKeyParameters( array, parameters ) {
  12113. array.push( parameters.precision );
  12114. array.push( parameters.outputEncoding );
  12115. array.push( parameters.envMapMode );
  12116. array.push( parameters.envMapCubeUVHeight );
  12117. array.push( parameters.mapUv );
  12118. array.push( parameters.alphaMapUv );
  12119. array.push( parameters.lightMapUv );
  12120. array.push( parameters.aoMapUv );
  12121. array.push( parameters.bumpMapUv );
  12122. array.push( parameters.normalMapUv );
  12123. array.push( parameters.displacementMapUv );
  12124. array.push( parameters.emissiveMapUv );
  12125. array.push( parameters.metalnessMapUv );
  12126. array.push( parameters.roughnessMapUv );
  12127. array.push( parameters.clearcoatMapUv );
  12128. array.push( parameters.clearcoatNormalMapUv );
  12129. array.push( parameters.clearcoatRoughnessMapUv );
  12130. array.push( parameters.iridescenceMapUv );
  12131. array.push( parameters.iridescenceThicknessMapUv );
  12132. array.push( parameters.sheenColorMapUv );
  12133. array.push( parameters.sheenRoughnessMapUv );
  12134. array.push( parameters.specularMapUv );
  12135. array.push( parameters.specularColorMapUv );
  12136. array.push( parameters.specularIntensityMapUv );
  12137. array.push( parameters.transmissionMapUv );
  12138. array.push( parameters.thicknessMapUv );
  12139. array.push( parameters.combine );
  12140. array.push( parameters.fogExp2 );
  12141. array.push( parameters.sizeAttenuation );
  12142. array.push( parameters.morphTargetsCount );
  12143. array.push( parameters.morphAttributeCount );
  12144. array.push( parameters.numDirLights );
  12145. array.push( parameters.numPointLights );
  12146. array.push( parameters.numSpotLights );
  12147. array.push( parameters.numSpotLightMaps );
  12148. array.push( parameters.numHemiLights );
  12149. array.push( parameters.numRectAreaLights );
  12150. array.push( parameters.numDirLightShadows );
  12151. array.push( parameters.numPointLightShadows );
  12152. array.push( parameters.numSpotLightShadows );
  12153. array.push( parameters.numSpotLightShadowsWithMaps );
  12154. array.push( parameters.shadowMapType );
  12155. array.push( parameters.toneMapping );
  12156. array.push( parameters.numClippingPlanes );
  12157. array.push( parameters.numClipIntersection );
  12158. array.push( parameters.depthPacking );
  12159. }
  12160. function getProgramCacheKeyBooleans( array, parameters ) {
  12161. _programLayers.disableAll();
  12162. if ( parameters.isWebGL2 )
  12163. _programLayers.enable( 0 );
  12164. if ( parameters.supportsVertexTextures )
  12165. _programLayers.enable( 1 );
  12166. if ( parameters.instancing )
  12167. _programLayers.enable( 2 );
  12168. if ( parameters.instancingColor )
  12169. _programLayers.enable( 3 );
  12170. if ( parameters.matcap )
  12171. _programLayers.enable( 4 );
  12172. if ( parameters.envMap )
  12173. _programLayers.enable( 5 );
  12174. if ( parameters.normalMapObjectSpace )
  12175. _programLayers.enable( 6 );
  12176. if ( parameters.normalMapTangentSpace )
  12177. _programLayers.enable( 7 );
  12178. if ( parameters.clearcoat )
  12179. _programLayers.enable( 8 );
  12180. if ( parameters.iridescence )
  12181. _programLayers.enable( 9 );
  12182. if ( parameters.alphaTest )
  12183. _programLayers.enable( 10 );
  12184. if ( parameters.vertexColors )
  12185. _programLayers.enable( 11 );
  12186. if ( parameters.vertexAlphas )
  12187. _programLayers.enable( 12 );
  12188. if ( parameters.vertexUvs )
  12189. _programLayers.enable( 13 );
  12190. if ( parameters.vertexUvs2 )
  12191. _programLayers.enable( 14 );
  12192. if ( parameters.vertexTangents )
  12193. _programLayers.enable( 15 );
  12194. array.push( _programLayers.mask );
  12195. _programLayers.disableAll();
  12196. if ( parameters.fog )
  12197. _programLayers.enable( 0 );
  12198. if ( parameters.useFog )
  12199. _programLayers.enable( 1 );
  12200. if ( parameters.flatShading )
  12201. _programLayers.enable( 2 );
  12202. if ( parameters.logarithmicDepthBuffer )
  12203. _programLayers.enable( 3 );
  12204. if ( parameters.skinning )
  12205. _programLayers.enable( 4 );
  12206. if ( parameters.morphTargets )
  12207. _programLayers.enable( 5 );
  12208. if ( parameters.morphNormals )
  12209. _programLayers.enable( 6 );
  12210. if ( parameters.morphColors )
  12211. _programLayers.enable( 7 );
  12212. if ( parameters.premultipliedAlpha )
  12213. _programLayers.enable( 8 );
  12214. if ( parameters.shadowMapEnabled )
  12215. _programLayers.enable( 9 );
  12216. if ( parameters.useLegacyLights )
  12217. _programLayers.enable( 10 );
  12218. if ( parameters.doubleSided )
  12219. _programLayers.enable( 11 );
  12220. if ( parameters.flipSided )
  12221. _programLayers.enable( 12 );
  12222. if ( parameters.useDepthPacking )
  12223. _programLayers.enable( 13 );
  12224. if ( parameters.dithering )
  12225. _programLayers.enable( 14 );
  12226. if ( parameters.transmission )
  12227. _programLayers.enable( 15 );
  12228. if ( parameters.sheen )
  12229. _programLayers.enable( 16 );
  12230. if ( parameters.decodeVideoTexture )
  12231. _programLayers.enable( 17 );
  12232. if ( parameters.opaque )
  12233. _programLayers.enable( 18 );
  12234. if ( parameters.pointsUvs )
  12235. _programLayers.enable( 19 );
  12236. array.push( _programLayers.mask );
  12237. }
  12238. function getUniforms( material ) {
  12239. const shaderID = shaderIDs[ material.type ];
  12240. let uniforms;
  12241. if ( shaderID ) {
  12242. const shader = ShaderLib[ shaderID ];
  12243. uniforms = UniformsUtils.clone( shader.uniforms );
  12244. } else {
  12245. uniforms = material.uniforms;
  12246. }
  12247. return uniforms;
  12248. }
  12249. function acquireProgram( parameters, cacheKey ) {
  12250. let program;
  12251. // Check if code has been already compiled
  12252. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12253. const preexistingProgram = programs[ p ];
  12254. if ( preexistingProgram.cacheKey === cacheKey ) {
  12255. program = preexistingProgram;
  12256. ++ program.usedTimes;
  12257. break;
  12258. }
  12259. }
  12260. if ( program === undefined ) {
  12261. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12262. programs.push( program );
  12263. }
  12264. return program;
  12265. }
  12266. function releaseProgram( program ) {
  12267. if ( -- program.usedTimes === 0 ) {
  12268. // Remove from unordered set
  12269. const i = programs.indexOf( program );
  12270. programs[ i ] = programs[ programs.length - 1 ];
  12271. programs.pop();
  12272. // Free WebGL resources
  12273. program.destroy();
  12274. }
  12275. }
  12276. function releaseShaderCache( material ) {
  12277. _customShaders.remove( material );
  12278. }
  12279. function dispose() {
  12280. _customShaders.dispose();
  12281. }
  12282. return {
  12283. getParameters: getParameters,
  12284. getProgramCacheKey: getProgramCacheKey,
  12285. getUniforms: getUniforms,
  12286. acquireProgram: acquireProgram,
  12287. releaseProgram: releaseProgram,
  12288. releaseShaderCache: releaseShaderCache,
  12289. // Exposed for resource monitoring & error feedback via renderer.info:
  12290. programs: programs,
  12291. dispose: dispose
  12292. };
  12293. }
  12294. function WebGLProperties() {
  12295. let properties = new WeakMap();
  12296. function get( object ) {
  12297. let map = properties.get( object );
  12298. if ( map === undefined ) {
  12299. map = {};
  12300. properties.set( object, map );
  12301. }
  12302. return map;
  12303. }
  12304. function remove( object ) {
  12305. properties.delete( object );
  12306. }
  12307. function update( object, key, value ) {
  12308. properties.get( object )[ key ] = value;
  12309. }
  12310. function dispose() {
  12311. properties = new WeakMap();
  12312. }
  12313. return {
  12314. get: get,
  12315. remove: remove,
  12316. update: update,
  12317. dispose: dispose
  12318. };
  12319. }
  12320. function painterSortStable( a, b ) {
  12321. if ( a.groupOrder !== b.groupOrder ) {
  12322. return a.groupOrder - b.groupOrder;
  12323. } else if ( a.renderOrder !== b.renderOrder ) {
  12324. return a.renderOrder - b.renderOrder;
  12325. } else if ( a.material.id !== b.material.id ) {
  12326. return a.material.id - b.material.id;
  12327. } else if ( a.z !== b.z ) {
  12328. return a.z - b.z;
  12329. } else {
  12330. return a.id - b.id;
  12331. }
  12332. }
  12333. function reversePainterSortStable( a, b ) {
  12334. if ( a.groupOrder !== b.groupOrder ) {
  12335. return a.groupOrder - b.groupOrder;
  12336. } else if ( a.renderOrder !== b.renderOrder ) {
  12337. return a.renderOrder - b.renderOrder;
  12338. } else if ( a.z !== b.z ) {
  12339. return b.z - a.z;
  12340. } else {
  12341. return a.id - b.id;
  12342. }
  12343. }
  12344. function WebGLRenderList() {
  12345. const renderItems = [];
  12346. let renderItemsIndex = 0;
  12347. const opaque = [];
  12348. const transmissive = [];
  12349. const transparent = [];
  12350. function init() {
  12351. renderItemsIndex = 0;
  12352. opaque.length = 0;
  12353. transmissive.length = 0;
  12354. transparent.length = 0;
  12355. }
  12356. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12357. let renderItem = renderItems[ renderItemsIndex ];
  12358. if ( renderItem === undefined ) {
  12359. renderItem = {
  12360. id: object.id,
  12361. object: object,
  12362. geometry: geometry,
  12363. material: material,
  12364. groupOrder: groupOrder,
  12365. renderOrder: object.renderOrder,
  12366. z: z,
  12367. group: group
  12368. };
  12369. renderItems[ renderItemsIndex ] = renderItem;
  12370. } else {
  12371. renderItem.id = object.id;
  12372. renderItem.object = object;
  12373. renderItem.geometry = geometry;
  12374. renderItem.material = material;
  12375. renderItem.groupOrder = groupOrder;
  12376. renderItem.renderOrder = object.renderOrder;
  12377. renderItem.z = z;
  12378. renderItem.group = group;
  12379. }
  12380. renderItemsIndex ++;
  12381. return renderItem;
  12382. }
  12383. function push( object, geometry, material, groupOrder, z, group ) {
  12384. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12385. if ( material.transmission > 0.0 ) {
  12386. transmissive.push( renderItem );
  12387. } else if ( material.transparent === true ) {
  12388. transparent.push( renderItem );
  12389. } else {
  12390. opaque.push( renderItem );
  12391. }
  12392. }
  12393. function unshift( object, geometry, material, groupOrder, z, group ) {
  12394. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12395. if ( material.transmission > 0.0 ) {
  12396. transmissive.unshift( renderItem );
  12397. } else if ( material.transparent === true ) {
  12398. transparent.unshift( renderItem );
  12399. } else {
  12400. opaque.unshift( renderItem );
  12401. }
  12402. }
  12403. function sort( customOpaqueSort, customTransparentSort ) {
  12404. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12405. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12406. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12407. }
  12408. function finish() {
  12409. // Clear references from inactive renderItems in the list
  12410. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12411. const renderItem = renderItems[ i ];
  12412. if ( renderItem.id === null ) break;
  12413. renderItem.id = null;
  12414. renderItem.object = null;
  12415. renderItem.geometry = null;
  12416. renderItem.material = null;
  12417. renderItem.group = null;
  12418. }
  12419. }
  12420. return {
  12421. opaque: opaque,
  12422. transmissive: transmissive,
  12423. transparent: transparent,
  12424. init: init,
  12425. push: push,
  12426. unshift: unshift,
  12427. finish: finish,
  12428. sort: sort
  12429. };
  12430. }
  12431. function WebGLRenderLists() {
  12432. let lists = new WeakMap();
  12433. function get( scene, renderCallDepth ) {
  12434. const listArray = lists.get( scene );
  12435. let list;
  12436. if ( listArray === undefined ) {
  12437. list = new WebGLRenderList();
  12438. lists.set( scene, [ list ] );
  12439. } else {
  12440. if ( renderCallDepth >= listArray.length ) {
  12441. list = new WebGLRenderList();
  12442. listArray.push( list );
  12443. } else {
  12444. list = listArray[ renderCallDepth ];
  12445. }
  12446. }
  12447. return list;
  12448. }
  12449. function dispose() {
  12450. lists = new WeakMap();
  12451. }
  12452. return {
  12453. get: get,
  12454. dispose: dispose
  12455. };
  12456. }
  12457. function UniformsCache() {
  12458. const lights = {};
  12459. return {
  12460. get: function ( light ) {
  12461. if ( lights[ light.id ] !== undefined ) {
  12462. return lights[ light.id ];
  12463. }
  12464. let uniforms;
  12465. switch ( light.type ) {
  12466. case 'DirectionalLight':
  12467. uniforms = {
  12468. direction: new Vector3(),
  12469. color: new Color()
  12470. };
  12471. break;
  12472. case 'SpotLight':
  12473. uniforms = {
  12474. position: new Vector3(),
  12475. direction: new Vector3(),
  12476. color: new Color(),
  12477. distance: 0,
  12478. coneCos: 0,
  12479. penumbraCos: 0,
  12480. decay: 0
  12481. };
  12482. break;
  12483. case 'PointLight':
  12484. uniforms = {
  12485. position: new Vector3(),
  12486. color: new Color(),
  12487. distance: 0,
  12488. decay: 0
  12489. };
  12490. break;
  12491. case 'HemisphereLight':
  12492. uniforms = {
  12493. direction: new Vector3(),
  12494. skyColor: new Color(),
  12495. groundColor: new Color()
  12496. };
  12497. break;
  12498. case 'RectAreaLight':
  12499. uniforms = {
  12500. color: new Color(),
  12501. position: new Vector3(),
  12502. halfWidth: new Vector3(),
  12503. halfHeight: new Vector3()
  12504. };
  12505. break;
  12506. }
  12507. lights[ light.id ] = uniforms;
  12508. return uniforms;
  12509. }
  12510. };
  12511. }
  12512. function ShadowUniformsCache() {
  12513. const lights = {};
  12514. return {
  12515. get: function ( light ) {
  12516. if ( lights[ light.id ] !== undefined ) {
  12517. return lights[ light.id ];
  12518. }
  12519. let uniforms;
  12520. switch ( light.type ) {
  12521. case 'DirectionalLight':
  12522. uniforms = {
  12523. shadowBias: 0,
  12524. shadowNormalBias: 0,
  12525. shadowRadius: 1,
  12526. shadowMapSize: new Vector2()
  12527. };
  12528. break;
  12529. case 'SpotLight':
  12530. uniforms = {
  12531. shadowBias: 0,
  12532. shadowNormalBias: 0,
  12533. shadowRadius: 1,
  12534. shadowMapSize: new Vector2()
  12535. };
  12536. break;
  12537. case 'PointLight':
  12538. uniforms = {
  12539. shadowBias: 0,
  12540. shadowNormalBias: 0,
  12541. shadowRadius: 1,
  12542. shadowMapSize: new Vector2(),
  12543. shadowCameraNear: 1,
  12544. shadowCameraFar: 1000
  12545. };
  12546. break;
  12547. // TODO (abelnation): set RectAreaLight shadow uniforms
  12548. }
  12549. lights[ light.id ] = uniforms;
  12550. return uniforms;
  12551. }
  12552. };
  12553. }
  12554. let nextVersion = 0;
  12555. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12556. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12557. }
  12558. function WebGLLights( extensions, capabilities ) {
  12559. const cache = new UniformsCache();
  12560. const shadowCache = ShadowUniformsCache();
  12561. const state = {
  12562. version: 0,
  12563. hash: {
  12564. directionalLength: - 1,
  12565. pointLength: - 1,
  12566. spotLength: - 1,
  12567. rectAreaLength: - 1,
  12568. hemiLength: - 1,
  12569. numDirectionalShadows: - 1,
  12570. numPointShadows: - 1,
  12571. numSpotShadows: - 1,
  12572. numSpotMaps: - 1
  12573. },
  12574. ambient: [ 0, 0, 0 ],
  12575. probe: [],
  12576. directional: [],
  12577. directionalShadow: [],
  12578. directionalShadowMap: [],
  12579. directionalShadowMatrix: [],
  12580. spot: [],
  12581. spotLightMap: [],
  12582. spotShadow: [],
  12583. spotShadowMap: [],
  12584. spotLightMatrix: [],
  12585. rectArea: [],
  12586. rectAreaLTC1: null,
  12587. rectAreaLTC2: null,
  12588. point: [],
  12589. pointShadow: [],
  12590. pointShadowMap: [],
  12591. pointShadowMatrix: [],
  12592. hemi: [],
  12593. numSpotLightShadowsWithMaps: 0
  12594. };
  12595. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12596. const vector3 = new Vector3();
  12597. const matrix4 = new Matrix4();
  12598. const matrix42 = new Matrix4();
  12599. function setup( lights, useLegacyLights ) {
  12600. let r = 0, g = 0, b = 0;
  12601. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12602. let directionalLength = 0;
  12603. let pointLength = 0;
  12604. let spotLength = 0;
  12605. let rectAreaLength = 0;
  12606. let hemiLength = 0;
  12607. let numDirectionalShadows = 0;
  12608. let numPointShadows = 0;
  12609. let numSpotShadows = 0;
  12610. let numSpotMaps = 0;
  12611. let numSpotShadowsWithMaps = 0;
  12612. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12613. lights.sort( shadowCastingAndTexturingLightsFirst );
  12614. // artist-friendly light intensity scaling factor
  12615. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  12616. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12617. const light = lights[ i ];
  12618. const color = light.color;
  12619. const intensity = light.intensity;
  12620. const distance = light.distance;
  12621. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12622. if ( light.isAmbientLight ) {
  12623. r += color.r * intensity * scaleFactor;
  12624. g += color.g * intensity * scaleFactor;
  12625. b += color.b * intensity * scaleFactor;
  12626. } else if ( light.isLightProbe ) {
  12627. for ( let j = 0; j < 9; j ++ ) {
  12628. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12629. }
  12630. } else if ( light.isDirectionalLight ) {
  12631. const uniforms = cache.get( light );
  12632. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12633. if ( light.castShadow ) {
  12634. const shadow = light.shadow;
  12635. const shadowUniforms = shadowCache.get( light );
  12636. shadowUniforms.shadowBias = shadow.bias;
  12637. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12638. shadowUniforms.shadowRadius = shadow.radius;
  12639. shadowUniforms.shadowMapSize = shadow.mapSize;
  12640. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12641. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12642. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12643. numDirectionalShadows ++;
  12644. }
  12645. state.directional[ directionalLength ] = uniforms;
  12646. directionalLength ++;
  12647. } else if ( light.isSpotLight ) {
  12648. const uniforms = cache.get( light );
  12649. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12650. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12651. uniforms.distance = distance;
  12652. uniforms.coneCos = Math.cos( light.angle );
  12653. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12654. uniforms.decay = light.decay;
  12655. state.spot[ spotLength ] = uniforms;
  12656. const shadow = light.shadow;
  12657. if ( light.map ) {
  12658. state.spotLightMap[ numSpotMaps ] = light.map;
  12659. numSpotMaps ++;
  12660. // make sure the lightMatrix is up to date
  12661. // TODO : do it if required only
  12662. shadow.updateMatrices( light );
  12663. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12664. }
  12665. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12666. if ( light.castShadow ) {
  12667. const shadowUniforms = shadowCache.get( light );
  12668. shadowUniforms.shadowBias = shadow.bias;
  12669. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12670. shadowUniforms.shadowRadius = shadow.radius;
  12671. shadowUniforms.shadowMapSize = shadow.mapSize;
  12672. state.spotShadow[ spotLength ] = shadowUniforms;
  12673. state.spotShadowMap[ spotLength ] = shadowMap;
  12674. numSpotShadows ++;
  12675. }
  12676. spotLength ++;
  12677. } else if ( light.isRectAreaLight ) {
  12678. const uniforms = cache.get( light );
  12679. uniforms.color.copy( color ).multiplyScalar( intensity );
  12680. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12681. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12682. state.rectArea[ rectAreaLength ] = uniforms;
  12683. rectAreaLength ++;
  12684. } else if ( light.isPointLight ) {
  12685. const uniforms = cache.get( light );
  12686. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12687. uniforms.distance = light.distance;
  12688. uniforms.decay = light.decay;
  12689. if ( light.castShadow ) {
  12690. const shadow = light.shadow;
  12691. const shadowUniforms = shadowCache.get( light );
  12692. shadowUniforms.shadowBias = shadow.bias;
  12693. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12694. shadowUniforms.shadowRadius = shadow.radius;
  12695. shadowUniforms.shadowMapSize = shadow.mapSize;
  12696. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12697. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12698. state.pointShadow[ pointLength ] = shadowUniforms;
  12699. state.pointShadowMap[ pointLength ] = shadowMap;
  12700. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12701. numPointShadows ++;
  12702. }
  12703. state.point[ pointLength ] = uniforms;
  12704. pointLength ++;
  12705. } else if ( light.isHemisphereLight ) {
  12706. const uniforms = cache.get( light );
  12707. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12708. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12709. state.hemi[ hemiLength ] = uniforms;
  12710. hemiLength ++;
  12711. }
  12712. }
  12713. if ( rectAreaLength > 0 ) {
  12714. if ( capabilities.isWebGL2 ) {
  12715. // WebGL 2
  12716. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12717. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12718. } else {
  12719. // WebGL 1
  12720. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12721. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12722. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12723. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12724. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12725. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12726. } else {
  12727. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12728. }
  12729. }
  12730. }
  12731. state.ambient[ 0 ] = r;
  12732. state.ambient[ 1 ] = g;
  12733. state.ambient[ 2 ] = b;
  12734. const hash = state.hash;
  12735. if ( hash.directionalLength !== directionalLength ||
  12736. hash.pointLength !== pointLength ||
  12737. hash.spotLength !== spotLength ||
  12738. hash.rectAreaLength !== rectAreaLength ||
  12739. hash.hemiLength !== hemiLength ||
  12740. hash.numDirectionalShadows !== numDirectionalShadows ||
  12741. hash.numPointShadows !== numPointShadows ||
  12742. hash.numSpotShadows !== numSpotShadows ||
  12743. hash.numSpotMaps !== numSpotMaps ) {
  12744. state.directional.length = directionalLength;
  12745. state.spot.length = spotLength;
  12746. state.rectArea.length = rectAreaLength;
  12747. state.point.length = pointLength;
  12748. state.hemi.length = hemiLength;
  12749. state.directionalShadow.length = numDirectionalShadows;
  12750. state.directionalShadowMap.length = numDirectionalShadows;
  12751. state.pointShadow.length = numPointShadows;
  12752. state.pointShadowMap.length = numPointShadows;
  12753. state.spotShadow.length = numSpotShadows;
  12754. state.spotShadowMap.length = numSpotShadows;
  12755. state.directionalShadowMatrix.length = numDirectionalShadows;
  12756. state.pointShadowMatrix.length = numPointShadows;
  12757. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12758. state.spotLightMap.length = numSpotMaps;
  12759. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12760. hash.directionalLength = directionalLength;
  12761. hash.pointLength = pointLength;
  12762. hash.spotLength = spotLength;
  12763. hash.rectAreaLength = rectAreaLength;
  12764. hash.hemiLength = hemiLength;
  12765. hash.numDirectionalShadows = numDirectionalShadows;
  12766. hash.numPointShadows = numPointShadows;
  12767. hash.numSpotShadows = numSpotShadows;
  12768. hash.numSpotMaps = numSpotMaps;
  12769. state.version = nextVersion ++;
  12770. }
  12771. }
  12772. function setupView( lights, camera ) {
  12773. let directionalLength = 0;
  12774. let pointLength = 0;
  12775. let spotLength = 0;
  12776. let rectAreaLength = 0;
  12777. let hemiLength = 0;
  12778. const viewMatrix = camera.matrixWorldInverse;
  12779. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12780. const light = lights[ i ];
  12781. if ( light.isDirectionalLight ) {
  12782. const uniforms = state.directional[ directionalLength ];
  12783. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12784. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12785. uniforms.direction.sub( vector3 );
  12786. uniforms.direction.transformDirection( viewMatrix );
  12787. directionalLength ++;
  12788. } else if ( light.isSpotLight ) {
  12789. const uniforms = state.spot[ spotLength ];
  12790. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12791. uniforms.position.applyMatrix4( viewMatrix );
  12792. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12793. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12794. uniforms.direction.sub( vector3 );
  12795. uniforms.direction.transformDirection( viewMatrix );
  12796. spotLength ++;
  12797. } else if ( light.isRectAreaLight ) {
  12798. const uniforms = state.rectArea[ rectAreaLength ];
  12799. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12800. uniforms.position.applyMatrix4( viewMatrix );
  12801. // extract local rotation of light to derive width/height half vectors
  12802. matrix42.identity();
  12803. matrix4.copy( light.matrixWorld );
  12804. matrix4.premultiply( viewMatrix );
  12805. matrix42.extractRotation( matrix4 );
  12806. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12807. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12808. uniforms.halfWidth.applyMatrix4( matrix42 );
  12809. uniforms.halfHeight.applyMatrix4( matrix42 );
  12810. rectAreaLength ++;
  12811. } else if ( light.isPointLight ) {
  12812. const uniforms = state.point[ pointLength ];
  12813. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12814. uniforms.position.applyMatrix4( viewMatrix );
  12815. pointLength ++;
  12816. } else if ( light.isHemisphereLight ) {
  12817. const uniforms = state.hemi[ hemiLength ];
  12818. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12819. uniforms.direction.transformDirection( viewMatrix );
  12820. hemiLength ++;
  12821. }
  12822. }
  12823. }
  12824. return {
  12825. setup: setup,
  12826. setupView: setupView,
  12827. state: state
  12828. };
  12829. }
  12830. function WebGLRenderState( extensions, capabilities ) {
  12831. const lights = new WebGLLights( extensions, capabilities );
  12832. const lightsArray = [];
  12833. const shadowsArray = [];
  12834. function init() {
  12835. lightsArray.length = 0;
  12836. shadowsArray.length = 0;
  12837. }
  12838. function pushLight( light ) {
  12839. lightsArray.push( light );
  12840. }
  12841. function pushShadow( shadowLight ) {
  12842. shadowsArray.push( shadowLight );
  12843. }
  12844. function setupLights( useLegacyLights ) {
  12845. lights.setup( lightsArray, useLegacyLights );
  12846. }
  12847. function setupLightsView( camera ) {
  12848. lights.setupView( lightsArray, camera );
  12849. }
  12850. const state = {
  12851. lightsArray: lightsArray,
  12852. shadowsArray: shadowsArray,
  12853. lights: lights
  12854. };
  12855. return {
  12856. init: init,
  12857. state: state,
  12858. setupLights: setupLights,
  12859. setupLightsView: setupLightsView,
  12860. pushLight: pushLight,
  12861. pushShadow: pushShadow
  12862. };
  12863. }
  12864. function WebGLRenderStates( extensions, capabilities ) {
  12865. let renderStates = new WeakMap();
  12866. function get( scene, renderCallDepth = 0 ) {
  12867. const renderStateArray = renderStates.get( scene );
  12868. let renderState;
  12869. if ( renderStateArray === undefined ) {
  12870. renderState = new WebGLRenderState( extensions, capabilities );
  12871. renderStates.set( scene, [ renderState ] );
  12872. } else {
  12873. if ( renderCallDepth >= renderStateArray.length ) {
  12874. renderState = new WebGLRenderState( extensions, capabilities );
  12875. renderStateArray.push( renderState );
  12876. } else {
  12877. renderState = renderStateArray[ renderCallDepth ];
  12878. }
  12879. }
  12880. return renderState;
  12881. }
  12882. function dispose() {
  12883. renderStates = new WeakMap();
  12884. }
  12885. return {
  12886. get: get,
  12887. dispose: dispose
  12888. };
  12889. }
  12890. class MeshDepthMaterial extends Material {
  12891. constructor( parameters ) {
  12892. super();
  12893. this.isMeshDepthMaterial = true;
  12894. this.type = 'MeshDepthMaterial';
  12895. this.depthPacking = BasicDepthPacking;
  12896. this.map = null;
  12897. this.alphaMap = null;
  12898. this.displacementMap = null;
  12899. this.displacementScale = 1;
  12900. this.displacementBias = 0;
  12901. this.wireframe = false;
  12902. this.wireframeLinewidth = 1;
  12903. this.setValues( parameters );
  12904. }
  12905. copy( source ) {
  12906. super.copy( source );
  12907. this.depthPacking = source.depthPacking;
  12908. this.map = source.map;
  12909. this.alphaMap = source.alphaMap;
  12910. this.displacementMap = source.displacementMap;
  12911. this.displacementScale = source.displacementScale;
  12912. this.displacementBias = source.displacementBias;
  12913. this.wireframe = source.wireframe;
  12914. this.wireframeLinewidth = source.wireframeLinewidth;
  12915. return this;
  12916. }
  12917. }
  12918. class MeshDistanceMaterial extends Material {
  12919. constructor( parameters ) {
  12920. super();
  12921. this.isMeshDistanceMaterial = true;
  12922. this.type = 'MeshDistanceMaterial';
  12923. this.map = null;
  12924. this.alphaMap = null;
  12925. this.displacementMap = null;
  12926. this.displacementScale = 1;
  12927. this.displacementBias = 0;
  12928. this.setValues( parameters );
  12929. }
  12930. copy( source ) {
  12931. super.copy( source );
  12932. this.map = source.map;
  12933. this.alphaMap = source.alphaMap;
  12934. this.displacementMap = source.displacementMap;
  12935. this.displacementScale = source.displacementScale;
  12936. this.displacementBias = source.displacementBias;
  12937. return this;
  12938. }
  12939. }
  12940. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12941. 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}";
  12942. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12943. let _frustum = new Frustum();
  12944. const _shadowMapSize = new Vector2(),
  12945. _viewportSize = new Vector2(),
  12946. _viewport = new Vector4(),
  12947. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12948. _distanceMaterial = new MeshDistanceMaterial(),
  12949. _materialCache = {},
  12950. _maxTextureSize = _capabilities.maxTextureSize;
  12951. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  12952. const shadowMaterialVertical = new ShaderMaterial( {
  12953. defines: {
  12954. VSM_SAMPLES: 8
  12955. },
  12956. uniforms: {
  12957. shadow_pass: { value: null },
  12958. resolution: { value: new Vector2() },
  12959. radius: { value: 4.0 }
  12960. },
  12961. vertexShader: vertex,
  12962. fragmentShader: fragment
  12963. } );
  12964. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12965. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12966. const fullScreenTri = new BufferGeometry();
  12967. fullScreenTri.setAttribute(
  12968. 'position',
  12969. new BufferAttribute(
  12970. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12971. 3
  12972. )
  12973. );
  12974. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12975. const scope = this;
  12976. this.enabled = false;
  12977. this.autoUpdate = true;
  12978. this.needsUpdate = false;
  12979. this.type = PCFShadowMap;
  12980. this.render = function ( lights, scene, camera ) {
  12981. if ( scope.enabled === false ) return;
  12982. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12983. if ( lights.length === 0 ) return;
  12984. const currentRenderTarget = _renderer.getRenderTarget();
  12985. const activeCubeFace = _renderer.getActiveCubeFace();
  12986. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12987. const _state = _renderer.state;
  12988. // Set GL state for depth map.
  12989. _state.setBlending( NoBlending );
  12990. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12991. _state.buffers.depth.setTest( true );
  12992. _state.setScissorTest( false );
  12993. // render depth map
  12994. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12995. const light = lights[ i ];
  12996. const shadow = light.shadow;
  12997. if ( shadow === undefined ) {
  12998. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12999. continue;
  13000. }
  13001. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13002. _shadowMapSize.copy( shadow.mapSize );
  13003. const shadowFrameExtents = shadow.getFrameExtents();
  13004. _shadowMapSize.multiply( shadowFrameExtents );
  13005. _viewportSize.copy( shadow.mapSize );
  13006. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13007. if ( _shadowMapSize.x > _maxTextureSize ) {
  13008. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13009. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13010. shadow.mapSize.x = _viewportSize.x;
  13011. }
  13012. if ( _shadowMapSize.y > _maxTextureSize ) {
  13013. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13014. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13015. shadow.mapSize.y = _viewportSize.y;
  13016. }
  13017. }
  13018. if ( shadow.map === null ) {
  13019. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13020. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13021. shadow.map.texture.name = light.name + '.shadowMap';
  13022. shadow.camera.updateProjectionMatrix();
  13023. }
  13024. _renderer.setRenderTarget( shadow.map );
  13025. _renderer.clear();
  13026. const viewportCount = shadow.getViewportCount();
  13027. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13028. const viewport = shadow.getViewport( vp );
  13029. _viewport.set(
  13030. _viewportSize.x * viewport.x,
  13031. _viewportSize.y * viewport.y,
  13032. _viewportSize.x * viewport.z,
  13033. _viewportSize.y * viewport.w
  13034. );
  13035. _state.viewport( _viewport );
  13036. shadow.updateMatrices( light, vp );
  13037. _frustum = shadow.getFrustum();
  13038. renderObject( scene, camera, shadow.camera, light, this.type );
  13039. }
  13040. // do blur pass for VSM
  13041. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13042. VSMPass( shadow, camera );
  13043. }
  13044. shadow.needsUpdate = false;
  13045. }
  13046. scope.needsUpdate = false;
  13047. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13048. };
  13049. function VSMPass( shadow, camera ) {
  13050. const geometry = _objects.update( fullScreenMesh );
  13051. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13052. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13053. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13054. shadowMaterialVertical.needsUpdate = true;
  13055. shadowMaterialHorizontal.needsUpdate = true;
  13056. }
  13057. if ( shadow.mapPass === null ) {
  13058. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13059. }
  13060. // vertical pass
  13061. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13062. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13063. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13064. _renderer.setRenderTarget( shadow.mapPass );
  13065. _renderer.clear();
  13066. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13067. // horizontal pass
  13068. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13069. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13070. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13071. _renderer.setRenderTarget( shadow.map );
  13072. _renderer.clear();
  13073. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13074. }
  13075. function getDepthMaterial( object, material, light, type ) {
  13076. let result = null;
  13077. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13078. if ( customMaterial !== undefined ) {
  13079. result = customMaterial;
  13080. } else {
  13081. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13082. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13083. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13084. ( material.alphaMap && material.alphaTest > 0 ) ||
  13085. ( material.map && material.alphaTest > 0 ) ) {
  13086. // in this case we need a unique material instance reflecting the
  13087. // appropriate state
  13088. const keyA = result.uuid, keyB = material.uuid;
  13089. let materialsForVariant = _materialCache[ keyA ];
  13090. if ( materialsForVariant === undefined ) {
  13091. materialsForVariant = {};
  13092. _materialCache[ keyA ] = materialsForVariant;
  13093. }
  13094. let cachedMaterial = materialsForVariant[ keyB ];
  13095. if ( cachedMaterial === undefined ) {
  13096. cachedMaterial = result.clone();
  13097. materialsForVariant[ keyB ] = cachedMaterial;
  13098. }
  13099. result = cachedMaterial;
  13100. }
  13101. }
  13102. result.visible = material.visible;
  13103. result.wireframe = material.wireframe;
  13104. if ( type === VSMShadowMap ) {
  13105. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13106. } else {
  13107. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13108. }
  13109. result.alphaMap = material.alphaMap;
  13110. result.alphaTest = material.alphaTest;
  13111. result.map = material.map;
  13112. result.clipShadows = material.clipShadows;
  13113. result.clippingPlanes = material.clippingPlanes;
  13114. result.clipIntersection = material.clipIntersection;
  13115. result.displacementMap = material.displacementMap;
  13116. result.displacementScale = material.displacementScale;
  13117. result.displacementBias = material.displacementBias;
  13118. result.wireframeLinewidth = material.wireframeLinewidth;
  13119. result.linewidth = material.linewidth;
  13120. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13121. const materialProperties = _renderer.properties.get( result );
  13122. materialProperties.light = light;
  13123. }
  13124. return result;
  13125. }
  13126. function renderObject( object, camera, shadowCamera, light, type ) {
  13127. if ( object.visible === false ) return;
  13128. const visible = object.layers.test( camera.layers );
  13129. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13130. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13131. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13132. const geometry = _objects.update( object );
  13133. const material = object.material;
  13134. if ( Array.isArray( material ) ) {
  13135. const groups = geometry.groups;
  13136. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13137. const group = groups[ k ];
  13138. const groupMaterial = material[ group.materialIndex ];
  13139. if ( groupMaterial && groupMaterial.visible ) {
  13140. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13141. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13142. }
  13143. }
  13144. } else if ( material.visible ) {
  13145. const depthMaterial = getDepthMaterial( object, material, light, type );
  13146. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13147. }
  13148. }
  13149. }
  13150. const children = object.children;
  13151. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13152. renderObject( children[ i ], camera, shadowCamera, light, type );
  13153. }
  13154. }
  13155. }
  13156. function WebGLState( gl, extensions, capabilities ) {
  13157. const isWebGL2 = capabilities.isWebGL2;
  13158. function ColorBuffer() {
  13159. let locked = false;
  13160. const color = new Vector4();
  13161. let currentColorMask = null;
  13162. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13163. return {
  13164. setMask: function ( colorMask ) {
  13165. if ( currentColorMask !== colorMask && ! locked ) {
  13166. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13167. currentColorMask = colorMask;
  13168. }
  13169. },
  13170. setLocked: function ( lock ) {
  13171. locked = lock;
  13172. },
  13173. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13174. if ( premultipliedAlpha === true ) {
  13175. r *= a; g *= a; b *= a;
  13176. }
  13177. color.set( r, g, b, a );
  13178. if ( currentColorClear.equals( color ) === false ) {
  13179. gl.clearColor( r, g, b, a );
  13180. currentColorClear.copy( color );
  13181. }
  13182. },
  13183. reset: function () {
  13184. locked = false;
  13185. currentColorMask = null;
  13186. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13187. }
  13188. };
  13189. }
  13190. function DepthBuffer() {
  13191. let locked = false;
  13192. let currentDepthMask = null;
  13193. let currentDepthFunc = null;
  13194. let currentDepthClear = null;
  13195. return {
  13196. setTest: function ( depthTest ) {
  13197. if ( depthTest ) {
  13198. enable( 2929 );
  13199. } else {
  13200. disable( 2929 );
  13201. }
  13202. },
  13203. setMask: function ( depthMask ) {
  13204. if ( currentDepthMask !== depthMask && ! locked ) {
  13205. gl.depthMask( depthMask );
  13206. currentDepthMask = depthMask;
  13207. }
  13208. },
  13209. setFunc: function ( depthFunc ) {
  13210. if ( currentDepthFunc !== depthFunc ) {
  13211. switch ( depthFunc ) {
  13212. case NeverDepth:
  13213. gl.depthFunc( 512 );
  13214. break;
  13215. case AlwaysDepth:
  13216. gl.depthFunc( 519 );
  13217. break;
  13218. case LessDepth:
  13219. gl.depthFunc( 513 );
  13220. break;
  13221. case LessEqualDepth:
  13222. gl.depthFunc( 515 );
  13223. break;
  13224. case EqualDepth:
  13225. gl.depthFunc( 514 );
  13226. break;
  13227. case GreaterEqualDepth:
  13228. gl.depthFunc( 518 );
  13229. break;
  13230. case GreaterDepth:
  13231. gl.depthFunc( 516 );
  13232. break;
  13233. case NotEqualDepth:
  13234. gl.depthFunc( 517 );
  13235. break;
  13236. default:
  13237. gl.depthFunc( 515 );
  13238. }
  13239. currentDepthFunc = depthFunc;
  13240. }
  13241. },
  13242. setLocked: function ( lock ) {
  13243. locked = lock;
  13244. },
  13245. setClear: function ( depth ) {
  13246. if ( currentDepthClear !== depth ) {
  13247. gl.clearDepth( depth );
  13248. currentDepthClear = depth;
  13249. }
  13250. },
  13251. reset: function () {
  13252. locked = false;
  13253. currentDepthMask = null;
  13254. currentDepthFunc = null;
  13255. currentDepthClear = null;
  13256. }
  13257. };
  13258. }
  13259. function StencilBuffer() {
  13260. let locked = false;
  13261. let currentStencilMask = null;
  13262. let currentStencilFunc = null;
  13263. let currentStencilRef = null;
  13264. let currentStencilFuncMask = null;
  13265. let currentStencilFail = null;
  13266. let currentStencilZFail = null;
  13267. let currentStencilZPass = null;
  13268. let currentStencilClear = null;
  13269. return {
  13270. setTest: function ( stencilTest ) {
  13271. if ( ! locked ) {
  13272. if ( stencilTest ) {
  13273. enable( 2960 );
  13274. } else {
  13275. disable( 2960 );
  13276. }
  13277. }
  13278. },
  13279. setMask: function ( stencilMask ) {
  13280. if ( currentStencilMask !== stencilMask && ! locked ) {
  13281. gl.stencilMask( stencilMask );
  13282. currentStencilMask = stencilMask;
  13283. }
  13284. },
  13285. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13286. if ( currentStencilFunc !== stencilFunc ||
  13287. currentStencilRef !== stencilRef ||
  13288. currentStencilFuncMask !== stencilMask ) {
  13289. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13290. currentStencilFunc = stencilFunc;
  13291. currentStencilRef = stencilRef;
  13292. currentStencilFuncMask = stencilMask;
  13293. }
  13294. },
  13295. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13296. if ( currentStencilFail !== stencilFail ||
  13297. currentStencilZFail !== stencilZFail ||
  13298. currentStencilZPass !== stencilZPass ) {
  13299. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13300. currentStencilFail = stencilFail;
  13301. currentStencilZFail = stencilZFail;
  13302. currentStencilZPass = stencilZPass;
  13303. }
  13304. },
  13305. setLocked: function ( lock ) {
  13306. locked = lock;
  13307. },
  13308. setClear: function ( stencil ) {
  13309. if ( currentStencilClear !== stencil ) {
  13310. gl.clearStencil( stencil );
  13311. currentStencilClear = stencil;
  13312. }
  13313. },
  13314. reset: function () {
  13315. locked = false;
  13316. currentStencilMask = null;
  13317. currentStencilFunc = null;
  13318. currentStencilRef = null;
  13319. currentStencilFuncMask = null;
  13320. currentStencilFail = null;
  13321. currentStencilZFail = null;
  13322. currentStencilZPass = null;
  13323. currentStencilClear = null;
  13324. }
  13325. };
  13326. }
  13327. //
  13328. const colorBuffer = new ColorBuffer();
  13329. const depthBuffer = new DepthBuffer();
  13330. const stencilBuffer = new StencilBuffer();
  13331. const uboBindings = new WeakMap();
  13332. const uboProgramMap = new WeakMap();
  13333. let enabledCapabilities = {};
  13334. let currentBoundFramebuffers = {};
  13335. let currentDrawbuffers = new WeakMap();
  13336. let defaultDrawbuffers = [];
  13337. let currentProgram = null;
  13338. let currentBlendingEnabled = false;
  13339. let currentBlending = null;
  13340. let currentBlendEquation = null;
  13341. let currentBlendSrc = null;
  13342. let currentBlendDst = null;
  13343. let currentBlendEquationAlpha = null;
  13344. let currentBlendSrcAlpha = null;
  13345. let currentBlendDstAlpha = null;
  13346. let currentPremultipledAlpha = false;
  13347. let currentFlipSided = null;
  13348. let currentCullFace = null;
  13349. let currentLineWidth = null;
  13350. let currentPolygonOffsetFactor = null;
  13351. let currentPolygonOffsetUnits = null;
  13352. const maxTextures = gl.getParameter( 35661 );
  13353. let lineWidthAvailable = false;
  13354. let version = 0;
  13355. const glVersion = gl.getParameter( 7938 );
  13356. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13357. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13358. lineWidthAvailable = ( version >= 1.0 );
  13359. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13360. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13361. lineWidthAvailable = ( version >= 2.0 );
  13362. }
  13363. let currentTextureSlot = null;
  13364. let currentBoundTextures = {};
  13365. const scissorParam = gl.getParameter( 3088 );
  13366. const viewportParam = gl.getParameter( 2978 );
  13367. const currentScissor = new Vector4().fromArray( scissorParam );
  13368. const currentViewport = new Vector4().fromArray( viewportParam );
  13369. function createTexture( type, target, count ) {
  13370. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13371. const texture = gl.createTexture();
  13372. gl.bindTexture( type, texture );
  13373. gl.texParameteri( type, 10241, 9728 );
  13374. gl.texParameteri( type, 10240, 9728 );
  13375. for ( let i = 0; i < count; i ++ ) {
  13376. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  13377. }
  13378. return texture;
  13379. }
  13380. const emptyTextures = {};
  13381. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  13382. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  13383. // init
  13384. colorBuffer.setClear( 0, 0, 0, 1 );
  13385. depthBuffer.setClear( 1 );
  13386. stencilBuffer.setClear( 0 );
  13387. enable( 2929 );
  13388. depthBuffer.setFunc( LessEqualDepth );
  13389. setFlipSided( false );
  13390. setCullFace( CullFaceBack );
  13391. enable( 2884 );
  13392. setBlending( NoBlending );
  13393. //
  13394. function enable( id ) {
  13395. if ( enabledCapabilities[ id ] !== true ) {
  13396. gl.enable( id );
  13397. enabledCapabilities[ id ] = true;
  13398. }
  13399. }
  13400. function disable( id ) {
  13401. if ( enabledCapabilities[ id ] !== false ) {
  13402. gl.disable( id );
  13403. enabledCapabilities[ id ] = false;
  13404. }
  13405. }
  13406. function bindFramebuffer( target, framebuffer ) {
  13407. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13408. gl.bindFramebuffer( target, framebuffer );
  13409. currentBoundFramebuffers[ target ] = framebuffer;
  13410. if ( isWebGL2 ) {
  13411. // 36009 is equivalent to 36160
  13412. if ( target === 36009 ) {
  13413. currentBoundFramebuffers[ 36160 ] = framebuffer;
  13414. }
  13415. if ( target === 36160 ) {
  13416. currentBoundFramebuffers[ 36009 ] = framebuffer;
  13417. }
  13418. }
  13419. return true;
  13420. }
  13421. return false;
  13422. }
  13423. function drawBuffers( renderTarget, framebuffer ) {
  13424. let drawBuffers = defaultDrawbuffers;
  13425. let needsUpdate = false;
  13426. if ( renderTarget ) {
  13427. drawBuffers = currentDrawbuffers.get( framebuffer );
  13428. if ( drawBuffers === undefined ) {
  13429. drawBuffers = [];
  13430. currentDrawbuffers.set( framebuffer, drawBuffers );
  13431. }
  13432. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13433. const textures = renderTarget.texture;
  13434. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) {
  13435. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13436. drawBuffers[ i ] = 36064 + i;
  13437. }
  13438. drawBuffers.length = textures.length;
  13439. needsUpdate = true;
  13440. }
  13441. } else {
  13442. if ( drawBuffers[ 0 ] !== 36064 ) {
  13443. drawBuffers[ 0 ] = 36064;
  13444. needsUpdate = true;
  13445. }
  13446. }
  13447. } else {
  13448. if ( drawBuffers[ 0 ] !== 1029 ) {
  13449. drawBuffers[ 0 ] = 1029;
  13450. needsUpdate = true;
  13451. }
  13452. }
  13453. if ( needsUpdate ) {
  13454. if ( capabilities.isWebGL2 ) {
  13455. gl.drawBuffers( drawBuffers );
  13456. } else {
  13457. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13458. }
  13459. }
  13460. }
  13461. function useProgram( program ) {
  13462. if ( currentProgram !== program ) {
  13463. gl.useProgram( program );
  13464. currentProgram = program;
  13465. return true;
  13466. }
  13467. return false;
  13468. }
  13469. const equationToGL = {
  13470. [ AddEquation ]: 32774,
  13471. [ SubtractEquation ]: 32778,
  13472. [ ReverseSubtractEquation ]: 32779
  13473. };
  13474. if ( isWebGL2 ) {
  13475. equationToGL[ MinEquation ] = 32775;
  13476. equationToGL[ MaxEquation ] = 32776;
  13477. } else {
  13478. const extension = extensions.get( 'EXT_blend_minmax' );
  13479. if ( extension !== null ) {
  13480. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13481. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13482. }
  13483. }
  13484. const factorToGL = {
  13485. [ ZeroFactor ]: 0,
  13486. [ OneFactor ]: 1,
  13487. [ SrcColorFactor ]: 768,
  13488. [ SrcAlphaFactor ]: 770,
  13489. [ SrcAlphaSaturateFactor ]: 776,
  13490. [ DstColorFactor ]: 774,
  13491. [ DstAlphaFactor ]: 772,
  13492. [ OneMinusSrcColorFactor ]: 769,
  13493. [ OneMinusSrcAlphaFactor ]: 771,
  13494. [ OneMinusDstColorFactor ]: 775,
  13495. [ OneMinusDstAlphaFactor ]: 773
  13496. };
  13497. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13498. if ( blending === NoBlending ) {
  13499. if ( currentBlendingEnabled === true ) {
  13500. disable( 3042 );
  13501. currentBlendingEnabled = false;
  13502. }
  13503. return;
  13504. }
  13505. if ( currentBlendingEnabled === false ) {
  13506. enable( 3042 );
  13507. currentBlendingEnabled = true;
  13508. }
  13509. if ( blending !== CustomBlending ) {
  13510. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13511. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13512. gl.blendEquation( 32774 );
  13513. currentBlendEquation = AddEquation;
  13514. currentBlendEquationAlpha = AddEquation;
  13515. }
  13516. if ( premultipliedAlpha ) {
  13517. switch ( blending ) {
  13518. case NormalBlending:
  13519. gl.blendFuncSeparate( 1, 771, 1, 771 );
  13520. break;
  13521. case AdditiveBlending:
  13522. gl.blendFunc( 1, 1 );
  13523. break;
  13524. case SubtractiveBlending:
  13525. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13526. break;
  13527. case MultiplyBlending:
  13528. gl.blendFuncSeparate( 0, 768, 0, 770 );
  13529. break;
  13530. default:
  13531. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13532. break;
  13533. }
  13534. } else {
  13535. switch ( blending ) {
  13536. case NormalBlending:
  13537. gl.blendFuncSeparate( 770, 771, 1, 771 );
  13538. break;
  13539. case AdditiveBlending:
  13540. gl.blendFunc( 770, 1 );
  13541. break;
  13542. case SubtractiveBlending:
  13543. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13544. break;
  13545. case MultiplyBlending:
  13546. gl.blendFunc( 0, 768 );
  13547. break;
  13548. default:
  13549. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13550. break;
  13551. }
  13552. }
  13553. currentBlendSrc = null;
  13554. currentBlendDst = null;
  13555. currentBlendSrcAlpha = null;
  13556. currentBlendDstAlpha = null;
  13557. currentBlending = blending;
  13558. currentPremultipledAlpha = premultipliedAlpha;
  13559. }
  13560. return;
  13561. }
  13562. // custom blending
  13563. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13564. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13565. blendDstAlpha = blendDstAlpha || blendDst;
  13566. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13567. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13568. currentBlendEquation = blendEquation;
  13569. currentBlendEquationAlpha = blendEquationAlpha;
  13570. }
  13571. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13572. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13573. currentBlendSrc = blendSrc;
  13574. currentBlendDst = blendDst;
  13575. currentBlendSrcAlpha = blendSrcAlpha;
  13576. currentBlendDstAlpha = blendDstAlpha;
  13577. }
  13578. currentBlending = blending;
  13579. currentPremultipledAlpha = false;
  13580. }
  13581. function setMaterial( material, frontFaceCW ) {
  13582. material.side === DoubleSide
  13583. ? disable( 2884 )
  13584. : enable( 2884 );
  13585. let flipSided = ( material.side === BackSide );
  13586. if ( frontFaceCW ) flipSided = ! flipSided;
  13587. setFlipSided( flipSided );
  13588. ( material.blending === NormalBlending && material.transparent === false )
  13589. ? setBlending( NoBlending )
  13590. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13591. depthBuffer.setFunc( material.depthFunc );
  13592. depthBuffer.setTest( material.depthTest );
  13593. depthBuffer.setMask( material.depthWrite );
  13594. colorBuffer.setMask( material.colorWrite );
  13595. const stencilWrite = material.stencilWrite;
  13596. stencilBuffer.setTest( stencilWrite );
  13597. if ( stencilWrite ) {
  13598. stencilBuffer.setMask( material.stencilWriteMask );
  13599. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13600. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13601. }
  13602. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13603. material.alphaToCoverage === true
  13604. ? enable( 32926 )
  13605. : disable( 32926 );
  13606. }
  13607. //
  13608. function setFlipSided( flipSided ) {
  13609. if ( currentFlipSided !== flipSided ) {
  13610. if ( flipSided ) {
  13611. gl.frontFace( 2304 );
  13612. } else {
  13613. gl.frontFace( 2305 );
  13614. }
  13615. currentFlipSided = flipSided;
  13616. }
  13617. }
  13618. function setCullFace( cullFace ) {
  13619. if ( cullFace !== CullFaceNone ) {
  13620. enable( 2884 );
  13621. if ( cullFace !== currentCullFace ) {
  13622. if ( cullFace === CullFaceBack ) {
  13623. gl.cullFace( 1029 );
  13624. } else if ( cullFace === CullFaceFront ) {
  13625. gl.cullFace( 1028 );
  13626. } else {
  13627. gl.cullFace( 1032 );
  13628. }
  13629. }
  13630. } else {
  13631. disable( 2884 );
  13632. }
  13633. currentCullFace = cullFace;
  13634. }
  13635. function setLineWidth( width ) {
  13636. if ( width !== currentLineWidth ) {
  13637. if ( lineWidthAvailable ) gl.lineWidth( width );
  13638. currentLineWidth = width;
  13639. }
  13640. }
  13641. function setPolygonOffset( polygonOffset, factor, units ) {
  13642. if ( polygonOffset ) {
  13643. enable( 32823 );
  13644. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13645. gl.polygonOffset( factor, units );
  13646. currentPolygonOffsetFactor = factor;
  13647. currentPolygonOffsetUnits = units;
  13648. }
  13649. } else {
  13650. disable( 32823 );
  13651. }
  13652. }
  13653. function setScissorTest( scissorTest ) {
  13654. if ( scissorTest ) {
  13655. enable( 3089 );
  13656. } else {
  13657. disable( 3089 );
  13658. }
  13659. }
  13660. // texture
  13661. function activeTexture( webglSlot ) {
  13662. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  13663. if ( currentTextureSlot !== webglSlot ) {
  13664. gl.activeTexture( webglSlot );
  13665. currentTextureSlot = webglSlot;
  13666. }
  13667. }
  13668. function bindTexture( webglType, webglTexture, webglSlot ) {
  13669. if ( webglSlot === undefined ) {
  13670. if ( currentTextureSlot === null ) {
  13671. webglSlot = 33984 + maxTextures - 1;
  13672. } else {
  13673. webglSlot = currentTextureSlot;
  13674. }
  13675. }
  13676. let boundTexture = currentBoundTextures[ webglSlot ];
  13677. if ( boundTexture === undefined ) {
  13678. boundTexture = { type: undefined, texture: undefined };
  13679. currentBoundTextures[ webglSlot ] = boundTexture;
  13680. }
  13681. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13682. if ( currentTextureSlot !== webglSlot ) {
  13683. gl.activeTexture( webglSlot );
  13684. currentTextureSlot = webglSlot;
  13685. }
  13686. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13687. boundTexture.type = webglType;
  13688. boundTexture.texture = webglTexture;
  13689. }
  13690. }
  13691. function unbindTexture() {
  13692. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13693. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13694. gl.bindTexture( boundTexture.type, null );
  13695. boundTexture.type = undefined;
  13696. boundTexture.texture = undefined;
  13697. }
  13698. }
  13699. function compressedTexImage2D() {
  13700. try {
  13701. gl.compressedTexImage2D.apply( gl, arguments );
  13702. } catch ( error ) {
  13703. console.error( 'THREE.WebGLState:', error );
  13704. }
  13705. }
  13706. function compressedTexImage3D() {
  13707. try {
  13708. gl.compressedTexImage3D.apply( gl, arguments );
  13709. } catch ( error ) {
  13710. console.error( 'THREE.WebGLState:', error );
  13711. }
  13712. }
  13713. function texSubImage2D() {
  13714. try {
  13715. gl.texSubImage2D.apply( gl, arguments );
  13716. } catch ( error ) {
  13717. console.error( 'THREE.WebGLState:', error );
  13718. }
  13719. }
  13720. function texSubImage3D() {
  13721. try {
  13722. gl.texSubImage3D.apply( gl, arguments );
  13723. } catch ( error ) {
  13724. console.error( 'THREE.WebGLState:', error );
  13725. }
  13726. }
  13727. function compressedTexSubImage2D() {
  13728. try {
  13729. gl.compressedTexSubImage2D.apply( gl, arguments );
  13730. } catch ( error ) {
  13731. console.error( 'THREE.WebGLState:', error );
  13732. }
  13733. }
  13734. function compressedTexSubImage3D() {
  13735. try {
  13736. gl.compressedTexSubImage3D.apply( gl, arguments );
  13737. } catch ( error ) {
  13738. console.error( 'THREE.WebGLState:', error );
  13739. }
  13740. }
  13741. function texStorage2D() {
  13742. try {
  13743. gl.texStorage2D.apply( gl, arguments );
  13744. } catch ( error ) {
  13745. console.error( 'THREE.WebGLState:', error );
  13746. }
  13747. }
  13748. function texStorage3D() {
  13749. try {
  13750. gl.texStorage3D.apply( gl, arguments );
  13751. } catch ( error ) {
  13752. console.error( 'THREE.WebGLState:', error );
  13753. }
  13754. }
  13755. function texImage2D() {
  13756. try {
  13757. gl.texImage2D.apply( gl, arguments );
  13758. } catch ( error ) {
  13759. console.error( 'THREE.WebGLState:', error );
  13760. }
  13761. }
  13762. function texImage3D() {
  13763. try {
  13764. gl.texImage3D.apply( gl, arguments );
  13765. } catch ( error ) {
  13766. console.error( 'THREE.WebGLState:', error );
  13767. }
  13768. }
  13769. //
  13770. function scissor( scissor ) {
  13771. if ( currentScissor.equals( scissor ) === false ) {
  13772. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13773. currentScissor.copy( scissor );
  13774. }
  13775. }
  13776. function viewport( viewport ) {
  13777. if ( currentViewport.equals( viewport ) === false ) {
  13778. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13779. currentViewport.copy( viewport );
  13780. }
  13781. }
  13782. function updateUBOMapping( uniformsGroup, program ) {
  13783. let mapping = uboProgramMap.get( program );
  13784. if ( mapping === undefined ) {
  13785. mapping = new WeakMap();
  13786. uboProgramMap.set( program, mapping );
  13787. }
  13788. let blockIndex = mapping.get( uniformsGroup );
  13789. if ( blockIndex === undefined ) {
  13790. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13791. mapping.set( uniformsGroup, blockIndex );
  13792. }
  13793. }
  13794. function uniformBlockBinding( uniformsGroup, program ) {
  13795. const mapping = uboProgramMap.get( program );
  13796. const blockIndex = mapping.get( uniformsGroup );
  13797. if ( uboBindings.get( program ) !== blockIndex ) {
  13798. // bind shader specific block index to global block point
  13799. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13800. uboBindings.set( program, blockIndex );
  13801. }
  13802. }
  13803. //
  13804. function reset() {
  13805. // reset state
  13806. gl.disable( 3042 );
  13807. gl.disable( 2884 );
  13808. gl.disable( 2929 );
  13809. gl.disable( 32823 );
  13810. gl.disable( 3089 );
  13811. gl.disable( 2960 );
  13812. gl.disable( 32926 );
  13813. gl.blendEquation( 32774 );
  13814. gl.blendFunc( 1, 0 );
  13815. gl.blendFuncSeparate( 1, 0, 1, 0 );
  13816. gl.colorMask( true, true, true, true );
  13817. gl.clearColor( 0, 0, 0, 0 );
  13818. gl.depthMask( true );
  13819. gl.depthFunc( 513 );
  13820. gl.clearDepth( 1 );
  13821. gl.stencilMask( 0xffffffff );
  13822. gl.stencilFunc( 519, 0, 0xffffffff );
  13823. gl.stencilOp( 7680, 7680, 7680 );
  13824. gl.clearStencil( 0 );
  13825. gl.cullFace( 1029 );
  13826. gl.frontFace( 2305 );
  13827. gl.polygonOffset( 0, 0 );
  13828. gl.activeTexture( 33984 );
  13829. gl.bindFramebuffer( 36160, null );
  13830. if ( isWebGL2 === true ) {
  13831. gl.bindFramebuffer( 36009, null );
  13832. gl.bindFramebuffer( 36008, null );
  13833. }
  13834. gl.useProgram( null );
  13835. gl.lineWidth( 1 );
  13836. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13837. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13838. // reset internals
  13839. enabledCapabilities = {};
  13840. currentTextureSlot = null;
  13841. currentBoundTextures = {};
  13842. currentBoundFramebuffers = {};
  13843. currentDrawbuffers = new WeakMap();
  13844. defaultDrawbuffers = [];
  13845. currentProgram = null;
  13846. currentBlendingEnabled = false;
  13847. currentBlending = null;
  13848. currentBlendEquation = null;
  13849. currentBlendSrc = null;
  13850. currentBlendDst = null;
  13851. currentBlendEquationAlpha = null;
  13852. currentBlendSrcAlpha = null;
  13853. currentBlendDstAlpha = null;
  13854. currentPremultipledAlpha = false;
  13855. currentFlipSided = null;
  13856. currentCullFace = null;
  13857. currentLineWidth = null;
  13858. currentPolygonOffsetFactor = null;
  13859. currentPolygonOffsetUnits = null;
  13860. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13861. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13862. colorBuffer.reset();
  13863. depthBuffer.reset();
  13864. stencilBuffer.reset();
  13865. }
  13866. return {
  13867. buffers: {
  13868. color: colorBuffer,
  13869. depth: depthBuffer,
  13870. stencil: stencilBuffer
  13871. },
  13872. enable: enable,
  13873. disable: disable,
  13874. bindFramebuffer: bindFramebuffer,
  13875. drawBuffers: drawBuffers,
  13876. useProgram: useProgram,
  13877. setBlending: setBlending,
  13878. setMaterial: setMaterial,
  13879. setFlipSided: setFlipSided,
  13880. setCullFace: setCullFace,
  13881. setLineWidth: setLineWidth,
  13882. setPolygonOffset: setPolygonOffset,
  13883. setScissorTest: setScissorTest,
  13884. activeTexture: activeTexture,
  13885. bindTexture: bindTexture,
  13886. unbindTexture: unbindTexture,
  13887. compressedTexImage2D: compressedTexImage2D,
  13888. compressedTexImage3D: compressedTexImage3D,
  13889. texImage2D: texImage2D,
  13890. texImage3D: texImage3D,
  13891. updateUBOMapping: updateUBOMapping,
  13892. uniformBlockBinding: uniformBlockBinding,
  13893. texStorage2D: texStorage2D,
  13894. texStorage3D: texStorage3D,
  13895. texSubImage2D: texSubImage2D,
  13896. texSubImage3D: texSubImage3D,
  13897. compressedTexSubImage2D: compressedTexSubImage2D,
  13898. compressedTexSubImage3D: compressedTexSubImage3D,
  13899. scissor: scissor,
  13900. viewport: viewport,
  13901. reset: reset
  13902. };
  13903. }
  13904. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13905. const isWebGL2 = capabilities.isWebGL2;
  13906. const maxTextures = capabilities.maxTextures;
  13907. const maxCubemapSize = capabilities.maxCubemapSize;
  13908. const maxTextureSize = capabilities.maxTextureSize;
  13909. const maxSamples = capabilities.maxSamples;
  13910. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13911. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  13912. const _videoTextures = new WeakMap();
  13913. let _canvas;
  13914. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13915. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13916. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13917. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13918. let useOffscreenCanvas = false;
  13919. try {
  13920. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13921. // eslint-disable-next-line compat/compat
  13922. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13923. } catch ( err ) {
  13924. // Ignore any errors
  13925. }
  13926. function createCanvas( width, height ) {
  13927. // Use OffscreenCanvas when available. Specially needed in web workers
  13928. return useOffscreenCanvas ?
  13929. // eslint-disable-next-line compat/compat
  13930. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13931. }
  13932. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13933. let scale = 1;
  13934. // handle case if texture exceeds max size
  13935. if ( image.width > maxSize || image.height > maxSize ) {
  13936. scale = maxSize / Math.max( image.width, image.height );
  13937. }
  13938. // only perform resize if necessary
  13939. if ( scale < 1 || needsPowerOfTwo === true ) {
  13940. // only perform resize for certain image types
  13941. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13942. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13943. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13944. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13945. const width = floor( scale * image.width );
  13946. const height = floor( scale * image.height );
  13947. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13948. // cube textures can't reuse the same canvas
  13949. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13950. canvas.width = width;
  13951. canvas.height = height;
  13952. const context = canvas.getContext( '2d' );
  13953. context.drawImage( image, 0, 0, width, height );
  13954. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13955. return canvas;
  13956. } else {
  13957. if ( 'data' in image ) {
  13958. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13959. }
  13960. return image;
  13961. }
  13962. }
  13963. return image;
  13964. }
  13965. function isPowerOfTwo$1( image ) {
  13966. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13967. }
  13968. function textureNeedsPowerOfTwo( texture ) {
  13969. if ( isWebGL2 ) return false;
  13970. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13971. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13972. }
  13973. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13974. return texture.generateMipmaps && supportsMips &&
  13975. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13976. }
  13977. function generateMipmap( target ) {
  13978. _gl.generateMipmap( target );
  13979. }
  13980. function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) {
  13981. if ( isWebGL2 === false ) return glFormat;
  13982. if ( internalFormatName !== null ) {
  13983. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13984. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13985. }
  13986. let internalFormat = glFormat;
  13987. if ( glFormat === 6403 ) {
  13988. if ( glType === 5126 ) internalFormat = 33326;
  13989. if ( glType === 5131 ) internalFormat = 33325;
  13990. if ( glType === 5121 ) internalFormat = 33321;
  13991. }
  13992. if ( glFormat === 33319 ) {
  13993. if ( glType === 5126 ) internalFormat = 33328;
  13994. if ( glType === 5131 ) internalFormat = 33327;
  13995. if ( glType === 5121 ) internalFormat = 33323;
  13996. }
  13997. if ( glFormat === 6408 ) {
  13998. if ( glType === 5126 ) internalFormat = 34836;
  13999. if ( glType === 5131 ) internalFormat = 34842;
  14000. if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? 35907 : 32856;
  14001. if ( glType === 32819 ) internalFormat = 32854;
  14002. if ( glType === 32820 ) internalFormat = 32855;
  14003. }
  14004. if ( internalFormat === 33325 || internalFormat === 33326 ||
  14005. internalFormat === 33327 || internalFormat === 33328 ||
  14006. internalFormat === 34842 || internalFormat === 34836 ) {
  14007. extensions.get( 'EXT_color_buffer_float' );
  14008. }
  14009. return internalFormat;
  14010. }
  14011. function getMipLevels( texture, image, supportsMips ) {
  14012. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14013. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14014. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14015. // user-defined mipmaps
  14016. return texture.mipmaps.length;
  14017. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14018. return image.mipmaps.length;
  14019. } else {
  14020. // texture without mipmaps (only base level)
  14021. return 1;
  14022. }
  14023. }
  14024. // Fallback filters for non-power-of-2 textures
  14025. function filterFallback( f ) {
  14026. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  14027. return 9728;
  14028. }
  14029. return 9729;
  14030. }
  14031. //
  14032. function onTextureDispose( event ) {
  14033. const texture = event.target;
  14034. texture.removeEventListener( 'dispose', onTextureDispose );
  14035. deallocateTexture( texture );
  14036. if ( texture.isVideoTexture ) {
  14037. _videoTextures.delete( texture );
  14038. }
  14039. }
  14040. function onRenderTargetDispose( event ) {
  14041. const renderTarget = event.target;
  14042. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14043. deallocateRenderTarget( renderTarget );
  14044. }
  14045. //
  14046. function deallocateTexture( texture ) {
  14047. const textureProperties = properties.get( texture );
  14048. if ( textureProperties.__webglInit === undefined ) return;
  14049. // check if it's necessary to remove the WebGLTexture object
  14050. const source = texture.source;
  14051. const webglTextures = _sources.get( source );
  14052. if ( webglTextures ) {
  14053. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14054. webglTexture.usedTimes --;
  14055. // the WebGLTexture object is not used anymore, remove it
  14056. if ( webglTexture.usedTimes === 0 ) {
  14057. deleteTexture( texture );
  14058. }
  14059. // remove the weak map entry if no WebGLTexture uses the source anymore
  14060. if ( Object.keys( webglTextures ).length === 0 ) {
  14061. _sources.delete( source );
  14062. }
  14063. }
  14064. properties.remove( texture );
  14065. }
  14066. function deleteTexture( texture ) {
  14067. const textureProperties = properties.get( texture );
  14068. _gl.deleteTexture( textureProperties.__webglTexture );
  14069. const source = texture.source;
  14070. const webglTextures = _sources.get( source );
  14071. delete webglTextures[ textureProperties.__cacheKey ];
  14072. info.memory.textures --;
  14073. }
  14074. function deallocateRenderTarget( renderTarget ) {
  14075. const texture = renderTarget.texture;
  14076. const renderTargetProperties = properties.get( renderTarget );
  14077. const textureProperties = properties.get( texture );
  14078. if ( textureProperties.__webglTexture !== undefined ) {
  14079. _gl.deleteTexture( textureProperties.__webglTexture );
  14080. info.memory.textures --;
  14081. }
  14082. if ( renderTarget.depthTexture ) {
  14083. renderTarget.depthTexture.dispose();
  14084. }
  14085. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14086. for ( let i = 0; i < 6; i ++ ) {
  14087. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14088. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14089. }
  14090. } else {
  14091. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14092. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14093. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14094. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14095. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14096. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14097. }
  14098. }
  14099. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14100. }
  14101. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  14102. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  14103. const attachmentProperties = properties.get( texture[ i ] );
  14104. if ( attachmentProperties.__webglTexture ) {
  14105. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14106. info.memory.textures --;
  14107. }
  14108. properties.remove( texture[ i ] );
  14109. }
  14110. }
  14111. properties.remove( texture );
  14112. properties.remove( renderTarget );
  14113. }
  14114. //
  14115. let textureUnits = 0;
  14116. function resetTextureUnits() {
  14117. textureUnits = 0;
  14118. }
  14119. function allocateTextureUnit() {
  14120. const textureUnit = textureUnits;
  14121. if ( textureUnit >= maxTextures ) {
  14122. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  14123. }
  14124. textureUnits += 1;
  14125. return textureUnit;
  14126. }
  14127. function getTextureCacheKey( texture ) {
  14128. const array = [];
  14129. array.push( texture.wrapS );
  14130. array.push( texture.wrapT );
  14131. array.push( texture.wrapR || 0 );
  14132. array.push( texture.magFilter );
  14133. array.push( texture.minFilter );
  14134. array.push( texture.anisotropy );
  14135. array.push( texture.internalFormat );
  14136. array.push( texture.format );
  14137. array.push( texture.type );
  14138. array.push( texture.generateMipmaps );
  14139. array.push( texture.premultiplyAlpha );
  14140. array.push( texture.flipY );
  14141. array.push( texture.unpackAlignment );
  14142. array.push( texture.encoding );
  14143. return array.join();
  14144. }
  14145. //
  14146. function setTexture2D( texture, slot ) {
  14147. const textureProperties = properties.get( texture );
  14148. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14149. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14150. const image = texture.image;
  14151. if ( image === null ) {
  14152. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14153. } else if ( image.complete === false ) {
  14154. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14155. } else {
  14156. uploadTexture( textureProperties, texture, slot );
  14157. return;
  14158. }
  14159. }
  14160. state.bindTexture( 3553, textureProperties.__webglTexture, 33984 + slot );
  14161. }
  14162. function setTexture2DArray( texture, slot ) {
  14163. const textureProperties = properties.get( texture );
  14164. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14165. uploadTexture( textureProperties, texture, slot );
  14166. return;
  14167. }
  14168. state.bindTexture( 35866, textureProperties.__webglTexture, 33984 + slot );
  14169. }
  14170. function setTexture3D( texture, slot ) {
  14171. const textureProperties = properties.get( texture );
  14172. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14173. uploadTexture( textureProperties, texture, slot );
  14174. return;
  14175. }
  14176. state.bindTexture( 32879, textureProperties.__webglTexture, 33984 + slot );
  14177. }
  14178. function setTextureCube( texture, slot ) {
  14179. const textureProperties = properties.get( texture );
  14180. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14181. uploadCubeTexture( textureProperties, texture, slot );
  14182. return;
  14183. }
  14184. state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot );
  14185. }
  14186. const wrappingToGL = {
  14187. [ RepeatWrapping ]: 10497,
  14188. [ ClampToEdgeWrapping ]: 33071,
  14189. [ MirroredRepeatWrapping ]: 33648
  14190. };
  14191. const filterToGL = {
  14192. [ NearestFilter ]: 9728,
  14193. [ NearestMipmapNearestFilter ]: 9984,
  14194. [ NearestMipmapLinearFilter ]: 9986,
  14195. [ LinearFilter ]: 9729,
  14196. [ LinearMipmapNearestFilter ]: 9985,
  14197. [ LinearMipmapLinearFilter ]: 9987
  14198. };
  14199. function setTextureParameters( textureType, texture, supportsMips ) {
  14200. if ( supportsMips ) {
  14201. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  14202. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  14203. if ( textureType === 32879 || textureType === 35866 ) {
  14204. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  14205. }
  14206. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  14207. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  14208. } else {
  14209. _gl.texParameteri( textureType, 10242, 33071 );
  14210. _gl.texParameteri( textureType, 10243, 33071 );
  14211. if ( textureType === 32879 || textureType === 35866 ) {
  14212. _gl.texParameteri( textureType, 32882, 33071 );
  14213. }
  14214. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14215. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14216. }
  14217. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  14218. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  14219. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14220. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14221. }
  14222. }
  14223. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14224. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14225. if ( texture.magFilter === NearestFilter ) return;
  14226. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14227. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14228. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14229. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14230. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14231. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14232. }
  14233. }
  14234. }
  14235. function initTexture( textureProperties, texture ) {
  14236. let forceUpload = false;
  14237. if ( textureProperties.__webglInit === undefined ) {
  14238. textureProperties.__webglInit = true;
  14239. texture.addEventListener( 'dispose', onTextureDispose );
  14240. }
  14241. // create Source <-> WebGLTextures mapping if necessary
  14242. const source = texture.source;
  14243. let webglTextures = _sources.get( source );
  14244. if ( webglTextures === undefined ) {
  14245. webglTextures = {};
  14246. _sources.set( source, webglTextures );
  14247. }
  14248. // check if there is already a WebGLTexture object for the given texture parameters
  14249. const textureCacheKey = getTextureCacheKey( texture );
  14250. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14251. // if not, create a new instance of WebGLTexture
  14252. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14253. // create new entry
  14254. webglTextures[ textureCacheKey ] = {
  14255. texture: _gl.createTexture(),
  14256. usedTimes: 0
  14257. };
  14258. info.memory.textures ++;
  14259. // when a new instance of WebGLTexture was created, a texture upload is required
  14260. // even if the image contents are identical
  14261. forceUpload = true;
  14262. }
  14263. webglTextures[ textureCacheKey ].usedTimes ++;
  14264. // every time the texture cache key changes, it's necessary to check if an instance of
  14265. // WebGLTexture can be deleted in order to avoid a memory leak.
  14266. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14267. if ( webglTexture !== undefined ) {
  14268. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14269. if ( webglTexture.usedTimes === 0 ) {
  14270. deleteTexture( texture );
  14271. }
  14272. }
  14273. // store references to cache key and WebGLTexture object
  14274. textureProperties.__cacheKey = textureCacheKey;
  14275. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14276. }
  14277. return forceUpload;
  14278. }
  14279. function uploadTexture( textureProperties, texture, slot ) {
  14280. let textureType = 3553;
  14281. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = 35866;
  14282. if ( texture.isData3DTexture ) textureType = 32879;
  14283. const forceUpload = initTexture( textureProperties, texture );
  14284. const source = texture.source;
  14285. state.bindTexture( textureType, textureProperties.__webglTexture, 33984 + slot );
  14286. const sourceProperties = properties.get( source );
  14287. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14288. state.activeTexture( 33984 + slot );
  14289. _gl.pixelStorei( 37440, texture.flipY );
  14290. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14291. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14292. _gl.pixelStorei( 37443, 0 );
  14293. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14294. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  14295. image = verifyColorSpace( texture, image );
  14296. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14297. glFormat = utils.convert( texture.format, texture.encoding );
  14298. let glType = utils.convert( texture.type ),
  14299. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  14300. setTextureParameters( textureType, texture, supportsMips );
  14301. let mipmap;
  14302. const mipmaps = texture.mipmaps;
  14303. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14304. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14305. const levels = getMipLevels( texture, image, supportsMips );
  14306. if ( texture.isDepthTexture ) {
  14307. // populate depth texture with dummy data
  14308. glInternalFormat = 6402;
  14309. if ( isWebGL2 ) {
  14310. if ( texture.type === FloatType ) {
  14311. glInternalFormat = 36012;
  14312. } else if ( texture.type === UnsignedIntType ) {
  14313. glInternalFormat = 33190;
  14314. } else if ( texture.type === UnsignedInt248Type ) {
  14315. glInternalFormat = 35056;
  14316. } else {
  14317. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  14318. }
  14319. } else {
  14320. if ( texture.type === FloatType ) {
  14321. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14322. }
  14323. }
  14324. // validation checks for WebGL 1
  14325. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  14326. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14327. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14328. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14329. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14330. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14331. texture.type = UnsignedIntType;
  14332. glType = utils.convert( texture.type );
  14333. }
  14334. }
  14335. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  14336. // Depth stencil textures need the DEPTH_STENCIL internal format
  14337. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14338. glInternalFormat = 34041;
  14339. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14340. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14341. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14342. if ( texture.type !== UnsignedInt248Type ) {
  14343. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14344. texture.type = UnsignedInt248Type;
  14345. glType = utils.convert( texture.type );
  14346. }
  14347. }
  14348. //
  14349. if ( allocateMemory ) {
  14350. if ( useTexStorage ) {
  14351. state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height );
  14352. } else {
  14353. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14354. }
  14355. }
  14356. } else if ( texture.isDataTexture ) {
  14357. // use manually created mipmaps if available
  14358. // if there are no manual mipmaps
  14359. // set 0 level mipmap and then use GL to generate other mipmap levels
  14360. if ( mipmaps.length > 0 && supportsMips ) {
  14361. if ( useTexStorage && allocateMemory ) {
  14362. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14363. }
  14364. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14365. mipmap = mipmaps[ i ];
  14366. if ( useTexStorage ) {
  14367. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14368. } else {
  14369. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14370. }
  14371. }
  14372. texture.generateMipmaps = false;
  14373. } else {
  14374. if ( useTexStorage ) {
  14375. if ( allocateMemory ) {
  14376. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14377. }
  14378. state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14379. } else {
  14380. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14381. }
  14382. }
  14383. } else if ( texture.isCompressedTexture ) {
  14384. if ( texture.isCompressedArrayTexture ) {
  14385. if ( useTexStorage && allocateMemory ) {
  14386. state.texStorage3D( 35866, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14387. }
  14388. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14389. mipmap = mipmaps[ i ];
  14390. if ( texture.format !== RGBAFormat ) {
  14391. if ( glFormat !== null ) {
  14392. if ( useTexStorage ) {
  14393. state.compressedTexSubImage3D( 35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14394. } else {
  14395. state.compressedTexImage3D( 35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14396. }
  14397. } else {
  14398. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14399. }
  14400. } else {
  14401. if ( useTexStorage ) {
  14402. state.texSubImage3D( 35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14403. } else {
  14404. state.texImage3D( 35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14405. }
  14406. }
  14407. }
  14408. } else {
  14409. if ( useTexStorage && allocateMemory ) {
  14410. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14411. }
  14412. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14413. mipmap = mipmaps[ i ];
  14414. if ( texture.format !== RGBAFormat ) {
  14415. if ( glFormat !== null ) {
  14416. if ( useTexStorage ) {
  14417. state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14418. } else {
  14419. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14420. }
  14421. } else {
  14422. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14423. }
  14424. } else {
  14425. if ( useTexStorage ) {
  14426. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14427. } else {
  14428. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14429. }
  14430. }
  14431. }
  14432. }
  14433. } else if ( texture.isDataArrayTexture ) {
  14434. if ( useTexStorage ) {
  14435. if ( allocateMemory ) {
  14436. state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth );
  14437. }
  14438. state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14439. } else {
  14440. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14441. }
  14442. } else if ( texture.isData3DTexture ) {
  14443. if ( useTexStorage ) {
  14444. if ( allocateMemory ) {
  14445. state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth );
  14446. }
  14447. state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14448. } else {
  14449. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14450. }
  14451. } else if ( texture.isFramebufferTexture ) {
  14452. if ( allocateMemory ) {
  14453. if ( useTexStorage ) {
  14454. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14455. } else {
  14456. let width = image.width, height = image.height;
  14457. for ( let i = 0; i < levels; i ++ ) {
  14458. state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14459. width >>= 1;
  14460. height >>= 1;
  14461. }
  14462. }
  14463. }
  14464. } else {
  14465. // regular Texture (image, video, canvas)
  14466. // use manually created mipmaps if available
  14467. // if there are no manual mipmaps
  14468. // set 0 level mipmap and then use GL to generate other mipmap levels
  14469. if ( mipmaps.length > 0 && supportsMips ) {
  14470. if ( useTexStorage && allocateMemory ) {
  14471. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14472. }
  14473. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14474. mipmap = mipmaps[ i ];
  14475. if ( useTexStorage ) {
  14476. state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap );
  14477. } else {
  14478. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  14479. }
  14480. }
  14481. texture.generateMipmaps = false;
  14482. } else {
  14483. if ( useTexStorage ) {
  14484. if ( allocateMemory ) {
  14485. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14486. }
  14487. state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image );
  14488. } else {
  14489. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  14490. }
  14491. }
  14492. }
  14493. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14494. generateMipmap( textureType );
  14495. }
  14496. sourceProperties.__version = source.version;
  14497. if ( texture.onUpdate ) texture.onUpdate( texture );
  14498. }
  14499. textureProperties.__version = texture.version;
  14500. }
  14501. function uploadCubeTexture( textureProperties, texture, slot ) {
  14502. if ( texture.image.length !== 6 ) return;
  14503. const forceUpload = initTexture( textureProperties, texture );
  14504. const source = texture.source;
  14505. state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot );
  14506. const sourceProperties = properties.get( source );
  14507. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14508. state.activeTexture( 33984 + slot );
  14509. _gl.pixelStorei( 37440, texture.flipY );
  14510. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14511. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14512. _gl.pixelStorei( 37443, 0 );
  14513. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14514. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14515. const cubeImage = [];
  14516. for ( let i = 0; i < 6; i ++ ) {
  14517. if ( ! isCompressed && ! isDataTexture ) {
  14518. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14519. } else {
  14520. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14521. }
  14522. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14523. }
  14524. const image = cubeImage[ 0 ],
  14525. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14526. glFormat = utils.convert( texture.format, texture.encoding ),
  14527. glType = utils.convert( texture.type ),
  14528. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14529. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14530. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14531. let levels = getMipLevels( texture, image, supportsMips );
  14532. setTextureParameters( 34067, texture, supportsMips );
  14533. let mipmaps;
  14534. if ( isCompressed ) {
  14535. if ( useTexStorage && allocateMemory ) {
  14536. state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height );
  14537. }
  14538. for ( let i = 0; i < 6; i ++ ) {
  14539. mipmaps = cubeImage[ i ].mipmaps;
  14540. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14541. const mipmap = mipmaps[ j ];
  14542. if ( texture.format !== RGBAFormat ) {
  14543. if ( glFormat !== null ) {
  14544. if ( useTexStorage ) {
  14545. state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14546. } else {
  14547. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14548. }
  14549. } else {
  14550. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14551. }
  14552. } else {
  14553. if ( useTexStorage ) {
  14554. state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14555. } else {
  14556. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14557. }
  14558. }
  14559. }
  14560. }
  14561. } else {
  14562. mipmaps = texture.mipmaps;
  14563. if ( useTexStorage && allocateMemory ) {
  14564. // TODO: Uniformly handle mipmap definitions
  14565. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14566. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14567. if ( mipmaps.length > 0 ) levels ++;
  14568. state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14569. }
  14570. for ( let i = 0; i < 6; i ++ ) {
  14571. if ( isDataTexture ) {
  14572. if ( useTexStorage ) {
  14573. state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14574. } else {
  14575. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14576. }
  14577. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14578. const mipmap = mipmaps[ j ];
  14579. const mipmapImage = mipmap.image[ i ].image;
  14580. if ( useTexStorage ) {
  14581. state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14582. } else {
  14583. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14584. }
  14585. }
  14586. } else {
  14587. if ( useTexStorage ) {
  14588. state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14589. } else {
  14590. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14591. }
  14592. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14593. const mipmap = mipmaps[ j ];
  14594. if ( useTexStorage ) {
  14595. state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14596. } else {
  14597. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14598. }
  14599. }
  14600. }
  14601. }
  14602. }
  14603. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14604. // We assume images for cube map have the same size.
  14605. generateMipmap( 34067 );
  14606. }
  14607. sourceProperties.__version = source.version;
  14608. if ( texture.onUpdate ) texture.onUpdate( texture );
  14609. }
  14610. textureProperties.__version = texture.version;
  14611. }
  14612. // Render targets
  14613. // Setup storage for target texture and bind it to correct framebuffer
  14614. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14615. const glFormat = utils.convert( texture.format, texture.encoding );
  14616. const glType = utils.convert( texture.type );
  14617. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14618. const renderTargetProperties = properties.get( renderTarget );
  14619. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14620. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  14621. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14622. } else {
  14623. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14624. }
  14625. }
  14626. state.bindFramebuffer( 36160, framebuffer );
  14627. if ( useMultisampledRTT( renderTarget ) ) {
  14628. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14629. } else if ( textureTarget === 3553 || ( textureTarget >= 34069 && textureTarget <= 34074 ) ) { // see #24753
  14630. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14631. }
  14632. state.bindFramebuffer( 36160, null );
  14633. }
  14634. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14635. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14636. _gl.bindRenderbuffer( 36161, renderbuffer );
  14637. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14638. let glInternalFormat = 33189;
  14639. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14640. const depthTexture = renderTarget.depthTexture;
  14641. if ( depthTexture && depthTexture.isDepthTexture ) {
  14642. if ( depthTexture.type === FloatType ) {
  14643. glInternalFormat = 36012;
  14644. } else if ( depthTexture.type === UnsignedIntType ) {
  14645. glInternalFormat = 33190;
  14646. }
  14647. }
  14648. const samples = getRenderTargetSamples( renderTarget );
  14649. if ( useMultisampledRTT( renderTarget ) ) {
  14650. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14651. } else {
  14652. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14653. }
  14654. } else {
  14655. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14656. }
  14657. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  14658. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14659. const samples = getRenderTargetSamples( renderTarget );
  14660. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14661. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14662. } else if ( useMultisampledRTT( renderTarget ) ) {
  14663. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14664. } else {
  14665. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  14666. }
  14667. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  14668. } else {
  14669. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14670. for ( let i = 0; i < textures.length; i ++ ) {
  14671. const texture = textures[ i ];
  14672. const glFormat = utils.convert( texture.format, texture.encoding );
  14673. const glType = utils.convert( texture.type );
  14674. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14675. const samples = getRenderTargetSamples( renderTarget );
  14676. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14677. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14678. } else if ( useMultisampledRTT( renderTarget ) ) {
  14679. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14680. } else {
  14681. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14682. }
  14683. }
  14684. }
  14685. _gl.bindRenderbuffer( 36161, null );
  14686. }
  14687. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14688. function setupDepthTexture( framebuffer, renderTarget ) {
  14689. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14690. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14691. state.bindFramebuffer( 36160, framebuffer );
  14692. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14693. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14694. }
  14695. // upload an empty depth texture with framebuffer size
  14696. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14697. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14698. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14699. renderTarget.depthTexture.image.width = renderTarget.width;
  14700. renderTarget.depthTexture.image.height = renderTarget.height;
  14701. renderTarget.depthTexture.needsUpdate = true;
  14702. }
  14703. setTexture2D( renderTarget.depthTexture, 0 );
  14704. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14705. const samples = getRenderTargetSamples( renderTarget );
  14706. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14707. if ( useMultisampledRTT( renderTarget ) ) {
  14708. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples );
  14709. } else {
  14710. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  14711. }
  14712. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14713. if ( useMultisampledRTT( renderTarget ) ) {
  14714. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples );
  14715. } else {
  14716. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  14717. }
  14718. } else {
  14719. throw new Error( 'Unknown depthTexture format' );
  14720. }
  14721. }
  14722. // Setup GL resources for a non-texture depth buffer
  14723. function setupDepthRenderbuffer( renderTarget ) {
  14724. const renderTargetProperties = properties.get( renderTarget );
  14725. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14726. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14727. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14728. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14729. } else {
  14730. if ( isCube ) {
  14731. renderTargetProperties.__webglDepthbuffer = [];
  14732. for ( let i = 0; i < 6; i ++ ) {
  14733. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  14734. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14735. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14736. }
  14737. } else {
  14738. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14739. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14740. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14741. }
  14742. }
  14743. state.bindFramebuffer( 36160, null );
  14744. }
  14745. // rebind framebuffer with external textures
  14746. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14747. const renderTargetProperties = properties.get( renderTarget );
  14748. if ( colorTexture !== undefined ) {
  14749. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 );
  14750. }
  14751. if ( depthTexture !== undefined ) {
  14752. setupDepthRenderbuffer( renderTarget );
  14753. }
  14754. }
  14755. // Set up GL resources for the render target
  14756. function setupRenderTarget( renderTarget ) {
  14757. const texture = renderTarget.texture;
  14758. const renderTargetProperties = properties.get( renderTarget );
  14759. const textureProperties = properties.get( texture );
  14760. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14761. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14762. if ( textureProperties.__webglTexture === undefined ) {
  14763. textureProperties.__webglTexture = _gl.createTexture();
  14764. }
  14765. textureProperties.__version = texture.version;
  14766. info.memory.textures ++;
  14767. }
  14768. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14769. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14770. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14771. // Setup framebuffer
  14772. if ( isCube ) {
  14773. renderTargetProperties.__webglFramebuffer = [];
  14774. for ( let i = 0; i < 6; i ++ ) {
  14775. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14776. }
  14777. } else {
  14778. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14779. if ( isMultipleRenderTargets ) {
  14780. if ( capabilities.drawBuffers ) {
  14781. const textures = renderTarget.texture;
  14782. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14783. const attachmentProperties = properties.get( textures[ i ] );
  14784. if ( attachmentProperties.__webglTexture === undefined ) {
  14785. attachmentProperties.__webglTexture = _gl.createTexture();
  14786. info.memory.textures ++;
  14787. }
  14788. }
  14789. } else {
  14790. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14791. }
  14792. }
  14793. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14794. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14795. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14796. renderTargetProperties.__webglColorRenderbuffer = [];
  14797. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14798. for ( let i = 0; i < textures.length; i ++ ) {
  14799. const texture = textures[ i ];
  14800. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14801. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14802. const glFormat = utils.convert( texture.format, texture.encoding );
  14803. const glType = utils.convert( texture.type );
  14804. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true );
  14805. const samples = getRenderTargetSamples( renderTarget );
  14806. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14807. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14808. }
  14809. _gl.bindRenderbuffer( 36161, null );
  14810. if ( renderTarget.depthBuffer ) {
  14811. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14812. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14813. }
  14814. state.bindFramebuffer( 36160, null );
  14815. }
  14816. }
  14817. // Setup color buffer
  14818. if ( isCube ) {
  14819. state.bindTexture( 34067, textureProperties.__webglTexture );
  14820. setTextureParameters( 34067, texture, supportsMips );
  14821. for ( let i = 0; i < 6; i ++ ) {
  14822. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  14823. }
  14824. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14825. generateMipmap( 34067 );
  14826. }
  14827. state.unbindTexture();
  14828. } else if ( isMultipleRenderTargets ) {
  14829. const textures = renderTarget.texture;
  14830. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14831. const attachment = textures[ i ];
  14832. const attachmentProperties = properties.get( attachment );
  14833. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  14834. setTextureParameters( 3553, attachment, supportsMips );
  14835. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  14836. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14837. generateMipmap( 3553 );
  14838. }
  14839. }
  14840. state.unbindTexture();
  14841. } else {
  14842. let glTextureType = 3553;
  14843. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14844. if ( isWebGL2 ) {
  14845. glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866;
  14846. } else {
  14847. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14848. }
  14849. }
  14850. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14851. setTextureParameters( glTextureType, texture, supportsMips );
  14852. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  14853. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14854. generateMipmap( glTextureType );
  14855. }
  14856. state.unbindTexture();
  14857. }
  14858. // Setup depth and stencil buffers
  14859. if ( renderTarget.depthBuffer ) {
  14860. setupDepthRenderbuffer( renderTarget );
  14861. }
  14862. }
  14863. function updateRenderTargetMipmap( renderTarget ) {
  14864. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14865. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14866. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14867. const texture = textures[ i ];
  14868. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14869. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14870. const webglTexture = properties.get( texture ).__webglTexture;
  14871. state.bindTexture( target, webglTexture );
  14872. generateMipmap( target );
  14873. state.unbindTexture();
  14874. }
  14875. }
  14876. }
  14877. function updateMultisampleRenderTarget( renderTarget ) {
  14878. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14879. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14880. const width = renderTarget.width;
  14881. const height = renderTarget.height;
  14882. let mask = 16384;
  14883. const invalidationArray = [];
  14884. const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096;
  14885. const renderTargetProperties = properties.get( renderTarget );
  14886. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14887. // If MRT we need to remove FBO attachments
  14888. if ( isMultipleRenderTargets ) {
  14889. for ( let i = 0; i < textures.length; i ++ ) {
  14890. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14891. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null );
  14892. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14893. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 );
  14894. }
  14895. }
  14896. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  14897. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  14898. for ( let i = 0; i < textures.length; i ++ ) {
  14899. invalidationArray.push( 36064 + i );
  14900. if ( renderTarget.depthBuffer ) {
  14901. invalidationArray.push( depthStyle );
  14902. }
  14903. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14904. if ( ignoreDepthValues === false ) {
  14905. if ( renderTarget.depthBuffer ) mask |= 256;
  14906. if ( renderTarget.stencilBuffer ) mask |= 1024;
  14907. }
  14908. if ( isMultipleRenderTargets ) {
  14909. _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14910. }
  14911. if ( ignoreDepthValues === true ) {
  14912. _gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14913. _gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14914. }
  14915. if ( isMultipleRenderTargets ) {
  14916. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14917. _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 );
  14918. }
  14919. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  14920. if ( supportsInvalidateFramebuffer ) {
  14921. _gl.invalidateFramebuffer( 36008, invalidationArray );
  14922. }
  14923. }
  14924. state.bindFramebuffer( 36008, null );
  14925. state.bindFramebuffer( 36009, null );
  14926. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14927. if ( isMultipleRenderTargets ) {
  14928. for ( let i = 0; i < textures.length; i ++ ) {
  14929. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14930. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14931. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14932. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14933. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 );
  14934. }
  14935. }
  14936. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  14937. }
  14938. }
  14939. function getRenderTargetSamples( renderTarget ) {
  14940. return Math.min( maxSamples, renderTarget.samples );
  14941. }
  14942. function useMultisampledRTT( renderTarget ) {
  14943. const renderTargetProperties = properties.get( renderTarget );
  14944. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14945. }
  14946. function updateVideoTexture( texture ) {
  14947. const frame = info.render.frame;
  14948. // Check the last frame we updated the VideoTexture
  14949. if ( _videoTextures.get( texture ) !== frame ) {
  14950. _videoTextures.set( texture, frame );
  14951. texture.update();
  14952. }
  14953. }
  14954. function verifyColorSpace( texture, image ) {
  14955. const encoding = texture.encoding;
  14956. const format = texture.format;
  14957. const type = texture.type;
  14958. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14959. if ( encoding !== LinearEncoding ) {
  14960. // sRGB
  14961. if ( encoding === sRGBEncoding ) {
  14962. if ( isWebGL2 === false ) {
  14963. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14964. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14965. texture.format = _SRGBAFormat;
  14966. // it's not possible to generate mips in WebGL 1 with this extension
  14967. texture.minFilter = LinearFilter;
  14968. texture.generateMipmaps = false;
  14969. } else {
  14970. // slow fallback (CPU decode)
  14971. image = ImageUtils.sRGBToLinear( image );
  14972. }
  14973. } else {
  14974. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14975. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14976. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14977. }
  14978. }
  14979. } else {
  14980. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14981. }
  14982. }
  14983. return image;
  14984. }
  14985. //
  14986. this.allocateTextureUnit = allocateTextureUnit;
  14987. this.resetTextureUnits = resetTextureUnits;
  14988. this.setTexture2D = setTexture2D;
  14989. this.setTexture2DArray = setTexture2DArray;
  14990. this.setTexture3D = setTexture3D;
  14991. this.setTextureCube = setTextureCube;
  14992. this.rebindTextures = rebindTextures;
  14993. this.setupRenderTarget = setupRenderTarget;
  14994. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14995. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14996. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14997. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14998. this.useMultisampledRTT = useMultisampledRTT;
  14999. }
  15000. function WebGLUtils( gl, extensions, capabilities ) {
  15001. const isWebGL2 = capabilities.isWebGL2;
  15002. function convert( p, encoding = null ) {
  15003. let extension;
  15004. if ( p === UnsignedByteType ) return 5121;
  15005. if ( p === UnsignedShort4444Type ) return 32819;
  15006. if ( p === UnsignedShort5551Type ) return 32820;
  15007. if ( p === ByteType ) return 5120;
  15008. if ( p === ShortType ) return 5122;
  15009. if ( p === UnsignedShortType ) return 5123;
  15010. if ( p === IntType ) return 5124;
  15011. if ( p === UnsignedIntType ) return 5125;
  15012. if ( p === FloatType ) return 5126;
  15013. if ( p === HalfFloatType ) {
  15014. if ( isWebGL2 ) return 5131;
  15015. extension = extensions.get( 'OES_texture_half_float' );
  15016. if ( extension !== null ) {
  15017. return extension.HALF_FLOAT_OES;
  15018. } else {
  15019. return null;
  15020. }
  15021. }
  15022. if ( p === AlphaFormat ) return 6406;
  15023. if ( p === RGBAFormat ) return 6408;
  15024. if ( p === LuminanceFormat ) return 6409;
  15025. if ( p === LuminanceAlphaFormat ) return 6410;
  15026. if ( p === DepthFormat ) return 6402;
  15027. if ( p === DepthStencilFormat ) return 34041;
  15028. // WebGL 1 sRGB fallback
  15029. if ( p === _SRGBAFormat ) {
  15030. extension = extensions.get( 'EXT_sRGB' );
  15031. if ( extension !== null ) {
  15032. return extension.SRGB_ALPHA_EXT;
  15033. } else {
  15034. return null;
  15035. }
  15036. }
  15037. // WebGL2 formats.
  15038. if ( p === RedFormat ) return 6403;
  15039. if ( p === RedIntegerFormat ) return 36244;
  15040. if ( p === RGFormat ) return 33319;
  15041. if ( p === RGIntegerFormat ) return 33320;
  15042. if ( p === RGBAIntegerFormat ) return 36249;
  15043. // S3TC
  15044. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15045. if ( encoding === sRGBEncoding ) {
  15046. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15047. if ( extension !== null ) {
  15048. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15049. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15050. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15051. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15052. } else {
  15053. return null;
  15054. }
  15055. } else {
  15056. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15057. if ( extension !== null ) {
  15058. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15059. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15060. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15061. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15062. } else {
  15063. return null;
  15064. }
  15065. }
  15066. }
  15067. // PVRTC
  15068. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15069. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15070. if ( extension !== null ) {
  15071. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15072. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15073. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15074. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15075. } else {
  15076. return null;
  15077. }
  15078. }
  15079. // ETC1
  15080. if ( p === RGB_ETC1_Format ) {
  15081. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  15082. if ( extension !== null ) {
  15083. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15084. } else {
  15085. return null;
  15086. }
  15087. }
  15088. // ETC2
  15089. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15090. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15091. if ( extension !== null ) {
  15092. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15093. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15094. } else {
  15095. return null;
  15096. }
  15097. }
  15098. // ASTC
  15099. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15100. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15101. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15102. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15103. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15104. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15105. if ( extension !== null ) {
  15106. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15107. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15108. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15109. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15110. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15111. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15112. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15113. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15114. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15115. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15116. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15117. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15118. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15119. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15120. } else {
  15121. return null;
  15122. }
  15123. }
  15124. // BPTC
  15125. if ( p === RGBA_BPTC_Format ) {
  15126. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15127. if ( extension !== null ) {
  15128. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15129. } else {
  15130. return null;
  15131. }
  15132. }
  15133. // RGTC
  15134. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15135. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15136. if ( extension !== null ) {
  15137. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15138. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15139. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15140. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15141. } else {
  15142. return null;
  15143. }
  15144. }
  15145. //
  15146. if ( p === UnsignedInt248Type ) {
  15147. if ( isWebGL2 ) return 34042;
  15148. extension = extensions.get( 'WEBGL_depth_texture' );
  15149. if ( extension !== null ) {
  15150. return extension.UNSIGNED_INT_24_8_WEBGL;
  15151. } else {
  15152. return null;
  15153. }
  15154. }
  15155. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15156. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15157. }
  15158. return { convert: convert };
  15159. }
  15160. class ArrayCamera extends PerspectiveCamera {
  15161. constructor( array = [] ) {
  15162. super();
  15163. this.isArrayCamera = true;
  15164. this.cameras = array;
  15165. }
  15166. }
  15167. class Group extends Object3D {
  15168. constructor() {
  15169. super();
  15170. this.isGroup = true;
  15171. this.type = 'Group';
  15172. }
  15173. }
  15174. const _moveEvent = { type: 'move' };
  15175. class WebXRController {
  15176. constructor() {
  15177. this._targetRay = null;
  15178. this._grip = null;
  15179. this._hand = null;
  15180. }
  15181. getHandSpace() {
  15182. if ( this._hand === null ) {
  15183. this._hand = new Group();
  15184. this._hand.matrixAutoUpdate = false;
  15185. this._hand.visible = false;
  15186. this._hand.joints = {};
  15187. this._hand.inputState = { pinching: false };
  15188. }
  15189. return this._hand;
  15190. }
  15191. getTargetRaySpace() {
  15192. if ( this._targetRay === null ) {
  15193. this._targetRay = new Group();
  15194. this._targetRay.matrixAutoUpdate = false;
  15195. this._targetRay.visible = false;
  15196. this._targetRay.hasLinearVelocity = false;
  15197. this._targetRay.linearVelocity = new Vector3();
  15198. this._targetRay.hasAngularVelocity = false;
  15199. this._targetRay.angularVelocity = new Vector3();
  15200. }
  15201. return this._targetRay;
  15202. }
  15203. getGripSpace() {
  15204. if ( this._grip === null ) {
  15205. this._grip = new Group();
  15206. this._grip.matrixAutoUpdate = false;
  15207. this._grip.visible = false;
  15208. this._grip.hasLinearVelocity = false;
  15209. this._grip.linearVelocity = new Vector3();
  15210. this._grip.hasAngularVelocity = false;
  15211. this._grip.angularVelocity = new Vector3();
  15212. }
  15213. return this._grip;
  15214. }
  15215. dispatchEvent( event ) {
  15216. if ( this._targetRay !== null ) {
  15217. this._targetRay.dispatchEvent( event );
  15218. }
  15219. if ( this._grip !== null ) {
  15220. this._grip.dispatchEvent( event );
  15221. }
  15222. if ( this._hand !== null ) {
  15223. this._hand.dispatchEvent( event );
  15224. }
  15225. return this;
  15226. }
  15227. connect( inputSource ) {
  15228. if ( inputSource && inputSource.hand ) {
  15229. const hand = this._hand;
  15230. if ( hand ) {
  15231. for ( const inputjoint of inputSource.hand.values() ) {
  15232. // Initialize hand with joints when connected
  15233. this._getHandJoint( hand, inputjoint );
  15234. }
  15235. }
  15236. }
  15237. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15238. return this;
  15239. }
  15240. disconnect( inputSource ) {
  15241. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15242. if ( this._targetRay !== null ) {
  15243. this._targetRay.visible = false;
  15244. }
  15245. if ( this._grip !== null ) {
  15246. this._grip.visible = false;
  15247. }
  15248. if ( this._hand !== null ) {
  15249. this._hand.visible = false;
  15250. }
  15251. return this;
  15252. }
  15253. update( inputSource, frame, referenceSpace ) {
  15254. let inputPose = null;
  15255. let gripPose = null;
  15256. let handPose = null;
  15257. const targetRay = this._targetRay;
  15258. const grip = this._grip;
  15259. const hand = this._hand;
  15260. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15261. if ( hand && inputSource.hand ) {
  15262. handPose = true;
  15263. for ( const inputjoint of inputSource.hand.values() ) {
  15264. // Update the joints groups with the XRJoint poses
  15265. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15266. // The transform of this joint will be updated with the joint pose on each frame
  15267. const joint = this._getHandJoint( hand, inputjoint );
  15268. if ( jointPose !== null ) {
  15269. joint.matrix.fromArray( jointPose.transform.matrix );
  15270. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15271. joint.jointRadius = jointPose.radius;
  15272. }
  15273. joint.visible = jointPose !== null;
  15274. }
  15275. // Custom events
  15276. // Check pinchz
  15277. const indexTip = hand.joints[ 'index-finger-tip' ];
  15278. const thumbTip = hand.joints[ 'thumb-tip' ];
  15279. const distance = indexTip.position.distanceTo( thumbTip.position );
  15280. const distanceToPinch = 0.02;
  15281. const threshold = 0.005;
  15282. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15283. hand.inputState.pinching = false;
  15284. this.dispatchEvent( {
  15285. type: 'pinchend',
  15286. handedness: inputSource.handedness,
  15287. target: this
  15288. } );
  15289. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15290. hand.inputState.pinching = true;
  15291. this.dispatchEvent( {
  15292. type: 'pinchstart',
  15293. handedness: inputSource.handedness,
  15294. target: this
  15295. } );
  15296. }
  15297. } else {
  15298. if ( grip !== null && inputSource.gripSpace ) {
  15299. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15300. if ( gripPose !== null ) {
  15301. grip.matrix.fromArray( gripPose.transform.matrix );
  15302. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15303. if ( gripPose.linearVelocity ) {
  15304. grip.hasLinearVelocity = true;
  15305. grip.linearVelocity.copy( gripPose.linearVelocity );
  15306. } else {
  15307. grip.hasLinearVelocity = false;
  15308. }
  15309. if ( gripPose.angularVelocity ) {
  15310. grip.hasAngularVelocity = true;
  15311. grip.angularVelocity.copy( gripPose.angularVelocity );
  15312. } else {
  15313. grip.hasAngularVelocity = false;
  15314. }
  15315. }
  15316. }
  15317. }
  15318. if ( targetRay !== null ) {
  15319. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15320. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15321. if ( inputPose === null && gripPose !== null ) {
  15322. inputPose = gripPose;
  15323. }
  15324. if ( inputPose !== null ) {
  15325. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15326. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15327. if ( inputPose.linearVelocity ) {
  15328. targetRay.hasLinearVelocity = true;
  15329. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15330. } else {
  15331. targetRay.hasLinearVelocity = false;
  15332. }
  15333. if ( inputPose.angularVelocity ) {
  15334. targetRay.hasAngularVelocity = true;
  15335. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15336. } else {
  15337. targetRay.hasAngularVelocity = false;
  15338. }
  15339. this.dispatchEvent( _moveEvent );
  15340. }
  15341. }
  15342. }
  15343. if ( targetRay !== null ) {
  15344. targetRay.visible = ( inputPose !== null );
  15345. }
  15346. if ( grip !== null ) {
  15347. grip.visible = ( gripPose !== null );
  15348. }
  15349. if ( hand !== null ) {
  15350. hand.visible = ( handPose !== null );
  15351. }
  15352. return this;
  15353. }
  15354. // private method
  15355. _getHandJoint( hand, inputjoint ) {
  15356. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15357. const joint = new Group();
  15358. joint.matrixAutoUpdate = false;
  15359. joint.visible = false;
  15360. hand.joints[ inputjoint.jointName ] = joint;
  15361. hand.add( joint );
  15362. }
  15363. return hand.joints[ inputjoint.jointName ];
  15364. }
  15365. }
  15366. class DepthTexture extends Texture {
  15367. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15368. format = format !== undefined ? format : DepthFormat;
  15369. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15370. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15371. }
  15372. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15373. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15374. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15375. this.isDepthTexture = true;
  15376. this.image = { width: width, height: height };
  15377. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15378. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15379. this.flipY = false;
  15380. this.generateMipmaps = false;
  15381. }
  15382. }
  15383. class WebXRManager extends EventDispatcher {
  15384. constructor( renderer, gl ) {
  15385. super();
  15386. const scope = this;
  15387. let session = null;
  15388. let framebufferScaleFactor = 1.0;
  15389. let referenceSpace = null;
  15390. let referenceSpaceType = 'local-floor';
  15391. // Set default foveation to maximum.
  15392. let foveation = 1.0;
  15393. let customReferenceSpace = null;
  15394. let pose = null;
  15395. let glBinding = null;
  15396. let glProjLayer = null;
  15397. let glBaseLayer = null;
  15398. let xrFrame = null;
  15399. const attributes = gl.getContextAttributes();
  15400. let initialRenderTarget = null;
  15401. let newRenderTarget = null;
  15402. const controllers = [];
  15403. const controllerInputSources = [];
  15404. const planes = new Set();
  15405. const planesLastChangedTimes = new Map();
  15406. //
  15407. const cameraL = new PerspectiveCamera();
  15408. cameraL.layers.enable( 1 );
  15409. cameraL.viewport = new Vector4();
  15410. const cameraR = new PerspectiveCamera();
  15411. cameraR.layers.enable( 2 );
  15412. cameraR.viewport = new Vector4();
  15413. const cameras = [ cameraL, cameraR ];
  15414. const cameraVR = new ArrayCamera();
  15415. cameraVR.layers.enable( 1 );
  15416. cameraVR.layers.enable( 2 );
  15417. let _currentDepthNear = null;
  15418. let _currentDepthFar = null;
  15419. //
  15420. this.cameraAutoUpdate = true;
  15421. this.enabled = false;
  15422. this.isPresenting = false;
  15423. this.getController = function ( index ) {
  15424. let controller = controllers[ index ];
  15425. if ( controller === undefined ) {
  15426. controller = new WebXRController();
  15427. controllers[ index ] = controller;
  15428. }
  15429. return controller.getTargetRaySpace();
  15430. };
  15431. this.getControllerGrip = function ( index ) {
  15432. let controller = controllers[ index ];
  15433. if ( controller === undefined ) {
  15434. controller = new WebXRController();
  15435. controllers[ index ] = controller;
  15436. }
  15437. return controller.getGripSpace();
  15438. };
  15439. this.getHand = function ( index ) {
  15440. let controller = controllers[ index ];
  15441. if ( controller === undefined ) {
  15442. controller = new WebXRController();
  15443. controllers[ index ] = controller;
  15444. }
  15445. return controller.getHandSpace();
  15446. };
  15447. //
  15448. function onSessionEvent( event ) {
  15449. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15450. if ( controllerIndex === - 1 ) {
  15451. return;
  15452. }
  15453. const controller = controllers[ controllerIndex ];
  15454. if ( controller !== undefined ) {
  15455. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15456. }
  15457. }
  15458. function onSessionEnd() {
  15459. session.removeEventListener( 'select', onSessionEvent );
  15460. session.removeEventListener( 'selectstart', onSessionEvent );
  15461. session.removeEventListener( 'selectend', onSessionEvent );
  15462. session.removeEventListener( 'squeeze', onSessionEvent );
  15463. session.removeEventListener( 'squeezestart', onSessionEvent );
  15464. session.removeEventListener( 'squeezeend', onSessionEvent );
  15465. session.removeEventListener( 'end', onSessionEnd );
  15466. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15467. for ( let i = 0; i < controllers.length; i ++ ) {
  15468. const inputSource = controllerInputSources[ i ];
  15469. if ( inputSource === null ) continue;
  15470. controllerInputSources[ i ] = null;
  15471. controllers[ i ].disconnect( inputSource );
  15472. }
  15473. _currentDepthNear = null;
  15474. _currentDepthFar = null;
  15475. // restore framebuffer/rendering state
  15476. renderer.setRenderTarget( initialRenderTarget );
  15477. glBaseLayer = null;
  15478. glProjLayer = null;
  15479. glBinding = null;
  15480. session = null;
  15481. newRenderTarget = null;
  15482. //
  15483. animation.stop();
  15484. scope.isPresenting = false;
  15485. scope.dispatchEvent( { type: 'sessionend' } );
  15486. }
  15487. this.setFramebufferScaleFactor = function ( value ) {
  15488. framebufferScaleFactor = value;
  15489. if ( scope.isPresenting === true ) {
  15490. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15491. }
  15492. };
  15493. this.setReferenceSpaceType = function ( value ) {
  15494. referenceSpaceType = value;
  15495. if ( scope.isPresenting === true ) {
  15496. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15497. }
  15498. };
  15499. this.getReferenceSpace = function () {
  15500. return customReferenceSpace || referenceSpace;
  15501. };
  15502. this.setReferenceSpace = function ( space ) {
  15503. customReferenceSpace = space;
  15504. };
  15505. this.getBaseLayer = function () {
  15506. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15507. };
  15508. this.getBinding = function () {
  15509. return glBinding;
  15510. };
  15511. this.getFrame = function () {
  15512. return xrFrame;
  15513. };
  15514. this.getSession = function () {
  15515. return session;
  15516. };
  15517. this.setSession = async function ( value ) {
  15518. session = value;
  15519. if ( session !== null ) {
  15520. initialRenderTarget = renderer.getRenderTarget();
  15521. session.addEventListener( 'select', onSessionEvent );
  15522. session.addEventListener( 'selectstart', onSessionEvent );
  15523. session.addEventListener( 'selectend', onSessionEvent );
  15524. session.addEventListener( 'squeeze', onSessionEvent );
  15525. session.addEventListener( 'squeezestart', onSessionEvent );
  15526. session.addEventListener( 'squeezeend', onSessionEvent );
  15527. session.addEventListener( 'end', onSessionEnd );
  15528. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15529. if ( attributes.xrCompatible !== true ) {
  15530. await gl.makeXRCompatible();
  15531. }
  15532. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15533. const layerInit = {
  15534. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15535. alpha: attributes.alpha,
  15536. depth: attributes.depth,
  15537. stencil: attributes.stencil,
  15538. framebufferScaleFactor: framebufferScaleFactor
  15539. };
  15540. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15541. session.updateRenderState( { baseLayer: glBaseLayer } );
  15542. newRenderTarget = new WebGLRenderTarget(
  15543. glBaseLayer.framebufferWidth,
  15544. glBaseLayer.framebufferHeight,
  15545. {
  15546. format: RGBAFormat,
  15547. type: UnsignedByteType,
  15548. encoding: renderer.outputEncoding,
  15549. stencilBuffer: attributes.stencil
  15550. }
  15551. );
  15552. } else {
  15553. let depthFormat = null;
  15554. let depthType = null;
  15555. let glDepthFormat = null;
  15556. if ( attributes.depth ) {
  15557. glDepthFormat = attributes.stencil ? 35056 : 33190;
  15558. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15559. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15560. }
  15561. const projectionlayerInit = {
  15562. colorFormat: 32856,
  15563. depthFormat: glDepthFormat,
  15564. scaleFactor: framebufferScaleFactor
  15565. };
  15566. glBinding = new XRWebGLBinding( session, gl );
  15567. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15568. session.updateRenderState( { layers: [ glProjLayer ] } );
  15569. newRenderTarget = new WebGLRenderTarget(
  15570. glProjLayer.textureWidth,
  15571. glProjLayer.textureHeight,
  15572. {
  15573. format: RGBAFormat,
  15574. type: UnsignedByteType,
  15575. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15576. stencilBuffer: attributes.stencil,
  15577. encoding: renderer.outputEncoding,
  15578. samples: attributes.antialias ? 4 : 0
  15579. } );
  15580. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15581. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15582. }
  15583. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15584. this.setFoveation( foveation );
  15585. customReferenceSpace = null;
  15586. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15587. animation.setContext( session );
  15588. animation.start();
  15589. scope.isPresenting = true;
  15590. scope.dispatchEvent( { type: 'sessionstart' } );
  15591. }
  15592. };
  15593. function onInputSourcesChange( event ) {
  15594. // Notify disconnected
  15595. for ( let i = 0; i < event.removed.length; i ++ ) {
  15596. const inputSource = event.removed[ i ];
  15597. const index = controllerInputSources.indexOf( inputSource );
  15598. if ( index >= 0 ) {
  15599. controllerInputSources[ index ] = null;
  15600. controllers[ index ].disconnect( inputSource );
  15601. }
  15602. }
  15603. // Notify connected
  15604. for ( let i = 0; i < event.added.length; i ++ ) {
  15605. const inputSource = event.added[ i ];
  15606. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15607. if ( controllerIndex === - 1 ) {
  15608. // Assign input source a controller that currently has no input source
  15609. for ( let i = 0; i < controllers.length; i ++ ) {
  15610. if ( i >= controllerInputSources.length ) {
  15611. controllerInputSources.push( inputSource );
  15612. controllerIndex = i;
  15613. break;
  15614. } else if ( controllerInputSources[ i ] === null ) {
  15615. controllerInputSources[ i ] = inputSource;
  15616. controllerIndex = i;
  15617. break;
  15618. }
  15619. }
  15620. // If all controllers do currently receive input we ignore new ones
  15621. if ( controllerIndex === - 1 ) break;
  15622. }
  15623. const controller = controllers[ controllerIndex ];
  15624. if ( controller ) {
  15625. controller.connect( inputSource );
  15626. }
  15627. }
  15628. }
  15629. //
  15630. const cameraLPos = new Vector3();
  15631. const cameraRPos = new Vector3();
  15632. /**
  15633. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15634. * the cameras' projection and world matrices have already been set.
  15635. * And that near and far planes are identical for both cameras.
  15636. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15637. */
  15638. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15639. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15640. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15641. const ipd = cameraLPos.distanceTo( cameraRPos );
  15642. const projL = cameraL.projectionMatrix.elements;
  15643. const projR = cameraR.projectionMatrix.elements;
  15644. // VR systems will have identical far and near planes, and
  15645. // most likely identical top and bottom frustum extents.
  15646. // Use the left camera for these values.
  15647. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15648. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15649. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15650. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15651. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15652. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15653. const left = near * leftFov;
  15654. const right = near * rightFov;
  15655. // Calculate the new camera's position offset from the
  15656. // left camera. xOffset should be roughly half `ipd`.
  15657. const zOffset = ipd / ( - leftFov + rightFov );
  15658. const xOffset = zOffset * - leftFov;
  15659. // TODO: Better way to apply this offset?
  15660. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15661. camera.translateX( xOffset );
  15662. camera.translateZ( zOffset );
  15663. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15664. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15665. // Find the union of the frustum values of the cameras and scale
  15666. // the values so that the near plane's position does not change in world space,
  15667. // although must now be relative to the new union camera.
  15668. const near2 = near + zOffset;
  15669. const far2 = far + zOffset;
  15670. const left2 = left - xOffset;
  15671. const right2 = right + ( ipd - xOffset );
  15672. const top2 = topFov * far / far2 * near2;
  15673. const bottom2 = bottomFov * far / far2 * near2;
  15674. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15675. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  15676. }
  15677. function updateCamera( camera, parent ) {
  15678. if ( parent === null ) {
  15679. camera.matrixWorld.copy( camera.matrix );
  15680. } else {
  15681. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15682. }
  15683. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15684. }
  15685. this.updateCamera = function ( camera ) {
  15686. if ( session === null ) return;
  15687. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15688. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15689. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15690. // Note that the new renderState won't apply until the next frame. See #18320
  15691. session.updateRenderState( {
  15692. depthNear: cameraVR.near,
  15693. depthFar: cameraVR.far
  15694. } );
  15695. _currentDepthNear = cameraVR.near;
  15696. _currentDepthFar = cameraVR.far;
  15697. }
  15698. const parent = camera.parent;
  15699. const cameras = cameraVR.cameras;
  15700. updateCamera( cameraVR, parent );
  15701. for ( let i = 0; i < cameras.length; i ++ ) {
  15702. updateCamera( cameras[ i ], parent );
  15703. }
  15704. // update projection matrix for proper view frustum culling
  15705. if ( cameras.length === 2 ) {
  15706. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15707. } else {
  15708. // assume single camera setup (AR)
  15709. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15710. }
  15711. // update user camera and its children
  15712. updateUserCamera( camera, cameraVR, parent );
  15713. };
  15714. function updateUserCamera( camera, cameraVR, parent ) {
  15715. if ( parent === null ) {
  15716. camera.matrix.copy( cameraVR.matrixWorld );
  15717. } else {
  15718. camera.matrix.copy( parent.matrixWorld );
  15719. camera.matrix.invert();
  15720. camera.matrix.multiply( cameraVR.matrixWorld );
  15721. }
  15722. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15723. camera.updateMatrixWorld( true );
  15724. const children = camera.children;
  15725. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15726. children[ i ].updateMatrixWorld( true );
  15727. }
  15728. camera.projectionMatrix.copy( cameraVR.projectionMatrix );
  15729. camera.projectionMatrixInverse.copy( cameraVR.projectionMatrixInverse );
  15730. if ( camera.isPerspectiveCamera ) {
  15731. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  15732. camera.zoom = 1;
  15733. }
  15734. }
  15735. this.getCamera = function () {
  15736. return cameraVR;
  15737. };
  15738. this.getFoveation = function () {
  15739. if ( glProjLayer === null && glBaseLayer === null ) {
  15740. return undefined;
  15741. }
  15742. return foveation;
  15743. };
  15744. this.setFoveation = function ( value ) {
  15745. // 0 = no foveation = full resolution
  15746. // 1 = maximum foveation = the edges render at lower resolution
  15747. foveation = value;
  15748. if ( glProjLayer !== null ) {
  15749. glProjLayer.fixedFoveation = value;
  15750. }
  15751. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15752. glBaseLayer.fixedFoveation = value;
  15753. }
  15754. };
  15755. this.getPlanes = function () {
  15756. return planes;
  15757. };
  15758. // Animation Loop
  15759. let onAnimationFrameCallback = null;
  15760. function onAnimationFrame( time, frame ) {
  15761. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15762. xrFrame = frame;
  15763. if ( pose !== null ) {
  15764. const views = pose.views;
  15765. if ( glBaseLayer !== null ) {
  15766. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15767. renderer.setRenderTarget( newRenderTarget );
  15768. }
  15769. let cameraVRNeedsUpdate = false;
  15770. // check if it's necessary to rebuild cameraVR's camera list
  15771. if ( views.length !== cameraVR.cameras.length ) {
  15772. cameraVR.cameras.length = 0;
  15773. cameraVRNeedsUpdate = true;
  15774. }
  15775. for ( let i = 0; i < views.length; i ++ ) {
  15776. const view = views[ i ];
  15777. let viewport = null;
  15778. if ( glBaseLayer !== null ) {
  15779. viewport = glBaseLayer.getViewport( view );
  15780. } else {
  15781. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15782. viewport = glSubImage.viewport;
  15783. // For side-by-side projection, we only produce a single texture for both eyes.
  15784. if ( i === 0 ) {
  15785. renderer.setRenderTargetTextures(
  15786. newRenderTarget,
  15787. glSubImage.colorTexture,
  15788. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15789. renderer.setRenderTarget( newRenderTarget );
  15790. }
  15791. }
  15792. let camera = cameras[ i ];
  15793. if ( camera === undefined ) {
  15794. camera = new PerspectiveCamera();
  15795. camera.layers.enable( i );
  15796. camera.viewport = new Vector4();
  15797. cameras[ i ] = camera;
  15798. }
  15799. camera.matrix.fromArray( view.transform.matrix );
  15800. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15801. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15802. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  15803. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15804. if ( i === 0 ) {
  15805. cameraVR.matrix.copy( camera.matrix );
  15806. cameraVR.matrix.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15807. }
  15808. if ( cameraVRNeedsUpdate === true ) {
  15809. cameraVR.cameras.push( camera );
  15810. }
  15811. }
  15812. }
  15813. //
  15814. for ( let i = 0; i < controllers.length; i ++ ) {
  15815. const inputSource = controllerInputSources[ i ];
  15816. const controller = controllers[ i ];
  15817. if ( inputSource !== null && controller !== undefined ) {
  15818. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15819. }
  15820. }
  15821. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15822. if ( frame.detectedPlanes ) {
  15823. scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } );
  15824. let planesToRemove = null;
  15825. for ( const plane of planes ) {
  15826. if ( ! frame.detectedPlanes.has( plane ) ) {
  15827. if ( planesToRemove === null ) {
  15828. planesToRemove = [];
  15829. }
  15830. planesToRemove.push( plane );
  15831. }
  15832. }
  15833. if ( planesToRemove !== null ) {
  15834. for ( const plane of planesToRemove ) {
  15835. planes.delete( plane );
  15836. planesLastChangedTimes.delete( plane );
  15837. scope.dispatchEvent( { type: 'planeremoved', data: plane } );
  15838. }
  15839. }
  15840. for ( const plane of frame.detectedPlanes ) {
  15841. if ( ! planes.has( plane ) ) {
  15842. planes.add( plane );
  15843. planesLastChangedTimes.set( plane, frame.lastChangedTime );
  15844. scope.dispatchEvent( { type: 'planeadded', data: plane } );
  15845. } else {
  15846. const lastKnownTime = planesLastChangedTimes.get( plane );
  15847. if ( plane.lastChangedTime > lastKnownTime ) {
  15848. planesLastChangedTimes.set( plane, plane.lastChangedTime );
  15849. scope.dispatchEvent( { type: 'planechanged', data: plane } );
  15850. }
  15851. }
  15852. }
  15853. }
  15854. xrFrame = null;
  15855. }
  15856. const animation = new WebGLAnimation();
  15857. animation.setAnimationLoop( onAnimationFrame );
  15858. this.setAnimationLoop = function ( callback ) {
  15859. onAnimationFrameCallback = callback;
  15860. };
  15861. this.dispose = function () {};
  15862. }
  15863. }
  15864. function WebGLMaterials( renderer, properties ) {
  15865. function refreshTransformUniform( map, uniform ) {
  15866. if ( map.matrixAutoUpdate === true ) {
  15867. map.updateMatrix();
  15868. }
  15869. uniform.value.copy( map.matrix );
  15870. }
  15871. function refreshFogUniforms( uniforms, fog ) {
  15872. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  15873. if ( fog.isFog ) {
  15874. uniforms.fogNear.value = fog.near;
  15875. uniforms.fogFar.value = fog.far;
  15876. } else if ( fog.isFogExp2 ) {
  15877. uniforms.fogDensity.value = fog.density;
  15878. }
  15879. }
  15880. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15881. if ( material.isMeshBasicMaterial ) {
  15882. refreshUniformsCommon( uniforms, material );
  15883. } else if ( material.isMeshLambertMaterial ) {
  15884. refreshUniformsCommon( uniforms, material );
  15885. } else if ( material.isMeshToonMaterial ) {
  15886. refreshUniformsCommon( uniforms, material );
  15887. refreshUniformsToon( uniforms, material );
  15888. } else if ( material.isMeshPhongMaterial ) {
  15889. refreshUniformsCommon( uniforms, material );
  15890. refreshUniformsPhong( uniforms, material );
  15891. } else if ( material.isMeshStandardMaterial ) {
  15892. refreshUniformsCommon( uniforms, material );
  15893. refreshUniformsStandard( uniforms, material );
  15894. if ( material.isMeshPhysicalMaterial ) {
  15895. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15896. }
  15897. } else if ( material.isMeshMatcapMaterial ) {
  15898. refreshUniformsCommon( uniforms, material );
  15899. refreshUniformsMatcap( uniforms, material );
  15900. } else if ( material.isMeshDepthMaterial ) {
  15901. refreshUniformsCommon( uniforms, material );
  15902. } else if ( material.isMeshDistanceMaterial ) {
  15903. refreshUniformsCommon( uniforms, material );
  15904. refreshUniformsDistance( uniforms, material );
  15905. } else if ( material.isMeshNormalMaterial ) {
  15906. refreshUniformsCommon( uniforms, material );
  15907. } else if ( material.isLineBasicMaterial ) {
  15908. refreshUniformsLine( uniforms, material );
  15909. if ( material.isLineDashedMaterial ) {
  15910. refreshUniformsDash( uniforms, material );
  15911. }
  15912. } else if ( material.isPointsMaterial ) {
  15913. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15914. } else if ( material.isSpriteMaterial ) {
  15915. refreshUniformsSprites( uniforms, material );
  15916. } else if ( material.isShadowMaterial ) {
  15917. uniforms.color.value.copy( material.color );
  15918. uniforms.opacity.value = material.opacity;
  15919. } else if ( material.isShaderMaterial ) {
  15920. material.uniformsNeedUpdate = false; // #15581
  15921. }
  15922. }
  15923. function refreshUniformsCommon( uniforms, material ) {
  15924. uniforms.opacity.value = material.opacity;
  15925. if ( material.color ) {
  15926. uniforms.diffuse.value.copy( material.color );
  15927. }
  15928. if ( material.emissive ) {
  15929. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15930. }
  15931. if ( material.map ) {
  15932. uniforms.map.value = material.map;
  15933. refreshTransformUniform( material.map, uniforms.mapTransform );
  15934. }
  15935. if ( material.alphaMap ) {
  15936. uniforms.alphaMap.value = material.alphaMap;
  15937. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  15938. }
  15939. if ( material.bumpMap ) {
  15940. uniforms.bumpMap.value = material.bumpMap;
  15941. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  15942. uniforms.bumpScale.value = material.bumpScale;
  15943. if ( material.side === BackSide ) {
  15944. uniforms.bumpScale.value *= - 1;
  15945. }
  15946. }
  15947. if ( material.normalMap ) {
  15948. uniforms.normalMap.value = material.normalMap;
  15949. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  15950. uniforms.normalScale.value.copy( material.normalScale );
  15951. if ( material.side === BackSide ) {
  15952. uniforms.normalScale.value.negate();
  15953. }
  15954. }
  15955. if ( material.displacementMap ) {
  15956. uniforms.displacementMap.value = material.displacementMap;
  15957. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  15958. uniforms.displacementScale.value = material.displacementScale;
  15959. uniforms.displacementBias.value = material.displacementBias;
  15960. }
  15961. if ( material.emissiveMap ) {
  15962. uniforms.emissiveMap.value = material.emissiveMap;
  15963. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  15964. }
  15965. if ( material.specularMap ) {
  15966. uniforms.specularMap.value = material.specularMap;
  15967. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  15968. }
  15969. if ( material.alphaTest > 0 ) {
  15970. uniforms.alphaTest.value = material.alphaTest;
  15971. }
  15972. const envMap = properties.get( material ).envMap;
  15973. if ( envMap ) {
  15974. uniforms.envMap.value = envMap;
  15975. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15976. uniforms.reflectivity.value = material.reflectivity;
  15977. uniforms.ior.value = material.ior;
  15978. uniforms.refractionRatio.value = material.refractionRatio;
  15979. }
  15980. if ( material.lightMap ) {
  15981. uniforms.lightMap.value = material.lightMap;
  15982. // artist-friendly light intensity scaling factor
  15983. const scaleFactor = ( renderer.useLegacyLights === true ) ? Math.PI : 1;
  15984. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15985. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  15986. }
  15987. if ( material.aoMap ) {
  15988. uniforms.aoMap.value = material.aoMap;
  15989. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15990. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  15991. }
  15992. }
  15993. function refreshUniformsLine( uniforms, material ) {
  15994. uniforms.diffuse.value.copy( material.color );
  15995. uniforms.opacity.value = material.opacity;
  15996. if ( material.map ) {
  15997. uniforms.map.value = material.map;
  15998. refreshTransformUniform( material.map, uniforms.mapTransform );
  15999. }
  16000. }
  16001. function refreshUniformsDash( uniforms, material ) {
  16002. uniforms.dashSize.value = material.dashSize;
  16003. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16004. uniforms.scale.value = material.scale;
  16005. }
  16006. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16007. uniforms.diffuse.value.copy( material.color );
  16008. uniforms.opacity.value = material.opacity;
  16009. uniforms.size.value = material.size * pixelRatio;
  16010. uniforms.scale.value = height * 0.5;
  16011. if ( material.map ) {
  16012. uniforms.map.value = material.map;
  16013. refreshTransformUniform( material.map, uniforms.uvTransform );
  16014. }
  16015. if ( material.alphaMap ) {
  16016. uniforms.alphaMap.value = material.alphaMap;
  16017. }
  16018. if ( material.alphaTest > 0 ) {
  16019. uniforms.alphaTest.value = material.alphaTest;
  16020. }
  16021. }
  16022. function refreshUniformsSprites( uniforms, material ) {
  16023. uniforms.diffuse.value.copy( material.color );
  16024. uniforms.opacity.value = material.opacity;
  16025. uniforms.rotation.value = material.rotation;
  16026. if ( material.map ) {
  16027. uniforms.map.value = material.map;
  16028. refreshTransformUniform( material.map, uniforms.mapTransform );
  16029. }
  16030. if ( material.alphaMap ) {
  16031. uniforms.alphaMap.value = material.alphaMap;
  16032. }
  16033. if ( material.alphaTest > 0 ) {
  16034. uniforms.alphaTest.value = material.alphaTest;
  16035. }
  16036. }
  16037. function refreshUniformsPhong( uniforms, material ) {
  16038. uniforms.specular.value.copy( material.specular );
  16039. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16040. }
  16041. function refreshUniformsToon( uniforms, material ) {
  16042. if ( material.gradientMap ) {
  16043. uniforms.gradientMap.value = material.gradientMap;
  16044. }
  16045. }
  16046. function refreshUniformsStandard( uniforms, material ) {
  16047. uniforms.metalness.value = material.metalness;
  16048. if ( material.metalnessMap ) {
  16049. uniforms.metalnessMap.value = material.metalnessMap;
  16050. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16051. }
  16052. uniforms.roughness.value = material.roughness;
  16053. if ( material.roughnessMap ) {
  16054. uniforms.roughnessMap.value = material.roughnessMap;
  16055. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16056. }
  16057. const envMap = properties.get( material ).envMap;
  16058. if ( envMap ) {
  16059. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16060. uniforms.envMapIntensity.value = material.envMapIntensity;
  16061. }
  16062. }
  16063. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16064. uniforms.ior.value = material.ior; // also part of uniforms common
  16065. if ( material.sheen > 0 ) {
  16066. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16067. uniforms.sheenRoughness.value = material.sheenRoughness;
  16068. if ( material.sheenColorMap ) {
  16069. uniforms.sheenColorMap.value = material.sheenColorMap;
  16070. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16071. }
  16072. if ( material.sheenRoughnessMap ) {
  16073. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16074. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16075. }
  16076. }
  16077. if ( material.clearcoat > 0 ) {
  16078. uniforms.clearcoat.value = material.clearcoat;
  16079. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16080. if ( material.clearcoatMap ) {
  16081. uniforms.clearcoatMap.value = material.clearcoatMap;
  16082. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16083. }
  16084. if ( material.clearcoatRoughnessMap ) {
  16085. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16086. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16087. }
  16088. if ( material.clearcoatNormalMap ) {
  16089. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16090. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16091. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16092. if ( material.side === BackSide ) {
  16093. uniforms.clearcoatNormalScale.value.negate();
  16094. }
  16095. }
  16096. }
  16097. if ( material.iridescence > 0 ) {
  16098. uniforms.iridescence.value = material.iridescence;
  16099. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16100. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16101. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16102. if ( material.iridescenceMap ) {
  16103. uniforms.iridescenceMap.value = material.iridescenceMap;
  16104. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16105. }
  16106. if ( material.iridescenceThicknessMap ) {
  16107. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16108. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16109. }
  16110. }
  16111. if ( material.transmission > 0 ) {
  16112. uniforms.transmission.value = material.transmission;
  16113. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16114. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16115. if ( material.transmissionMap ) {
  16116. uniforms.transmissionMap.value = material.transmissionMap;
  16117. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16118. }
  16119. uniforms.thickness.value = material.thickness;
  16120. if ( material.thicknessMap ) {
  16121. uniforms.thicknessMap.value = material.thicknessMap;
  16122. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16123. }
  16124. uniforms.attenuationDistance.value = material.attenuationDistance;
  16125. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16126. }
  16127. uniforms.specularIntensity.value = material.specularIntensity;
  16128. uniforms.specularColor.value.copy( material.specularColor );
  16129. if ( material.specularColorMap ) {
  16130. uniforms.specularColorMap.value = material.specularColorMap;
  16131. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16132. }
  16133. if ( material.specularIntensityMap ) {
  16134. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16135. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16136. }
  16137. }
  16138. function refreshUniformsMatcap( uniforms, material ) {
  16139. if ( material.matcap ) {
  16140. uniforms.matcap.value = material.matcap;
  16141. }
  16142. }
  16143. function refreshUniformsDistance( uniforms, material ) {
  16144. const light = properties.get( material ).light;
  16145. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16146. uniforms.nearDistance.value = light.shadow.camera.near;
  16147. uniforms.farDistance.value = light.shadow.camera.far;
  16148. }
  16149. return {
  16150. refreshFogUniforms: refreshFogUniforms,
  16151. refreshMaterialUniforms: refreshMaterialUniforms
  16152. };
  16153. }
  16154. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16155. let buffers = {};
  16156. let updateList = {};
  16157. let allocatedBindingPoints = [];
  16158. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( 35375 ) : 0; // binding points are global whereas block indices are per shader program
  16159. function bind( uniformsGroup, program ) {
  16160. const webglProgram = program.program;
  16161. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16162. }
  16163. function update( uniformsGroup, program ) {
  16164. let buffer = buffers[ uniformsGroup.id ];
  16165. if ( buffer === undefined ) {
  16166. prepareUniformsGroup( uniformsGroup );
  16167. buffer = createBuffer( uniformsGroup );
  16168. buffers[ uniformsGroup.id ] = buffer;
  16169. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16170. }
  16171. // ensure to update the binding points/block indices mapping for this program
  16172. const webglProgram = program.program;
  16173. state.updateUBOMapping( uniformsGroup, webglProgram );
  16174. // update UBO once per frame
  16175. const frame = info.render.frame;
  16176. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16177. updateBufferData( uniformsGroup );
  16178. updateList[ uniformsGroup.id ] = frame;
  16179. }
  16180. }
  16181. function createBuffer( uniformsGroup ) {
  16182. // the setup of an UBO is independent of a particular shader program but global
  16183. const bindingPointIndex = allocateBindingPointIndex();
  16184. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16185. const buffer = gl.createBuffer();
  16186. const size = uniformsGroup.__size;
  16187. const usage = uniformsGroup.usage;
  16188. gl.bindBuffer( 35345, buffer );
  16189. gl.bufferData( 35345, size, usage );
  16190. gl.bindBuffer( 35345, null );
  16191. gl.bindBufferBase( 35345, bindingPointIndex, buffer );
  16192. return buffer;
  16193. }
  16194. function allocateBindingPointIndex() {
  16195. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16196. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16197. allocatedBindingPoints.push( i );
  16198. return i;
  16199. }
  16200. }
  16201. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16202. return 0;
  16203. }
  16204. function updateBufferData( uniformsGroup ) {
  16205. const buffer = buffers[ uniformsGroup.id ];
  16206. const uniforms = uniformsGroup.uniforms;
  16207. const cache = uniformsGroup.__cache;
  16208. gl.bindBuffer( 35345, buffer );
  16209. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16210. const uniform = uniforms[ i ];
  16211. // partly update the buffer if necessary
  16212. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  16213. const offset = uniform.__offset;
  16214. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16215. let arrayOffset = 0;
  16216. for ( let i = 0; i < values.length; i ++ ) {
  16217. const value = values[ i ];
  16218. const info = getUniformSize( value );
  16219. if ( typeof value === 'number' ) {
  16220. uniform.__data[ 0 ] = value;
  16221. gl.bufferSubData( 35345, offset + arrayOffset, uniform.__data );
  16222. } else if ( value.isMatrix3 ) {
  16223. // manually converting 3x3 to 3x4
  16224. uniform.__data[ 0 ] = value.elements[ 0 ];
  16225. uniform.__data[ 1 ] = value.elements[ 1 ];
  16226. uniform.__data[ 2 ] = value.elements[ 2 ];
  16227. uniform.__data[ 3 ] = value.elements[ 0 ];
  16228. uniform.__data[ 4 ] = value.elements[ 3 ];
  16229. uniform.__data[ 5 ] = value.elements[ 4 ];
  16230. uniform.__data[ 6 ] = value.elements[ 5 ];
  16231. uniform.__data[ 7 ] = value.elements[ 0 ];
  16232. uniform.__data[ 8 ] = value.elements[ 6 ];
  16233. uniform.__data[ 9 ] = value.elements[ 7 ];
  16234. uniform.__data[ 10 ] = value.elements[ 8 ];
  16235. uniform.__data[ 11 ] = value.elements[ 0 ];
  16236. } else {
  16237. value.toArray( uniform.__data, arrayOffset );
  16238. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16239. }
  16240. }
  16241. gl.bufferSubData( 35345, offset, uniform.__data );
  16242. }
  16243. }
  16244. gl.bindBuffer( 35345, null );
  16245. }
  16246. function hasUniformChanged( uniform, index, cache ) {
  16247. const value = uniform.value;
  16248. if ( cache[ index ] === undefined ) {
  16249. // cache entry does not exist so far
  16250. if ( typeof value === 'number' ) {
  16251. cache[ index ] = value;
  16252. } else {
  16253. const values = Array.isArray( value ) ? value : [ value ];
  16254. const tempValues = [];
  16255. for ( let i = 0; i < values.length; i ++ ) {
  16256. tempValues.push( values[ i ].clone() );
  16257. }
  16258. cache[ index ] = tempValues;
  16259. }
  16260. return true;
  16261. } else {
  16262. // compare current value with cached entry
  16263. if ( typeof value === 'number' ) {
  16264. if ( cache[ index ] !== value ) {
  16265. cache[ index ] = value;
  16266. return true;
  16267. }
  16268. } else {
  16269. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  16270. const values = Array.isArray( value ) ? value : [ value ];
  16271. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  16272. const cachedObject = cachedObjects[ i ];
  16273. if ( cachedObject.equals( values[ i ] ) === false ) {
  16274. cachedObject.copy( values[ i ] );
  16275. return true;
  16276. }
  16277. }
  16278. }
  16279. }
  16280. return false;
  16281. }
  16282. function prepareUniformsGroup( uniformsGroup ) {
  16283. // determine total buffer size according to the STD140 layout
  16284. // Hint: STD140 is the only supported layout in WebGL 2
  16285. const uniforms = uniformsGroup.uniforms;
  16286. let offset = 0; // global buffer offset in bytes
  16287. const chunkSize = 16; // size of a chunk in bytes
  16288. let chunkOffset = 0; // offset within a single chunk in bytes
  16289. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16290. const uniform = uniforms[ i ];
  16291. const infos = {
  16292. boundary: 0, // bytes
  16293. storage: 0 // bytes
  16294. };
  16295. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16296. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  16297. const value = values[ j ];
  16298. const info = getUniformSize( value );
  16299. infos.boundary += info.boundary;
  16300. infos.storage += info.storage;
  16301. }
  16302. // the following two properties will be used for partial buffer updates
  16303. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16304. uniform.__offset = offset;
  16305. //
  16306. if ( i > 0 ) {
  16307. chunkOffset = offset % chunkSize;
  16308. const remainingSizeInChunk = chunkSize - chunkOffset;
  16309. // check for chunk overflow
  16310. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16311. // add padding and adjust offset
  16312. offset += ( chunkSize - chunkOffset );
  16313. uniform.__offset = offset;
  16314. }
  16315. }
  16316. offset += infos.storage;
  16317. }
  16318. // ensure correct final padding
  16319. chunkOffset = offset % chunkSize;
  16320. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16321. //
  16322. uniformsGroup.__size = offset;
  16323. uniformsGroup.__cache = {};
  16324. return this;
  16325. }
  16326. function getUniformSize( value ) {
  16327. const info = {
  16328. boundary: 0, // bytes
  16329. storage: 0 // bytes
  16330. };
  16331. // determine sizes according to STD140
  16332. if ( typeof value === 'number' ) {
  16333. // float/int
  16334. info.boundary = 4;
  16335. info.storage = 4;
  16336. } else if ( value.isVector2 ) {
  16337. // vec2
  16338. info.boundary = 8;
  16339. info.storage = 8;
  16340. } else if ( value.isVector3 || value.isColor ) {
  16341. // vec3
  16342. info.boundary = 16;
  16343. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16344. } else if ( value.isVector4 ) {
  16345. // vec4
  16346. info.boundary = 16;
  16347. info.storage = 16;
  16348. } else if ( value.isMatrix3 ) {
  16349. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16350. info.boundary = 48;
  16351. info.storage = 48;
  16352. } else if ( value.isMatrix4 ) {
  16353. // mat4
  16354. info.boundary = 64;
  16355. info.storage = 64;
  16356. } else if ( value.isTexture ) {
  16357. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16358. } else {
  16359. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16360. }
  16361. return info;
  16362. }
  16363. function onUniformsGroupsDispose( event ) {
  16364. const uniformsGroup = event.target;
  16365. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16366. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16367. allocatedBindingPoints.splice( index, 1 );
  16368. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16369. delete buffers[ uniformsGroup.id ];
  16370. delete updateList[ uniformsGroup.id ];
  16371. }
  16372. function dispose() {
  16373. for ( const id in buffers ) {
  16374. gl.deleteBuffer( buffers[ id ] );
  16375. }
  16376. allocatedBindingPoints = [];
  16377. buffers = {};
  16378. updateList = {};
  16379. }
  16380. return {
  16381. bind: bind,
  16382. update: update,
  16383. dispose: dispose
  16384. };
  16385. }
  16386. function createCanvasElement() {
  16387. const canvas = createElementNS( 'canvas' );
  16388. canvas.style.display = 'block';
  16389. return canvas;
  16390. }
  16391. class WebGLRenderer {
  16392. constructor( parameters = {} ) {
  16393. const {
  16394. canvas = createCanvasElement(),
  16395. context = null,
  16396. depth = true,
  16397. stencil = true,
  16398. alpha = false,
  16399. antialias = false,
  16400. premultipliedAlpha = true,
  16401. preserveDrawingBuffer = false,
  16402. powerPreference = 'default',
  16403. failIfMajorPerformanceCaveat = false,
  16404. } = parameters;
  16405. this.isWebGLRenderer = true;
  16406. let _alpha;
  16407. if ( context !== null ) {
  16408. _alpha = context.getContextAttributes().alpha;
  16409. } else {
  16410. _alpha = alpha;
  16411. }
  16412. let currentRenderList = null;
  16413. let currentRenderState = null;
  16414. // render() can be called from within a callback triggered by another render.
  16415. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16416. const renderListStack = [];
  16417. const renderStateStack = [];
  16418. // public properties
  16419. this.domElement = canvas;
  16420. // Debug configuration container
  16421. this.debug = {
  16422. /**
  16423. * Enables error checking and reporting when shader programs are being compiled
  16424. * @type {boolean}
  16425. */
  16426. checkShaderErrors: true,
  16427. /**
  16428. * Callback for custom error reporting.
  16429. * @type {?Function}
  16430. */
  16431. onShaderError: null
  16432. };
  16433. // clearing
  16434. this.autoClear = true;
  16435. this.autoClearColor = true;
  16436. this.autoClearDepth = true;
  16437. this.autoClearStencil = true;
  16438. // scene graph
  16439. this.sortObjects = true;
  16440. // user-defined clipping
  16441. this.clippingPlanes = [];
  16442. this.localClippingEnabled = false;
  16443. // physically based shading
  16444. this.outputEncoding = LinearEncoding;
  16445. // physical lights
  16446. this.useLegacyLights = true;
  16447. // tone mapping
  16448. this.toneMapping = NoToneMapping;
  16449. this.toneMappingExposure = 1.0;
  16450. // internal properties
  16451. const _this = this;
  16452. let _isContextLost = false;
  16453. // internal state cache
  16454. let _currentActiveCubeFace = 0;
  16455. let _currentActiveMipmapLevel = 0;
  16456. let _currentRenderTarget = null;
  16457. let _currentMaterialId = - 1;
  16458. let _currentCamera = null;
  16459. const _currentViewport = new Vector4();
  16460. const _currentScissor = new Vector4();
  16461. let _currentScissorTest = null;
  16462. //
  16463. let _width = canvas.width;
  16464. let _height = canvas.height;
  16465. let _pixelRatio = 1;
  16466. let _opaqueSort = null;
  16467. let _transparentSort = null;
  16468. const _viewport = new Vector4( 0, 0, _width, _height );
  16469. const _scissor = new Vector4( 0, 0, _width, _height );
  16470. let _scissorTest = false;
  16471. // frustum
  16472. const _frustum = new Frustum();
  16473. // clipping
  16474. let _clippingEnabled = false;
  16475. let _localClippingEnabled = false;
  16476. // transmission
  16477. let _transmissionRenderTarget = null;
  16478. // camera matrices cache
  16479. const _projScreenMatrix = new Matrix4();
  16480. const _vector3 = new Vector3();
  16481. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16482. function getTargetPixelRatio() {
  16483. return _currentRenderTarget === null ? _pixelRatio : 1;
  16484. }
  16485. // initialize
  16486. let _gl = context;
  16487. function getContext( contextNames, contextAttributes ) {
  16488. for ( let i = 0; i < contextNames.length; i ++ ) {
  16489. const contextName = contextNames[ i ];
  16490. const context = canvas.getContext( contextName, contextAttributes );
  16491. if ( context !== null ) return context;
  16492. }
  16493. return null;
  16494. }
  16495. try {
  16496. const contextAttributes = {
  16497. alpha: true,
  16498. depth,
  16499. stencil,
  16500. antialias,
  16501. premultipliedAlpha,
  16502. preserveDrawingBuffer,
  16503. powerPreference,
  16504. failIfMajorPerformanceCaveat,
  16505. };
  16506. // OffscreenCanvas does not have setAttribute, see #22811
  16507. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16508. // event listeners must be registered before WebGL context is created, see #12753
  16509. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16510. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16511. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16512. if ( _gl === null ) {
  16513. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16514. if ( _this.isWebGL1Renderer === true ) {
  16515. contextNames.shift();
  16516. }
  16517. _gl = getContext( contextNames, contextAttributes );
  16518. if ( _gl === null ) {
  16519. if ( getContext( contextNames ) ) {
  16520. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16521. } else {
  16522. throw new Error( 'Error creating WebGL context.' );
  16523. }
  16524. }
  16525. }
  16526. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16527. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16528. _gl.getShaderPrecisionFormat = function () {
  16529. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16530. };
  16531. }
  16532. } catch ( error ) {
  16533. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16534. throw error;
  16535. }
  16536. let extensions, capabilities, state, info;
  16537. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16538. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16539. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16540. let utils, bindingStates, uniformsGroups;
  16541. function initGLContext() {
  16542. extensions = new WebGLExtensions( _gl );
  16543. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16544. extensions.init( capabilities );
  16545. utils = new WebGLUtils( _gl, extensions, capabilities );
  16546. state = new WebGLState( _gl, extensions, capabilities );
  16547. info = new WebGLInfo();
  16548. properties = new WebGLProperties();
  16549. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16550. cubemaps = new WebGLCubeMaps( _this );
  16551. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16552. attributes = new WebGLAttributes( _gl, capabilities );
  16553. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16554. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16555. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16556. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16557. clipping = new WebGLClipping( properties );
  16558. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16559. materials = new WebGLMaterials( _this, properties );
  16560. renderLists = new WebGLRenderLists();
  16561. renderStates = new WebGLRenderStates( extensions, capabilities );
  16562. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  16563. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16564. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16565. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16566. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16567. info.programs = programCache.programs;
  16568. _this.capabilities = capabilities;
  16569. _this.extensions = extensions;
  16570. _this.properties = properties;
  16571. _this.renderLists = renderLists;
  16572. _this.shadowMap = shadowMap;
  16573. _this.state = state;
  16574. _this.info = info;
  16575. }
  16576. initGLContext();
  16577. // xr
  16578. const xr = new WebXRManager( _this, _gl );
  16579. this.xr = xr;
  16580. // API
  16581. this.getContext = function () {
  16582. return _gl;
  16583. };
  16584. this.getContextAttributes = function () {
  16585. return _gl.getContextAttributes();
  16586. };
  16587. this.forceContextLoss = function () {
  16588. const extension = extensions.get( 'WEBGL_lose_context' );
  16589. if ( extension ) extension.loseContext();
  16590. };
  16591. this.forceContextRestore = function () {
  16592. const extension = extensions.get( 'WEBGL_lose_context' );
  16593. if ( extension ) extension.restoreContext();
  16594. };
  16595. this.getPixelRatio = function () {
  16596. return _pixelRatio;
  16597. };
  16598. this.setPixelRatio = function ( value ) {
  16599. if ( value === undefined ) return;
  16600. _pixelRatio = value;
  16601. this.setSize( _width, _height, false );
  16602. };
  16603. this.getSize = function ( target ) {
  16604. return target.set( _width, _height );
  16605. };
  16606. this.setSize = function ( width, height, updateStyle = true ) {
  16607. if ( xr.isPresenting ) {
  16608. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16609. return;
  16610. }
  16611. _width = width;
  16612. _height = height;
  16613. canvas.width = Math.floor( width * _pixelRatio );
  16614. canvas.height = Math.floor( height * _pixelRatio );
  16615. if ( updateStyle === true ) {
  16616. canvas.style.width = width + 'px';
  16617. canvas.style.height = height + 'px';
  16618. }
  16619. this.setViewport( 0, 0, width, height );
  16620. };
  16621. this.getDrawingBufferSize = function ( target ) {
  16622. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16623. };
  16624. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16625. _width = width;
  16626. _height = height;
  16627. _pixelRatio = pixelRatio;
  16628. canvas.width = Math.floor( width * pixelRatio );
  16629. canvas.height = Math.floor( height * pixelRatio );
  16630. this.setViewport( 0, 0, width, height );
  16631. };
  16632. this.getCurrentViewport = function ( target ) {
  16633. return target.copy( _currentViewport );
  16634. };
  16635. this.getViewport = function ( target ) {
  16636. return target.copy( _viewport );
  16637. };
  16638. this.setViewport = function ( x, y, width, height ) {
  16639. if ( x.isVector4 ) {
  16640. _viewport.set( x.x, x.y, x.z, x.w );
  16641. } else {
  16642. _viewport.set( x, y, width, height );
  16643. }
  16644. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16645. };
  16646. this.getScissor = function ( target ) {
  16647. return target.copy( _scissor );
  16648. };
  16649. this.setScissor = function ( x, y, width, height ) {
  16650. if ( x.isVector4 ) {
  16651. _scissor.set( x.x, x.y, x.z, x.w );
  16652. } else {
  16653. _scissor.set( x, y, width, height );
  16654. }
  16655. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16656. };
  16657. this.getScissorTest = function () {
  16658. return _scissorTest;
  16659. };
  16660. this.setScissorTest = function ( boolean ) {
  16661. state.setScissorTest( _scissorTest = boolean );
  16662. };
  16663. this.setOpaqueSort = function ( method ) {
  16664. _opaqueSort = method;
  16665. };
  16666. this.setTransparentSort = function ( method ) {
  16667. _transparentSort = method;
  16668. };
  16669. // Clearing
  16670. this.getClearColor = function ( target ) {
  16671. return target.copy( background.getClearColor() );
  16672. };
  16673. this.setClearColor = function () {
  16674. background.setClearColor.apply( background, arguments );
  16675. };
  16676. this.getClearAlpha = function () {
  16677. return background.getClearAlpha();
  16678. };
  16679. this.setClearAlpha = function () {
  16680. background.setClearAlpha.apply( background, arguments );
  16681. };
  16682. this.clear = function ( color = true, depth = true, stencil = true ) {
  16683. let bits = 0;
  16684. if ( color ) bits |= 16384;
  16685. if ( depth ) bits |= 256;
  16686. if ( stencil ) bits |= 1024;
  16687. _gl.clear( bits );
  16688. };
  16689. this.clearColor = function () {
  16690. this.clear( true, false, false );
  16691. };
  16692. this.clearDepth = function () {
  16693. this.clear( false, true, false );
  16694. };
  16695. this.clearStencil = function () {
  16696. this.clear( false, false, true );
  16697. };
  16698. //
  16699. this.dispose = function () {
  16700. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16701. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16702. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16703. renderLists.dispose();
  16704. renderStates.dispose();
  16705. properties.dispose();
  16706. cubemaps.dispose();
  16707. cubeuvmaps.dispose();
  16708. objects.dispose();
  16709. bindingStates.dispose();
  16710. uniformsGroups.dispose();
  16711. programCache.dispose();
  16712. xr.dispose();
  16713. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16714. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16715. if ( _transmissionRenderTarget ) {
  16716. _transmissionRenderTarget.dispose();
  16717. _transmissionRenderTarget = null;
  16718. }
  16719. animation.stop();
  16720. };
  16721. // Events
  16722. function onContextLost( event ) {
  16723. event.preventDefault();
  16724. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16725. _isContextLost = true;
  16726. }
  16727. function onContextRestore( /* event */ ) {
  16728. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16729. _isContextLost = false;
  16730. const infoAutoReset = info.autoReset;
  16731. const shadowMapEnabled = shadowMap.enabled;
  16732. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16733. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16734. const shadowMapType = shadowMap.type;
  16735. initGLContext();
  16736. info.autoReset = infoAutoReset;
  16737. shadowMap.enabled = shadowMapEnabled;
  16738. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16739. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16740. shadowMap.type = shadowMapType;
  16741. }
  16742. function onContextCreationError( event ) {
  16743. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16744. }
  16745. function onMaterialDispose( event ) {
  16746. const material = event.target;
  16747. material.removeEventListener( 'dispose', onMaterialDispose );
  16748. deallocateMaterial( material );
  16749. }
  16750. // Buffer deallocation
  16751. function deallocateMaterial( material ) {
  16752. releaseMaterialProgramReferences( material );
  16753. properties.remove( material );
  16754. }
  16755. function releaseMaterialProgramReferences( material ) {
  16756. const programs = properties.get( material ).programs;
  16757. if ( programs !== undefined ) {
  16758. programs.forEach( function ( program ) {
  16759. programCache.releaseProgram( program );
  16760. } );
  16761. if ( material.isShaderMaterial ) {
  16762. programCache.releaseShaderCache( material );
  16763. }
  16764. }
  16765. }
  16766. // Buffer rendering
  16767. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16768. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16769. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16770. const program = setProgram( camera, scene, geometry, material, object );
  16771. state.setMaterial( material, frontFaceCW );
  16772. //
  16773. let index = geometry.index;
  16774. let rangeFactor = 1;
  16775. if ( material.wireframe === true ) {
  16776. index = geometries.getWireframeAttribute( geometry );
  16777. rangeFactor = 2;
  16778. }
  16779. //
  16780. const drawRange = geometry.drawRange;
  16781. const position = geometry.attributes.position;
  16782. let drawStart = drawRange.start * rangeFactor;
  16783. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  16784. if ( group !== null ) {
  16785. drawStart = Math.max( drawStart, group.start * rangeFactor );
  16786. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  16787. }
  16788. if ( index !== null ) {
  16789. drawStart = Math.max( drawStart, 0 );
  16790. drawEnd = Math.min( drawEnd, index.count );
  16791. } else if ( position !== undefined && position !== null ) {
  16792. drawStart = Math.max( drawStart, 0 );
  16793. drawEnd = Math.min( drawEnd, position.count );
  16794. }
  16795. const drawCount = drawEnd - drawStart;
  16796. if ( drawCount < 0 || drawCount === Infinity ) return;
  16797. //
  16798. bindingStates.setup( object, material, program, geometry, index );
  16799. let attribute;
  16800. let renderer = bufferRenderer;
  16801. if ( index !== null ) {
  16802. attribute = attributes.get( index );
  16803. renderer = indexedBufferRenderer;
  16804. renderer.setIndex( attribute );
  16805. }
  16806. //
  16807. if ( object.isMesh ) {
  16808. if ( material.wireframe === true ) {
  16809. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16810. renderer.setMode( 1 );
  16811. } else {
  16812. renderer.setMode( 4 );
  16813. }
  16814. } else if ( object.isLine ) {
  16815. let lineWidth = material.linewidth;
  16816. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16817. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16818. if ( object.isLineSegments ) {
  16819. renderer.setMode( 1 );
  16820. } else if ( object.isLineLoop ) {
  16821. renderer.setMode( 2 );
  16822. } else {
  16823. renderer.setMode( 3 );
  16824. }
  16825. } else if ( object.isPoints ) {
  16826. renderer.setMode( 0 );
  16827. } else if ( object.isSprite ) {
  16828. renderer.setMode( 4 );
  16829. }
  16830. if ( object.isInstancedMesh ) {
  16831. renderer.renderInstances( drawStart, drawCount, object.count );
  16832. } else if ( geometry.isInstancedBufferGeometry ) {
  16833. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  16834. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  16835. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16836. } else {
  16837. renderer.render( drawStart, drawCount );
  16838. }
  16839. };
  16840. // Compile
  16841. this.compile = function ( scene, camera ) {
  16842. function prepare( material, scene, object ) {
  16843. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16844. material.side = BackSide;
  16845. material.needsUpdate = true;
  16846. getProgram( material, scene, object );
  16847. material.side = FrontSide;
  16848. material.needsUpdate = true;
  16849. getProgram( material, scene, object );
  16850. material.side = DoubleSide;
  16851. } else {
  16852. getProgram( material, scene, object );
  16853. }
  16854. }
  16855. currentRenderState = renderStates.get( scene );
  16856. currentRenderState.init();
  16857. renderStateStack.push( currentRenderState );
  16858. scene.traverseVisible( function ( object ) {
  16859. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16860. currentRenderState.pushLight( object );
  16861. if ( object.castShadow ) {
  16862. currentRenderState.pushShadow( object );
  16863. }
  16864. }
  16865. } );
  16866. currentRenderState.setupLights( _this.useLegacyLights );
  16867. scene.traverse( function ( object ) {
  16868. const material = object.material;
  16869. if ( material ) {
  16870. if ( Array.isArray( material ) ) {
  16871. for ( let i = 0; i < material.length; i ++ ) {
  16872. const material2 = material[ i ];
  16873. prepare( material2, scene, object );
  16874. }
  16875. } else {
  16876. prepare( material, scene, object );
  16877. }
  16878. }
  16879. } );
  16880. renderStateStack.pop();
  16881. currentRenderState = null;
  16882. };
  16883. // Animation Loop
  16884. let onAnimationFrameCallback = null;
  16885. function onAnimationFrame( time ) {
  16886. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16887. }
  16888. function onXRSessionStart() {
  16889. animation.stop();
  16890. }
  16891. function onXRSessionEnd() {
  16892. animation.start();
  16893. }
  16894. const animation = new WebGLAnimation();
  16895. animation.setAnimationLoop( onAnimationFrame );
  16896. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16897. this.setAnimationLoop = function ( callback ) {
  16898. onAnimationFrameCallback = callback;
  16899. xr.setAnimationLoop( callback );
  16900. ( callback === null ) ? animation.stop() : animation.start();
  16901. };
  16902. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16903. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16904. // Rendering
  16905. this.render = function ( scene, camera ) {
  16906. if ( camera !== undefined && camera.isCamera !== true ) {
  16907. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16908. return;
  16909. }
  16910. if ( _isContextLost === true ) return;
  16911. // update scene graph
  16912. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16913. // update camera matrices and frustum
  16914. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16915. if ( xr.enabled === true && xr.isPresenting === true ) {
  16916. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16917. camera = xr.getCamera(); // use XR camera for rendering
  16918. }
  16919. //
  16920. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16921. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16922. currentRenderState.init();
  16923. renderStateStack.push( currentRenderState );
  16924. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16925. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16926. _localClippingEnabled = this.localClippingEnabled;
  16927. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  16928. currentRenderList = renderLists.get( scene, renderListStack.length );
  16929. currentRenderList.init();
  16930. renderListStack.push( currentRenderList );
  16931. projectObject( scene, camera, 0, _this.sortObjects );
  16932. currentRenderList.finish();
  16933. if ( _this.sortObjects === true ) {
  16934. currentRenderList.sort( _opaqueSort, _transparentSort );
  16935. }
  16936. //
  16937. if ( _clippingEnabled === true ) clipping.beginShadows();
  16938. const shadowsArray = currentRenderState.state.shadowsArray;
  16939. shadowMap.render( shadowsArray, scene, camera );
  16940. if ( _clippingEnabled === true ) clipping.endShadows();
  16941. //
  16942. if ( this.info.autoReset === true ) this.info.reset();
  16943. //
  16944. background.render( currentRenderList, scene );
  16945. // render scene
  16946. currentRenderState.setupLights( _this.useLegacyLights );
  16947. if ( camera.isArrayCamera ) {
  16948. const cameras = camera.cameras;
  16949. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16950. const camera2 = cameras[ i ];
  16951. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16952. }
  16953. } else {
  16954. renderScene( currentRenderList, scene, camera );
  16955. }
  16956. //
  16957. if ( _currentRenderTarget !== null ) {
  16958. // resolve multisample renderbuffers to a single-sample texture if necessary
  16959. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16960. // Generate mipmap if we're using any kind of mipmap filtering
  16961. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16962. }
  16963. //
  16964. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16965. // _gl.finish();
  16966. bindingStates.resetDefaultState();
  16967. _currentMaterialId = - 1;
  16968. _currentCamera = null;
  16969. renderStateStack.pop();
  16970. if ( renderStateStack.length > 0 ) {
  16971. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16972. } else {
  16973. currentRenderState = null;
  16974. }
  16975. renderListStack.pop();
  16976. if ( renderListStack.length > 0 ) {
  16977. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16978. } else {
  16979. currentRenderList = null;
  16980. }
  16981. };
  16982. function projectObject( object, camera, groupOrder, sortObjects ) {
  16983. if ( object.visible === false ) return;
  16984. const visible = object.layers.test( camera.layers );
  16985. if ( visible ) {
  16986. if ( object.isGroup ) {
  16987. groupOrder = object.renderOrder;
  16988. } else if ( object.isLOD ) {
  16989. if ( object.autoUpdate === true ) object.update( camera );
  16990. } else if ( object.isLight ) {
  16991. currentRenderState.pushLight( object );
  16992. if ( object.castShadow ) {
  16993. currentRenderState.pushShadow( object );
  16994. }
  16995. } else if ( object.isSprite ) {
  16996. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16997. if ( sortObjects ) {
  16998. _vector3.setFromMatrixPosition( object.matrixWorld )
  16999. .applyMatrix4( _projScreenMatrix );
  17000. }
  17001. const geometry = objects.update( object );
  17002. const material = object.material;
  17003. if ( material.visible ) {
  17004. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17005. }
  17006. }
  17007. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17008. if ( object.isSkinnedMesh ) {
  17009. // update skeleton only once in a frame
  17010. if ( object.skeleton.frame !== info.render.frame ) {
  17011. object.skeleton.update();
  17012. object.skeleton.frame = info.render.frame;
  17013. }
  17014. }
  17015. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17016. if ( sortObjects ) {
  17017. _vector3.setFromMatrixPosition( object.matrixWorld )
  17018. .applyMatrix4( _projScreenMatrix );
  17019. }
  17020. const geometry = objects.update( object );
  17021. const material = object.material;
  17022. if ( Array.isArray( material ) ) {
  17023. const groups = geometry.groups;
  17024. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17025. const group = groups[ i ];
  17026. const groupMaterial = material[ group.materialIndex ];
  17027. if ( groupMaterial && groupMaterial.visible ) {
  17028. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  17029. }
  17030. }
  17031. } else if ( material.visible ) {
  17032. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17033. }
  17034. }
  17035. }
  17036. }
  17037. const children = object.children;
  17038. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17039. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17040. }
  17041. }
  17042. function renderScene( currentRenderList, scene, camera, viewport ) {
  17043. const opaqueObjects = currentRenderList.opaque;
  17044. const transmissiveObjects = currentRenderList.transmissive;
  17045. const transparentObjects = currentRenderList.transparent;
  17046. currentRenderState.setupLightsView( camera );
  17047. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17048. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17049. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17050. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17051. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17052. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17053. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17054. state.buffers.depth.setTest( true );
  17055. state.buffers.depth.setMask( true );
  17056. state.buffers.color.setMask( true );
  17057. state.setPolygonOffset( false );
  17058. }
  17059. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17060. if ( _transmissionRenderTarget === null ) {
  17061. const isWebGL2 = capabilities.isWebGL2;
  17062. _transmissionRenderTarget = new WebGLRenderTarget( 1024, 1024, {
  17063. generateMipmaps: true,
  17064. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  17065. minFilter: LinearMipmapLinearFilter,
  17066. samples: ( isWebGL2 && antialias === true ) ? 4 : 0
  17067. } );
  17068. // debug
  17069. /*
  17070. const geometry = new PlaneGeometry();
  17071. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17072. const mesh = new Mesh( geometry, material );
  17073. scene.add( mesh );
  17074. */
  17075. }
  17076. //
  17077. const currentRenderTarget = _this.getRenderTarget();
  17078. _this.setRenderTarget( _transmissionRenderTarget );
  17079. _this.clear();
  17080. // Turn off the features which can affect the frag color for opaque objects pass.
  17081. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17082. const currentToneMapping = _this.toneMapping;
  17083. _this.toneMapping = NoToneMapping;
  17084. renderObjects( opaqueObjects, scene, camera );
  17085. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17086. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17087. let renderTargetNeedsUpdate = false;
  17088. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17089. const renderItem = transmissiveObjects[ i ];
  17090. const object = renderItem.object;
  17091. const geometry = renderItem.geometry;
  17092. const material = renderItem.material;
  17093. const group = renderItem.group;
  17094. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17095. const currentSide = material.side;
  17096. material.side = BackSide;
  17097. material.needsUpdate = true;
  17098. renderObject( object, scene, camera, geometry, material, group );
  17099. material.side = currentSide;
  17100. material.needsUpdate = true;
  17101. renderTargetNeedsUpdate = true;
  17102. }
  17103. }
  17104. if ( renderTargetNeedsUpdate === true ) {
  17105. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17106. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17107. }
  17108. _this.setRenderTarget( currentRenderTarget );
  17109. _this.toneMapping = currentToneMapping;
  17110. }
  17111. function renderObjects( renderList, scene, camera ) {
  17112. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17113. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17114. const renderItem = renderList[ i ];
  17115. const object = renderItem.object;
  17116. const geometry = renderItem.geometry;
  17117. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17118. const group = renderItem.group;
  17119. if ( object.layers.test( camera.layers ) ) {
  17120. renderObject( object, scene, camera, geometry, material, group );
  17121. }
  17122. }
  17123. }
  17124. function renderObject( object, scene, camera, geometry, material, group ) {
  17125. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17126. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17127. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17128. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17129. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17130. material.side = BackSide;
  17131. material.needsUpdate = true;
  17132. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17133. material.side = FrontSide;
  17134. material.needsUpdate = true;
  17135. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17136. material.side = DoubleSide;
  17137. } else {
  17138. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17139. }
  17140. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17141. }
  17142. function getProgram( material, scene, object ) {
  17143. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17144. const materialProperties = properties.get( material );
  17145. const lights = currentRenderState.state.lights;
  17146. const shadowsArray = currentRenderState.state.shadowsArray;
  17147. const lightsStateVersion = lights.state.version;
  17148. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17149. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17150. let programs = materialProperties.programs;
  17151. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17152. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17153. materialProperties.fog = scene.fog;
  17154. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17155. if ( programs === undefined ) {
  17156. // new material
  17157. material.addEventListener( 'dispose', onMaterialDispose );
  17158. programs = new Map();
  17159. materialProperties.programs = programs;
  17160. }
  17161. let program = programs.get( programCacheKey );
  17162. if ( program !== undefined ) {
  17163. // early out if program and light state is identical
  17164. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17165. updateCommonMaterialProperties( material, parameters );
  17166. return program;
  17167. }
  17168. } else {
  17169. parameters.uniforms = programCache.getUniforms( material );
  17170. material.onBuild( object, parameters, _this );
  17171. material.onBeforeCompile( parameters, _this );
  17172. program = programCache.acquireProgram( parameters, programCacheKey );
  17173. programs.set( programCacheKey, program );
  17174. materialProperties.uniforms = parameters.uniforms;
  17175. }
  17176. const uniforms = materialProperties.uniforms;
  17177. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17178. uniforms.clippingPlanes = clipping.uniform;
  17179. }
  17180. updateCommonMaterialProperties( material, parameters );
  17181. // store the light setup it was created for
  17182. materialProperties.needsLights = materialNeedsLights( material );
  17183. materialProperties.lightsStateVersion = lightsStateVersion;
  17184. if ( materialProperties.needsLights ) {
  17185. // wire up the material to this renderer's lighting state
  17186. uniforms.ambientLightColor.value = lights.state.ambient;
  17187. uniforms.lightProbe.value = lights.state.probe;
  17188. uniforms.directionalLights.value = lights.state.directional;
  17189. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17190. uniforms.spotLights.value = lights.state.spot;
  17191. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17192. uniforms.rectAreaLights.value = lights.state.rectArea;
  17193. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17194. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17195. uniforms.pointLights.value = lights.state.point;
  17196. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17197. uniforms.hemisphereLights.value = lights.state.hemi;
  17198. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17199. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17200. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17201. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17202. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17203. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17204. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17205. // TODO (abelnation): add area lights shadow info to uniforms
  17206. }
  17207. const progUniforms = program.getUniforms();
  17208. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17209. materialProperties.currentProgram = program;
  17210. materialProperties.uniformsList = uniformsList;
  17211. return program;
  17212. }
  17213. function updateCommonMaterialProperties( material, parameters ) {
  17214. const materialProperties = properties.get( material );
  17215. materialProperties.outputEncoding = parameters.outputEncoding;
  17216. materialProperties.instancing = parameters.instancing;
  17217. materialProperties.skinning = parameters.skinning;
  17218. materialProperties.morphTargets = parameters.morphTargets;
  17219. materialProperties.morphNormals = parameters.morphNormals;
  17220. materialProperties.morphColors = parameters.morphColors;
  17221. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17222. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17223. materialProperties.numIntersection = parameters.numClipIntersection;
  17224. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17225. materialProperties.vertexTangents = parameters.vertexTangents;
  17226. materialProperties.toneMapping = parameters.toneMapping;
  17227. }
  17228. function setProgram( camera, scene, geometry, material, object ) {
  17229. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17230. textures.resetTextureUnits();
  17231. const fog = scene.fog;
  17232. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17233. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  17234. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17235. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17236. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  17237. const morphTargets = !! geometry.morphAttributes.position;
  17238. const morphNormals = !! geometry.morphAttributes.normal;
  17239. const morphColors = !! geometry.morphAttributes.color;
  17240. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  17241. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17242. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  17243. const materialProperties = properties.get( material );
  17244. const lights = currentRenderState.state.lights;
  17245. if ( _clippingEnabled === true ) {
  17246. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17247. const useCache =
  17248. camera === _currentCamera &&
  17249. material.id === _currentMaterialId;
  17250. // we might want to call this function with some ClippingGroup
  17251. // object instead of the material, once it becomes feasible
  17252. // (#8465, #8379)
  17253. clipping.setState( material, camera, useCache );
  17254. }
  17255. }
  17256. //
  17257. let needsProgramChange = false;
  17258. if ( material.version === materialProperties.__version ) {
  17259. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17260. needsProgramChange = true;
  17261. } else if ( materialProperties.outputEncoding !== encoding ) {
  17262. needsProgramChange = true;
  17263. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17264. needsProgramChange = true;
  17265. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17266. needsProgramChange = true;
  17267. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17268. needsProgramChange = true;
  17269. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17270. needsProgramChange = true;
  17271. } else if ( materialProperties.envMap !== envMap ) {
  17272. needsProgramChange = true;
  17273. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17274. needsProgramChange = true;
  17275. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17276. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17277. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17278. needsProgramChange = true;
  17279. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17280. needsProgramChange = true;
  17281. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17282. needsProgramChange = true;
  17283. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17284. needsProgramChange = true;
  17285. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17286. needsProgramChange = true;
  17287. } else if ( materialProperties.morphColors !== morphColors ) {
  17288. needsProgramChange = true;
  17289. } else if ( materialProperties.toneMapping !== toneMapping ) {
  17290. needsProgramChange = true;
  17291. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  17292. needsProgramChange = true;
  17293. }
  17294. } else {
  17295. needsProgramChange = true;
  17296. materialProperties.__version = material.version;
  17297. }
  17298. //
  17299. let program = materialProperties.currentProgram;
  17300. if ( needsProgramChange === true ) {
  17301. program = getProgram( material, scene, object );
  17302. }
  17303. let refreshProgram = false;
  17304. let refreshMaterial = false;
  17305. let refreshLights = false;
  17306. const p_uniforms = program.getUniforms(),
  17307. m_uniforms = materialProperties.uniforms;
  17308. if ( state.useProgram( program.program ) ) {
  17309. refreshProgram = true;
  17310. refreshMaterial = true;
  17311. refreshLights = true;
  17312. }
  17313. if ( material.id !== _currentMaterialId ) {
  17314. _currentMaterialId = material.id;
  17315. refreshMaterial = true;
  17316. }
  17317. if ( refreshProgram || _currentCamera !== camera ) {
  17318. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17319. if ( capabilities.logarithmicDepthBuffer ) {
  17320. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17321. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17322. }
  17323. if ( _currentCamera !== camera ) {
  17324. _currentCamera = camera;
  17325. // lighting uniforms depend on the camera so enforce an update
  17326. // now, in case this material supports lights - or later, when
  17327. // the next material that does gets activated:
  17328. refreshMaterial = true; // set to true on material change
  17329. refreshLights = true; // remains set until update done
  17330. }
  17331. // load material specific uniforms
  17332. // (shader material also gets them for the sake of genericity)
  17333. if ( material.isShaderMaterial ||
  17334. material.isMeshPhongMaterial ||
  17335. material.isMeshToonMaterial ||
  17336. material.isMeshStandardMaterial ||
  17337. material.envMap ) {
  17338. const uCamPos = p_uniforms.map.cameraPosition;
  17339. if ( uCamPos !== undefined ) {
  17340. uCamPos.setValue( _gl,
  17341. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17342. }
  17343. }
  17344. if ( material.isMeshPhongMaterial ||
  17345. material.isMeshToonMaterial ||
  17346. material.isMeshLambertMaterial ||
  17347. material.isMeshBasicMaterial ||
  17348. material.isMeshStandardMaterial ||
  17349. material.isShaderMaterial ) {
  17350. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17351. }
  17352. if ( material.isMeshPhongMaterial ||
  17353. material.isMeshToonMaterial ||
  17354. material.isMeshLambertMaterial ||
  17355. material.isMeshBasicMaterial ||
  17356. material.isMeshStandardMaterial ||
  17357. material.isShaderMaterial ||
  17358. material.isShadowMaterial ||
  17359. object.isSkinnedMesh ) {
  17360. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17361. }
  17362. }
  17363. // skinning and morph target uniforms must be set even if material didn't change
  17364. // auto-setting of texture unit for bone and morph texture must go before other textures
  17365. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17366. if ( object.isSkinnedMesh ) {
  17367. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17368. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17369. const skeleton = object.skeleton;
  17370. if ( skeleton ) {
  17371. if ( capabilities.floatVertexTextures ) {
  17372. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17373. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17374. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17375. } else {
  17376. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17377. }
  17378. }
  17379. }
  17380. const morphAttributes = geometry.morphAttributes;
  17381. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17382. morphtargets.update( object, geometry, program );
  17383. }
  17384. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17385. materialProperties.receiveShadow = object.receiveShadow;
  17386. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17387. }
  17388. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17389. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17390. m_uniforms.envMap.value = envMap;
  17391. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17392. }
  17393. if ( refreshMaterial ) {
  17394. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17395. if ( materialProperties.needsLights ) {
  17396. // the current material requires lighting info
  17397. // note: all lighting uniforms are always set correctly
  17398. // they simply reference the renderer's state for their
  17399. // values
  17400. //
  17401. // use the current material's .needsUpdate flags to set
  17402. // the GL state when required
  17403. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17404. }
  17405. // refresh uniforms common to several materials
  17406. if ( fog && material.fog === true ) {
  17407. materials.refreshFogUniforms( m_uniforms, fog );
  17408. }
  17409. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17410. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17411. }
  17412. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17413. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17414. material.uniformsNeedUpdate = false;
  17415. }
  17416. if ( material.isSpriteMaterial ) {
  17417. p_uniforms.setValue( _gl, 'center', object.center );
  17418. }
  17419. // common matrices
  17420. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17421. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17422. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17423. // UBOs
  17424. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17425. const groups = material.uniformsGroups;
  17426. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17427. if ( capabilities.isWebGL2 ) {
  17428. const group = groups[ i ];
  17429. uniformsGroups.update( group, program );
  17430. uniformsGroups.bind( group, program );
  17431. } else {
  17432. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17433. }
  17434. }
  17435. }
  17436. return program;
  17437. }
  17438. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17439. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17440. uniforms.ambientLightColor.needsUpdate = value;
  17441. uniforms.lightProbe.needsUpdate = value;
  17442. uniforms.directionalLights.needsUpdate = value;
  17443. uniforms.directionalLightShadows.needsUpdate = value;
  17444. uniforms.pointLights.needsUpdate = value;
  17445. uniforms.pointLightShadows.needsUpdate = value;
  17446. uniforms.spotLights.needsUpdate = value;
  17447. uniforms.spotLightShadows.needsUpdate = value;
  17448. uniforms.rectAreaLights.needsUpdate = value;
  17449. uniforms.hemisphereLights.needsUpdate = value;
  17450. }
  17451. function materialNeedsLights( material ) {
  17452. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17453. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17454. ( material.isShaderMaterial && material.lights === true );
  17455. }
  17456. this.getActiveCubeFace = function () {
  17457. return _currentActiveCubeFace;
  17458. };
  17459. this.getActiveMipmapLevel = function () {
  17460. return _currentActiveMipmapLevel;
  17461. };
  17462. this.getRenderTarget = function () {
  17463. return _currentRenderTarget;
  17464. };
  17465. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17466. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17467. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17468. const renderTargetProperties = properties.get( renderTarget );
  17469. renderTargetProperties.__hasExternalTextures = true;
  17470. if ( renderTargetProperties.__hasExternalTextures ) {
  17471. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17472. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17473. // The multisample_render_to_texture extension doesn't work properly if there
  17474. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17475. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17476. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17477. renderTargetProperties.__useRenderToTexture = false;
  17478. }
  17479. }
  17480. }
  17481. };
  17482. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17483. const renderTargetProperties = properties.get( renderTarget );
  17484. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17485. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17486. };
  17487. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17488. _currentRenderTarget = renderTarget;
  17489. _currentActiveCubeFace = activeCubeFace;
  17490. _currentActiveMipmapLevel = activeMipmapLevel;
  17491. let useDefaultFramebuffer = true;
  17492. let framebuffer = null;
  17493. let isCube = false;
  17494. let isRenderTarget3D = false;
  17495. if ( renderTarget ) {
  17496. const renderTargetProperties = properties.get( renderTarget );
  17497. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17498. // We need to make sure to rebind the framebuffer.
  17499. state.bindFramebuffer( 36160, null );
  17500. useDefaultFramebuffer = false;
  17501. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17502. textures.setupRenderTarget( renderTarget );
  17503. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17504. // Color and depth texture must be rebound in order for the swapchain to update.
  17505. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17506. }
  17507. const texture = renderTarget.texture;
  17508. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17509. isRenderTarget3D = true;
  17510. }
  17511. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17512. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17513. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17514. isCube = true;
  17515. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17516. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17517. } else {
  17518. framebuffer = __webglFramebuffer;
  17519. }
  17520. _currentViewport.copy( renderTarget.viewport );
  17521. _currentScissor.copy( renderTarget.scissor );
  17522. _currentScissorTest = renderTarget.scissorTest;
  17523. } else {
  17524. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17525. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17526. _currentScissorTest = _scissorTest;
  17527. }
  17528. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  17529. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17530. state.drawBuffers( renderTarget, framebuffer );
  17531. }
  17532. state.viewport( _currentViewport );
  17533. state.scissor( _currentScissor );
  17534. state.setScissorTest( _currentScissorTest );
  17535. if ( isCube ) {
  17536. const textureProperties = properties.get( renderTarget.texture );
  17537. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17538. } else if ( isRenderTarget3D ) {
  17539. const textureProperties = properties.get( renderTarget.texture );
  17540. const layer = activeCubeFace || 0;
  17541. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17542. }
  17543. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17544. };
  17545. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17546. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17547. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17548. return;
  17549. }
  17550. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17551. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17552. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17553. }
  17554. if ( framebuffer ) {
  17555. state.bindFramebuffer( 36160, framebuffer );
  17556. try {
  17557. const texture = renderTarget.texture;
  17558. const textureFormat = texture.format;
  17559. const textureType = texture.type;
  17560. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  17561. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17562. return;
  17563. }
  17564. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17565. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  17566. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17567. ! halfFloatSupportedByExt ) {
  17568. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17569. return;
  17570. }
  17571. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17572. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17573. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17574. }
  17575. } finally {
  17576. // restore framebuffer of current render target if necessary
  17577. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17578. state.bindFramebuffer( 36160, framebuffer );
  17579. }
  17580. }
  17581. };
  17582. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17583. const levelScale = Math.pow( 2, - level );
  17584. const width = Math.floor( texture.image.width * levelScale );
  17585. const height = Math.floor( texture.image.height * levelScale );
  17586. textures.setTexture2D( texture, 0 );
  17587. _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height );
  17588. state.unbindTexture();
  17589. };
  17590. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17591. const width = srcTexture.image.width;
  17592. const height = srcTexture.image.height;
  17593. const glFormat = utils.convert( dstTexture.format );
  17594. const glType = utils.convert( dstTexture.type );
  17595. textures.setTexture2D( dstTexture, 0 );
  17596. // As another texture upload may have changed pixelStorei
  17597. // parameters, make sure they are correct for the dstTexture
  17598. _gl.pixelStorei( 37440, dstTexture.flipY );
  17599. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17600. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17601. if ( srcTexture.isDataTexture ) {
  17602. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17603. } else {
  17604. if ( srcTexture.isCompressedTexture ) {
  17605. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17606. } else {
  17607. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17608. }
  17609. }
  17610. // Generate mipmaps only when copying level 0
  17611. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  17612. state.unbindTexture();
  17613. };
  17614. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17615. if ( _this.isWebGL1Renderer ) {
  17616. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17617. return;
  17618. }
  17619. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17620. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17621. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17622. const glFormat = utils.convert( dstTexture.format );
  17623. const glType = utils.convert( dstTexture.type );
  17624. let glTarget;
  17625. if ( dstTexture.isData3DTexture ) {
  17626. textures.setTexture3D( dstTexture, 0 );
  17627. glTarget = 32879;
  17628. } else if ( dstTexture.isDataArrayTexture ) {
  17629. textures.setTexture2DArray( dstTexture, 0 );
  17630. glTarget = 35866;
  17631. } else {
  17632. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17633. return;
  17634. }
  17635. _gl.pixelStorei( 37440, dstTexture.flipY );
  17636. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17637. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17638. const unpackRowLen = _gl.getParameter( 3314 );
  17639. const unpackImageHeight = _gl.getParameter( 32878 );
  17640. const unpackSkipPixels = _gl.getParameter( 3316 );
  17641. const unpackSkipRows = _gl.getParameter( 3315 );
  17642. const unpackSkipImages = _gl.getParameter( 32877 );
  17643. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17644. _gl.pixelStorei( 3314, image.width );
  17645. _gl.pixelStorei( 32878, image.height );
  17646. _gl.pixelStorei( 3316, sourceBox.min.x );
  17647. _gl.pixelStorei( 3315, sourceBox.min.y );
  17648. _gl.pixelStorei( 32877, sourceBox.min.z );
  17649. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17650. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17651. } else {
  17652. if ( srcTexture.isCompressedArrayTexture ) {
  17653. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17654. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17655. } else {
  17656. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17657. }
  17658. }
  17659. _gl.pixelStorei( 3314, unpackRowLen );
  17660. _gl.pixelStorei( 32878, unpackImageHeight );
  17661. _gl.pixelStorei( 3316, unpackSkipPixels );
  17662. _gl.pixelStorei( 3315, unpackSkipRows );
  17663. _gl.pixelStorei( 32877, unpackSkipImages );
  17664. // Generate mipmaps only when copying level 0
  17665. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17666. state.unbindTexture();
  17667. };
  17668. this.initTexture = function ( texture ) {
  17669. if ( texture.isCubeTexture ) {
  17670. textures.setTextureCube( texture, 0 );
  17671. } else if ( texture.isData3DTexture ) {
  17672. textures.setTexture3D( texture, 0 );
  17673. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17674. textures.setTexture2DArray( texture, 0 );
  17675. } else {
  17676. textures.setTexture2D( texture, 0 );
  17677. }
  17678. state.unbindTexture();
  17679. };
  17680. this.resetState = function () {
  17681. _currentActiveCubeFace = 0;
  17682. _currentActiveMipmapLevel = 0;
  17683. _currentRenderTarget = null;
  17684. state.reset();
  17685. bindingStates.reset();
  17686. };
  17687. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17688. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17689. }
  17690. }
  17691. get physicallyCorrectLights() { // @deprecated, r150
  17692. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17693. return ! this.useLegacyLights;
  17694. }
  17695. set physicallyCorrectLights( value ) { // @deprecated, r150
  17696. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17697. this.useLegacyLights = ! value;
  17698. }
  17699. }
  17700. class WebGL1Renderer extends WebGLRenderer {}
  17701. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17702. class FogExp2 {
  17703. constructor( color, density = 0.00025 ) {
  17704. this.isFogExp2 = true;
  17705. this.name = '';
  17706. this.color = new Color( color );
  17707. this.density = density;
  17708. }
  17709. clone() {
  17710. return new FogExp2( this.color, this.density );
  17711. }
  17712. toJSON( /* meta */ ) {
  17713. return {
  17714. type: 'FogExp2',
  17715. color: this.color.getHex(),
  17716. density: this.density
  17717. };
  17718. }
  17719. }
  17720. class Fog {
  17721. constructor( color, near = 1, far = 1000 ) {
  17722. this.isFog = true;
  17723. this.name = '';
  17724. this.color = new Color( color );
  17725. this.near = near;
  17726. this.far = far;
  17727. }
  17728. clone() {
  17729. return new Fog( this.color, this.near, this.far );
  17730. }
  17731. toJSON( /* meta */ ) {
  17732. return {
  17733. type: 'Fog',
  17734. color: this.color.getHex(),
  17735. near: this.near,
  17736. far: this.far
  17737. };
  17738. }
  17739. }
  17740. class Scene extends Object3D {
  17741. constructor() {
  17742. super();
  17743. this.isScene = true;
  17744. this.type = 'Scene';
  17745. this.background = null;
  17746. this.environment = null;
  17747. this.fog = null;
  17748. this.backgroundBlurriness = 0;
  17749. this.backgroundIntensity = 1;
  17750. this.overrideMaterial = null;
  17751. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17752. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17753. }
  17754. }
  17755. copy( source, recursive ) {
  17756. super.copy( source, recursive );
  17757. if ( source.background !== null ) this.background = source.background.clone();
  17758. if ( source.environment !== null ) this.environment = source.environment.clone();
  17759. if ( source.fog !== null ) this.fog = source.fog.clone();
  17760. this.backgroundBlurriness = source.backgroundBlurriness;
  17761. this.backgroundIntensity = source.backgroundIntensity;
  17762. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17763. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17764. return this;
  17765. }
  17766. toJSON( meta ) {
  17767. const data = super.toJSON( meta );
  17768. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17769. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17770. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17771. return data;
  17772. }
  17773. get autoUpdate() { // @deprecated, r144
  17774. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17775. return this.matrixWorldAutoUpdate;
  17776. }
  17777. set autoUpdate( value ) { // @deprecated, r144
  17778. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17779. this.matrixWorldAutoUpdate = value;
  17780. }
  17781. }
  17782. class InterleavedBuffer {
  17783. constructor( array, stride ) {
  17784. this.isInterleavedBuffer = true;
  17785. this.array = array;
  17786. this.stride = stride;
  17787. this.count = array !== undefined ? array.length / stride : 0;
  17788. this.usage = StaticDrawUsage;
  17789. this.updateRange = { offset: 0, count: - 1 };
  17790. this.version = 0;
  17791. this.uuid = generateUUID();
  17792. }
  17793. onUploadCallback() {}
  17794. set needsUpdate( value ) {
  17795. if ( value === true ) this.version ++;
  17796. }
  17797. setUsage( value ) {
  17798. this.usage = value;
  17799. return this;
  17800. }
  17801. copy( source ) {
  17802. this.array = new source.array.constructor( source.array );
  17803. this.count = source.count;
  17804. this.stride = source.stride;
  17805. this.usage = source.usage;
  17806. return this;
  17807. }
  17808. copyAt( index1, attribute, index2 ) {
  17809. index1 *= this.stride;
  17810. index2 *= attribute.stride;
  17811. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17812. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17813. }
  17814. return this;
  17815. }
  17816. set( value, offset = 0 ) {
  17817. this.array.set( value, offset );
  17818. return this;
  17819. }
  17820. clone( data ) {
  17821. if ( data.arrayBuffers === undefined ) {
  17822. data.arrayBuffers = {};
  17823. }
  17824. if ( this.array.buffer._uuid === undefined ) {
  17825. this.array.buffer._uuid = generateUUID();
  17826. }
  17827. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17828. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17829. }
  17830. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17831. const ib = new this.constructor( array, this.stride );
  17832. ib.setUsage( this.usage );
  17833. return ib;
  17834. }
  17835. onUpload( callback ) {
  17836. this.onUploadCallback = callback;
  17837. return this;
  17838. }
  17839. toJSON( data ) {
  17840. if ( data.arrayBuffers === undefined ) {
  17841. data.arrayBuffers = {};
  17842. }
  17843. // generate UUID for array buffer if necessary
  17844. if ( this.array.buffer._uuid === undefined ) {
  17845. this.array.buffer._uuid = generateUUID();
  17846. }
  17847. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17848. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17849. }
  17850. //
  17851. return {
  17852. uuid: this.uuid,
  17853. buffer: this.array.buffer._uuid,
  17854. type: this.array.constructor.name,
  17855. stride: this.stride
  17856. };
  17857. }
  17858. }
  17859. const _vector$5 = /*@__PURE__*/ new Vector3();
  17860. class InterleavedBufferAttribute {
  17861. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17862. this.isInterleavedBufferAttribute = true;
  17863. this.name = '';
  17864. this.data = interleavedBuffer;
  17865. this.itemSize = itemSize;
  17866. this.offset = offset;
  17867. this.normalized = normalized;
  17868. }
  17869. get count() {
  17870. return this.data.count;
  17871. }
  17872. get array() {
  17873. return this.data.array;
  17874. }
  17875. set needsUpdate( value ) {
  17876. this.data.needsUpdate = value;
  17877. }
  17878. applyMatrix4( m ) {
  17879. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17880. _vector$5.fromBufferAttribute( this, i );
  17881. _vector$5.applyMatrix4( m );
  17882. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  17883. }
  17884. return this;
  17885. }
  17886. applyNormalMatrix( m ) {
  17887. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17888. _vector$5.fromBufferAttribute( this, i );
  17889. _vector$5.applyNormalMatrix( m );
  17890. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  17891. }
  17892. return this;
  17893. }
  17894. transformDirection( m ) {
  17895. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17896. _vector$5.fromBufferAttribute( this, i );
  17897. _vector$5.transformDirection( m );
  17898. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  17899. }
  17900. return this;
  17901. }
  17902. setX( index, x ) {
  17903. if ( this.normalized ) x = normalize( x, this.array );
  17904. this.data.array[ index * this.data.stride + this.offset ] = x;
  17905. return this;
  17906. }
  17907. setY( index, y ) {
  17908. if ( this.normalized ) y = normalize( y, this.array );
  17909. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17910. return this;
  17911. }
  17912. setZ( index, z ) {
  17913. if ( this.normalized ) z = normalize( z, this.array );
  17914. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17915. return this;
  17916. }
  17917. setW( index, w ) {
  17918. if ( this.normalized ) w = normalize( w, this.array );
  17919. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17920. return this;
  17921. }
  17922. getX( index ) {
  17923. let x = this.data.array[ index * this.data.stride + this.offset ];
  17924. if ( this.normalized ) x = denormalize( x, this.array );
  17925. return x;
  17926. }
  17927. getY( index ) {
  17928. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17929. if ( this.normalized ) y = denormalize( y, this.array );
  17930. return y;
  17931. }
  17932. getZ( index ) {
  17933. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17934. if ( this.normalized ) z = denormalize( z, this.array );
  17935. return z;
  17936. }
  17937. getW( index ) {
  17938. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17939. if ( this.normalized ) w = denormalize( w, this.array );
  17940. return w;
  17941. }
  17942. setXY( index, x, y ) {
  17943. index = index * this.data.stride + this.offset;
  17944. if ( this.normalized ) {
  17945. x = normalize( x, this.array );
  17946. y = normalize( y, this.array );
  17947. }
  17948. this.data.array[ index + 0 ] = x;
  17949. this.data.array[ index + 1 ] = y;
  17950. return this;
  17951. }
  17952. setXYZ( index, x, y, z ) {
  17953. index = index * this.data.stride + this.offset;
  17954. if ( this.normalized ) {
  17955. x = normalize( x, this.array );
  17956. y = normalize( y, this.array );
  17957. z = normalize( z, this.array );
  17958. }
  17959. this.data.array[ index + 0 ] = x;
  17960. this.data.array[ index + 1 ] = y;
  17961. this.data.array[ index + 2 ] = z;
  17962. return this;
  17963. }
  17964. setXYZW( index, x, y, z, w ) {
  17965. index = index * this.data.stride + this.offset;
  17966. if ( this.normalized ) {
  17967. x = normalize( x, this.array );
  17968. y = normalize( y, this.array );
  17969. z = normalize( z, this.array );
  17970. w = normalize( w, this.array );
  17971. }
  17972. this.data.array[ index + 0 ] = x;
  17973. this.data.array[ index + 1 ] = y;
  17974. this.data.array[ index + 2 ] = z;
  17975. this.data.array[ index + 3 ] = w;
  17976. return this;
  17977. }
  17978. clone( data ) {
  17979. if ( data === undefined ) {
  17980. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17981. const array = [];
  17982. for ( let i = 0; i < this.count; i ++ ) {
  17983. const index = i * this.data.stride + this.offset;
  17984. for ( let j = 0; j < this.itemSize; j ++ ) {
  17985. array.push( this.data.array[ index + j ] );
  17986. }
  17987. }
  17988. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17989. } else {
  17990. if ( data.interleavedBuffers === undefined ) {
  17991. data.interleavedBuffers = {};
  17992. }
  17993. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17994. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17995. }
  17996. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17997. }
  17998. }
  17999. toJSON( data ) {
  18000. if ( data === undefined ) {
  18001. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18002. const array = [];
  18003. for ( let i = 0; i < this.count; i ++ ) {
  18004. const index = i * this.data.stride + this.offset;
  18005. for ( let j = 0; j < this.itemSize; j ++ ) {
  18006. array.push( this.data.array[ index + j ] );
  18007. }
  18008. }
  18009. // de-interleave data and save it as an ordinary buffer attribute for now
  18010. return {
  18011. itemSize: this.itemSize,
  18012. type: this.array.constructor.name,
  18013. array: array,
  18014. normalized: this.normalized
  18015. };
  18016. } else {
  18017. // save as true interleaved attribute
  18018. if ( data.interleavedBuffers === undefined ) {
  18019. data.interleavedBuffers = {};
  18020. }
  18021. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18022. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18023. }
  18024. return {
  18025. isInterleavedBufferAttribute: true,
  18026. itemSize: this.itemSize,
  18027. data: this.data.uuid,
  18028. offset: this.offset,
  18029. normalized: this.normalized
  18030. };
  18031. }
  18032. }
  18033. }
  18034. class SpriteMaterial extends Material {
  18035. constructor( parameters ) {
  18036. super();
  18037. this.isSpriteMaterial = true;
  18038. this.type = 'SpriteMaterial';
  18039. this.color = new Color( 0xffffff );
  18040. this.map = null;
  18041. this.alphaMap = null;
  18042. this.rotation = 0;
  18043. this.sizeAttenuation = true;
  18044. this.transparent = true;
  18045. this.fog = true;
  18046. this.setValues( parameters );
  18047. }
  18048. copy( source ) {
  18049. super.copy( source );
  18050. this.color.copy( source.color );
  18051. this.map = source.map;
  18052. this.alphaMap = source.alphaMap;
  18053. this.rotation = source.rotation;
  18054. this.sizeAttenuation = source.sizeAttenuation;
  18055. this.fog = source.fog;
  18056. return this;
  18057. }
  18058. }
  18059. let _geometry;
  18060. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18061. const _worldScale = /*@__PURE__*/ new Vector3();
  18062. const _mvPosition = /*@__PURE__*/ new Vector3();
  18063. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18064. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18065. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18066. const _vA = /*@__PURE__*/ new Vector3();
  18067. const _vB = /*@__PURE__*/ new Vector3();
  18068. const _vC = /*@__PURE__*/ new Vector3();
  18069. const _uvA = /*@__PURE__*/ new Vector2();
  18070. const _uvB = /*@__PURE__*/ new Vector2();
  18071. const _uvC = /*@__PURE__*/ new Vector2();
  18072. class Sprite extends Object3D {
  18073. constructor( material ) {
  18074. super();
  18075. this.isSprite = true;
  18076. this.type = 'Sprite';
  18077. if ( _geometry === undefined ) {
  18078. _geometry = new BufferGeometry();
  18079. const float32Array = new Float32Array( [
  18080. - 0.5, - 0.5, 0, 0, 0,
  18081. 0.5, - 0.5, 0, 1, 0,
  18082. 0.5, 0.5, 0, 1, 1,
  18083. - 0.5, 0.5, 0, 0, 1
  18084. ] );
  18085. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18086. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18087. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18088. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18089. }
  18090. this.geometry = _geometry;
  18091. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18092. this.center = new Vector2( 0.5, 0.5 );
  18093. }
  18094. raycast( raycaster, intersects ) {
  18095. if ( raycaster.camera === null ) {
  18096. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18097. }
  18098. _worldScale.setFromMatrixScale( this.matrixWorld );
  18099. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18100. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18101. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18102. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18103. _worldScale.multiplyScalar( - _mvPosition.z );
  18104. }
  18105. const rotation = this.material.rotation;
  18106. let sin, cos;
  18107. if ( rotation !== 0 ) {
  18108. cos = Math.cos( rotation );
  18109. sin = Math.sin( rotation );
  18110. }
  18111. const center = this.center;
  18112. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18113. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18114. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18115. _uvA.set( 0, 0 );
  18116. _uvB.set( 1, 0 );
  18117. _uvC.set( 1, 1 );
  18118. // check first triangle
  18119. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18120. if ( intersect === null ) {
  18121. // check second triangle
  18122. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18123. _uvB.set( 0, 1 );
  18124. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18125. if ( intersect === null ) {
  18126. return;
  18127. }
  18128. }
  18129. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18130. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18131. intersects.push( {
  18132. distance: distance,
  18133. point: _intersectPoint.clone(),
  18134. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18135. face: null,
  18136. object: this
  18137. } );
  18138. }
  18139. copy( source, recursive ) {
  18140. super.copy( source, recursive );
  18141. if ( source.center !== undefined ) this.center.copy( source.center );
  18142. this.material = source.material;
  18143. return this;
  18144. }
  18145. }
  18146. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18147. // compute position in camera space
  18148. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18149. // to check if rotation is not zero
  18150. if ( sin !== undefined ) {
  18151. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18152. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18153. } else {
  18154. _rotatedPosition.copy( _alignedPosition );
  18155. }
  18156. vertexPosition.copy( mvPosition );
  18157. vertexPosition.x += _rotatedPosition.x;
  18158. vertexPosition.y += _rotatedPosition.y;
  18159. // transform to world space
  18160. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18161. }
  18162. const _v1$2 = /*@__PURE__*/ new Vector3();
  18163. const _v2$1 = /*@__PURE__*/ new Vector3();
  18164. class LOD extends Object3D {
  18165. constructor() {
  18166. super();
  18167. this._currentLevel = 0;
  18168. this.type = 'LOD';
  18169. Object.defineProperties( this, {
  18170. levels: {
  18171. enumerable: true,
  18172. value: []
  18173. },
  18174. isLOD: {
  18175. value: true,
  18176. }
  18177. } );
  18178. this.autoUpdate = true;
  18179. }
  18180. copy( source ) {
  18181. super.copy( source, false );
  18182. const levels = source.levels;
  18183. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18184. const level = levels[ i ];
  18185. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18186. }
  18187. this.autoUpdate = source.autoUpdate;
  18188. return this;
  18189. }
  18190. addLevel( object, distance = 0, hysteresis = 0 ) {
  18191. distance = Math.abs( distance );
  18192. const levels = this.levels;
  18193. let l;
  18194. for ( l = 0; l < levels.length; l ++ ) {
  18195. if ( distance < levels[ l ].distance ) {
  18196. break;
  18197. }
  18198. }
  18199. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18200. this.add( object );
  18201. return this;
  18202. }
  18203. getCurrentLevel() {
  18204. return this._currentLevel;
  18205. }
  18206. getObjectForDistance( distance ) {
  18207. const levels = this.levels;
  18208. if ( levels.length > 0 ) {
  18209. let i, l;
  18210. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18211. let levelDistance = levels[ i ].distance;
  18212. if ( levels[ i ].object.visible ) {
  18213. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18214. }
  18215. if ( distance < levelDistance ) {
  18216. break;
  18217. }
  18218. }
  18219. return levels[ i - 1 ].object;
  18220. }
  18221. return null;
  18222. }
  18223. raycast( raycaster, intersects ) {
  18224. const levels = this.levels;
  18225. if ( levels.length > 0 ) {
  18226. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18227. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18228. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18229. }
  18230. }
  18231. update( camera ) {
  18232. const levels = this.levels;
  18233. if ( levels.length > 1 ) {
  18234. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18235. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18236. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18237. levels[ 0 ].object.visible = true;
  18238. let i, l;
  18239. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18240. let levelDistance = levels[ i ].distance;
  18241. if ( levels[ i ].object.visible ) {
  18242. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18243. }
  18244. if ( distance >= levelDistance ) {
  18245. levels[ i - 1 ].object.visible = false;
  18246. levels[ i ].object.visible = true;
  18247. } else {
  18248. break;
  18249. }
  18250. }
  18251. this._currentLevel = i - 1;
  18252. for ( ; i < l; i ++ ) {
  18253. levels[ i ].object.visible = false;
  18254. }
  18255. }
  18256. }
  18257. toJSON( meta ) {
  18258. const data = super.toJSON( meta );
  18259. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18260. data.object.levels = [];
  18261. const levels = this.levels;
  18262. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18263. const level = levels[ i ];
  18264. data.object.levels.push( {
  18265. object: level.object.uuid,
  18266. distance: level.distance,
  18267. hysteresis: level.hysteresis
  18268. } );
  18269. }
  18270. return data;
  18271. }
  18272. }
  18273. const _basePosition = /*@__PURE__*/ new Vector3();
  18274. const _skinIndex = /*@__PURE__*/ new Vector4();
  18275. const _skinWeight = /*@__PURE__*/ new Vector4();
  18276. const _vector3 = /*@__PURE__*/ new Vector3();
  18277. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18278. const _vertex = /*@__PURE__*/ new Vector3();
  18279. class SkinnedMesh extends Mesh {
  18280. constructor( geometry, material ) {
  18281. super( geometry, material );
  18282. this.isSkinnedMesh = true;
  18283. this.type = 'SkinnedMesh';
  18284. this.bindMode = 'attached';
  18285. this.bindMatrix = new Matrix4();
  18286. this.bindMatrixInverse = new Matrix4();
  18287. this.boundingBox = null;
  18288. this.boundingSphere = null;
  18289. }
  18290. computeBoundingBox() {
  18291. const geometry = this.geometry;
  18292. if ( this.boundingBox === null ) {
  18293. this.boundingBox = new Box3();
  18294. }
  18295. this.boundingBox.makeEmpty();
  18296. const positionAttribute = geometry.getAttribute( 'position' );
  18297. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18298. _vertex.fromBufferAttribute( positionAttribute, i );
  18299. this.applyBoneTransform( i, _vertex );
  18300. this.boundingBox.expandByPoint( _vertex );
  18301. }
  18302. }
  18303. computeBoundingSphere() {
  18304. const geometry = this.geometry;
  18305. if ( this.boundingSphere === null ) {
  18306. this.boundingSphere = new Sphere();
  18307. }
  18308. this.boundingSphere.makeEmpty();
  18309. const positionAttribute = geometry.getAttribute( 'position' );
  18310. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18311. _vertex.fromBufferAttribute( positionAttribute, i );
  18312. this.applyBoneTransform( i, _vertex );
  18313. this.boundingSphere.expandByPoint( _vertex );
  18314. }
  18315. }
  18316. copy( source, recursive ) {
  18317. super.copy( source, recursive );
  18318. this.bindMode = source.bindMode;
  18319. this.bindMatrix.copy( source.bindMatrix );
  18320. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18321. this.skeleton = source.skeleton;
  18322. return this;
  18323. }
  18324. bind( skeleton, bindMatrix ) {
  18325. this.skeleton = skeleton;
  18326. if ( bindMatrix === undefined ) {
  18327. this.updateMatrixWorld( true );
  18328. this.skeleton.calculateInverses();
  18329. bindMatrix = this.matrixWorld;
  18330. }
  18331. this.bindMatrix.copy( bindMatrix );
  18332. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18333. }
  18334. pose() {
  18335. this.skeleton.pose();
  18336. }
  18337. normalizeSkinWeights() {
  18338. const vector = new Vector4();
  18339. const skinWeight = this.geometry.attributes.skinWeight;
  18340. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18341. vector.fromBufferAttribute( skinWeight, i );
  18342. const scale = 1.0 / vector.manhattanLength();
  18343. if ( scale !== Infinity ) {
  18344. vector.multiplyScalar( scale );
  18345. } else {
  18346. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18347. }
  18348. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18349. }
  18350. }
  18351. updateMatrixWorld( force ) {
  18352. super.updateMatrixWorld( force );
  18353. if ( this.bindMode === 'attached' ) {
  18354. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18355. } else if ( this.bindMode === 'detached' ) {
  18356. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18357. } else {
  18358. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18359. }
  18360. }
  18361. applyBoneTransform( index, vector ) {
  18362. const skeleton = this.skeleton;
  18363. const geometry = this.geometry;
  18364. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18365. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18366. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  18367. vector.set( 0, 0, 0 );
  18368. for ( let i = 0; i < 4; i ++ ) {
  18369. const weight = _skinWeight.getComponent( i );
  18370. if ( weight !== 0 ) {
  18371. const boneIndex = _skinIndex.getComponent( i );
  18372. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18373. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18374. }
  18375. }
  18376. return vector.applyMatrix4( this.bindMatrixInverse );
  18377. }
  18378. boneTransform( index, vector ) { // @deprecated, r151
  18379. console.warn( 'THREE.SkinnedMesh: .boneTransform() was renamed to .applyBoneTransform() in r151.' );
  18380. return this.applyBoneTransform( index, vector );
  18381. }
  18382. }
  18383. class Bone extends Object3D {
  18384. constructor() {
  18385. super();
  18386. this.isBone = true;
  18387. this.type = 'Bone';
  18388. }
  18389. }
  18390. class DataTexture extends Texture {
  18391. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  18392. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18393. this.isDataTexture = true;
  18394. this.image = { data: data, width: width, height: height };
  18395. this.generateMipmaps = false;
  18396. this.flipY = false;
  18397. this.unpackAlignment = 1;
  18398. }
  18399. }
  18400. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18401. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18402. class Skeleton {
  18403. constructor( bones = [], boneInverses = [] ) {
  18404. this.uuid = generateUUID();
  18405. this.bones = bones.slice( 0 );
  18406. this.boneInverses = boneInverses;
  18407. this.boneMatrices = null;
  18408. this.boneTexture = null;
  18409. this.boneTextureSize = 0;
  18410. this.frame = - 1;
  18411. this.init();
  18412. }
  18413. init() {
  18414. const bones = this.bones;
  18415. const boneInverses = this.boneInverses;
  18416. this.boneMatrices = new Float32Array( bones.length * 16 );
  18417. // calculate inverse bone matrices if necessary
  18418. if ( boneInverses.length === 0 ) {
  18419. this.calculateInverses();
  18420. } else {
  18421. // handle special case
  18422. if ( bones.length !== boneInverses.length ) {
  18423. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18424. this.boneInverses = [];
  18425. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18426. this.boneInverses.push( new Matrix4() );
  18427. }
  18428. }
  18429. }
  18430. }
  18431. calculateInverses() {
  18432. this.boneInverses.length = 0;
  18433. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18434. const inverse = new Matrix4();
  18435. if ( this.bones[ i ] ) {
  18436. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18437. }
  18438. this.boneInverses.push( inverse );
  18439. }
  18440. }
  18441. pose() {
  18442. // recover the bind-time world matrices
  18443. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18444. const bone = this.bones[ i ];
  18445. if ( bone ) {
  18446. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18447. }
  18448. }
  18449. // compute the local matrices, positions, rotations and scales
  18450. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18451. const bone = this.bones[ i ];
  18452. if ( bone ) {
  18453. if ( bone.parent && bone.parent.isBone ) {
  18454. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18455. bone.matrix.multiply( bone.matrixWorld );
  18456. } else {
  18457. bone.matrix.copy( bone.matrixWorld );
  18458. }
  18459. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18460. }
  18461. }
  18462. }
  18463. update() {
  18464. const bones = this.bones;
  18465. const boneInverses = this.boneInverses;
  18466. const boneMatrices = this.boneMatrices;
  18467. const boneTexture = this.boneTexture;
  18468. // flatten bone matrices to array
  18469. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18470. // compute the offset between the current and the original transform
  18471. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18472. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18473. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18474. }
  18475. if ( boneTexture !== null ) {
  18476. boneTexture.needsUpdate = true;
  18477. }
  18478. }
  18479. clone() {
  18480. return new Skeleton( this.bones, this.boneInverses );
  18481. }
  18482. computeBoneTexture() {
  18483. // layout (1 matrix = 4 pixels)
  18484. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18485. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18486. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18487. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18488. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18489. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18490. size = ceilPowerOfTwo( size );
  18491. size = Math.max( size, 4 );
  18492. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18493. boneMatrices.set( this.boneMatrices ); // copy current values
  18494. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18495. boneTexture.needsUpdate = true;
  18496. this.boneMatrices = boneMatrices;
  18497. this.boneTexture = boneTexture;
  18498. this.boneTextureSize = size;
  18499. return this;
  18500. }
  18501. getBoneByName( name ) {
  18502. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18503. const bone = this.bones[ i ];
  18504. if ( bone.name === name ) {
  18505. return bone;
  18506. }
  18507. }
  18508. return undefined;
  18509. }
  18510. dispose( ) {
  18511. if ( this.boneTexture !== null ) {
  18512. this.boneTexture.dispose();
  18513. this.boneTexture = null;
  18514. }
  18515. }
  18516. fromJSON( json, bones ) {
  18517. this.uuid = json.uuid;
  18518. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18519. const uuid = json.bones[ i ];
  18520. let bone = bones[ uuid ];
  18521. if ( bone === undefined ) {
  18522. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18523. bone = new Bone();
  18524. }
  18525. this.bones.push( bone );
  18526. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18527. }
  18528. this.init();
  18529. return this;
  18530. }
  18531. toJSON() {
  18532. const data = {
  18533. metadata: {
  18534. version: 4.5,
  18535. type: 'Skeleton',
  18536. generator: 'Skeleton.toJSON'
  18537. },
  18538. bones: [],
  18539. boneInverses: []
  18540. };
  18541. data.uuid = this.uuid;
  18542. const bones = this.bones;
  18543. const boneInverses = this.boneInverses;
  18544. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18545. const bone = bones[ i ];
  18546. data.bones.push( bone.uuid );
  18547. const boneInverse = boneInverses[ i ];
  18548. data.boneInverses.push( boneInverse.toArray() );
  18549. }
  18550. return data;
  18551. }
  18552. }
  18553. class InstancedBufferAttribute extends BufferAttribute {
  18554. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18555. super( array, itemSize, normalized );
  18556. this.isInstancedBufferAttribute = true;
  18557. this.meshPerAttribute = meshPerAttribute;
  18558. }
  18559. copy( source ) {
  18560. super.copy( source );
  18561. this.meshPerAttribute = source.meshPerAttribute;
  18562. return this;
  18563. }
  18564. toJSON() {
  18565. const data = super.toJSON();
  18566. data.meshPerAttribute = this.meshPerAttribute;
  18567. data.isInstancedBufferAttribute = true;
  18568. return data;
  18569. }
  18570. }
  18571. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18572. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18573. const _instanceIntersects = [];
  18574. const _box3 = /*@__PURE__*/ new Box3();
  18575. const _identity = /*@__PURE__*/ new Matrix4();
  18576. const _mesh = /*@__PURE__*/ new Mesh();
  18577. const _sphere$2 = /*@__PURE__*/ new Sphere();
  18578. class InstancedMesh extends Mesh {
  18579. constructor( geometry, material, count ) {
  18580. super( geometry, material );
  18581. this.isInstancedMesh = true;
  18582. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18583. this.instanceColor = null;
  18584. this.count = count;
  18585. this.boundingBox = null;
  18586. this.boundingSphere = null;
  18587. for ( let i = 0; i < count; i ++ ) {
  18588. this.setMatrixAt( i, _identity );
  18589. }
  18590. }
  18591. computeBoundingBox() {
  18592. const geometry = this.geometry;
  18593. const count = this.count;
  18594. if ( this.boundingBox === null ) {
  18595. this.boundingBox = new Box3();
  18596. }
  18597. if ( geometry.boundingBox === null ) {
  18598. geometry.computeBoundingBox();
  18599. }
  18600. this.boundingBox.makeEmpty();
  18601. for ( let i = 0; i < count; i ++ ) {
  18602. this.getMatrixAt( i, _instanceLocalMatrix );
  18603. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18604. this.boundingBox.union( _box3 );
  18605. }
  18606. }
  18607. computeBoundingSphere() {
  18608. const geometry = this.geometry;
  18609. const count = this.count;
  18610. if ( this.boundingSphere === null ) {
  18611. this.boundingSphere = new Sphere();
  18612. }
  18613. if ( geometry.boundingSphere === null ) {
  18614. geometry.computeBoundingSphere();
  18615. }
  18616. this.boundingSphere.makeEmpty();
  18617. for ( let i = 0; i < count; i ++ ) {
  18618. this.getMatrixAt( i, _instanceLocalMatrix );
  18619. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18620. this.boundingSphere.union( _sphere$2 );
  18621. }
  18622. }
  18623. copy( source, recursive ) {
  18624. super.copy( source, recursive );
  18625. this.instanceMatrix.copy( source.instanceMatrix );
  18626. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18627. this.count = source.count;
  18628. return this;
  18629. }
  18630. getColorAt( index, color ) {
  18631. color.fromArray( this.instanceColor.array, index * 3 );
  18632. }
  18633. getMatrixAt( index, matrix ) {
  18634. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18635. }
  18636. raycast( raycaster, intersects ) {
  18637. const matrixWorld = this.matrixWorld;
  18638. const raycastTimes = this.count;
  18639. _mesh.geometry = this.geometry;
  18640. _mesh.material = this.material;
  18641. if ( _mesh.material === undefined ) return;
  18642. // test with bounding sphere first
  18643. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18644. _sphere$2.copy( this.boundingSphere );
  18645. _sphere$2.applyMatrix4( matrixWorld );
  18646. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
  18647. // now test each instance
  18648. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18649. // calculate the world matrix for each instance
  18650. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18651. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18652. // the mesh represents this single instance
  18653. _mesh.matrixWorld = _instanceWorldMatrix;
  18654. _mesh.raycast( raycaster, _instanceIntersects );
  18655. // process the result of raycast
  18656. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18657. const intersect = _instanceIntersects[ i ];
  18658. intersect.instanceId = instanceId;
  18659. intersect.object = this;
  18660. intersects.push( intersect );
  18661. }
  18662. _instanceIntersects.length = 0;
  18663. }
  18664. }
  18665. setColorAt( index, color ) {
  18666. if ( this.instanceColor === null ) {
  18667. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18668. }
  18669. color.toArray( this.instanceColor.array, index * 3 );
  18670. }
  18671. setMatrixAt( index, matrix ) {
  18672. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18673. }
  18674. updateMorphTargets() {
  18675. }
  18676. dispose() {
  18677. this.dispatchEvent( { type: 'dispose' } );
  18678. }
  18679. }
  18680. class LineBasicMaterial extends Material {
  18681. constructor( parameters ) {
  18682. super();
  18683. this.isLineBasicMaterial = true;
  18684. this.type = 'LineBasicMaterial';
  18685. this.color = new Color( 0xffffff );
  18686. this.map = null;
  18687. this.linewidth = 1;
  18688. this.linecap = 'round';
  18689. this.linejoin = 'round';
  18690. this.fog = true;
  18691. this.setValues( parameters );
  18692. }
  18693. copy( source ) {
  18694. super.copy( source );
  18695. this.color.copy( source.color );
  18696. this.map = source.map;
  18697. this.linewidth = source.linewidth;
  18698. this.linecap = source.linecap;
  18699. this.linejoin = source.linejoin;
  18700. this.fog = source.fog;
  18701. return this;
  18702. }
  18703. }
  18704. const _start$1 = /*@__PURE__*/ new Vector3();
  18705. const _end$1 = /*@__PURE__*/ new Vector3();
  18706. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18707. const _ray$1 = /*@__PURE__*/ new Ray();
  18708. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18709. class Line extends Object3D {
  18710. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18711. super();
  18712. this.isLine = true;
  18713. this.type = 'Line';
  18714. this.geometry = geometry;
  18715. this.material = material;
  18716. this.updateMorphTargets();
  18717. }
  18718. copy( source, recursive ) {
  18719. super.copy( source, recursive );
  18720. this.material = source.material;
  18721. this.geometry = source.geometry;
  18722. return this;
  18723. }
  18724. computeLineDistances() {
  18725. const geometry = this.geometry;
  18726. // we assume non-indexed geometry
  18727. if ( geometry.index === null ) {
  18728. const positionAttribute = geometry.attributes.position;
  18729. const lineDistances = [ 0 ];
  18730. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18731. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18732. _end$1.fromBufferAttribute( positionAttribute, i );
  18733. lineDistances[ i ] = lineDistances[ i - 1 ];
  18734. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18735. }
  18736. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18737. } else {
  18738. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18739. }
  18740. return this;
  18741. }
  18742. raycast( raycaster, intersects ) {
  18743. const geometry = this.geometry;
  18744. const matrixWorld = this.matrixWorld;
  18745. const threshold = raycaster.params.Line.threshold;
  18746. const drawRange = geometry.drawRange;
  18747. // Checking boundingSphere distance to ray
  18748. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18749. _sphere$1.copy( geometry.boundingSphere );
  18750. _sphere$1.applyMatrix4( matrixWorld );
  18751. _sphere$1.radius += threshold;
  18752. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18753. //
  18754. _inverseMatrix$1.copy( matrixWorld ).invert();
  18755. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18756. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18757. const localThresholdSq = localThreshold * localThreshold;
  18758. const vStart = new Vector3();
  18759. const vEnd = new Vector3();
  18760. const interSegment = new Vector3();
  18761. const interRay = new Vector3();
  18762. const step = this.isLineSegments ? 2 : 1;
  18763. const index = geometry.index;
  18764. const attributes = geometry.attributes;
  18765. const positionAttribute = attributes.position;
  18766. if ( index !== null ) {
  18767. const start = Math.max( 0, drawRange.start );
  18768. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18769. for ( let i = start, l = end - 1; i < l; i += step ) {
  18770. const a = index.getX( i );
  18771. const b = index.getX( i + 1 );
  18772. vStart.fromBufferAttribute( positionAttribute, a );
  18773. vEnd.fromBufferAttribute( positionAttribute, b );
  18774. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18775. if ( distSq > localThresholdSq ) continue;
  18776. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18777. const distance = raycaster.ray.origin.distanceTo( interRay );
  18778. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18779. intersects.push( {
  18780. distance: distance,
  18781. // What do we want? intersection point on the ray or on the segment??
  18782. // point: raycaster.ray.at( distance ),
  18783. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18784. index: i,
  18785. face: null,
  18786. faceIndex: null,
  18787. object: this
  18788. } );
  18789. }
  18790. } else {
  18791. const start = Math.max( 0, drawRange.start );
  18792. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18793. for ( let i = start, l = end - 1; i < l; i += step ) {
  18794. vStart.fromBufferAttribute( positionAttribute, i );
  18795. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18796. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18797. if ( distSq > localThresholdSq ) continue;
  18798. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18799. const distance = raycaster.ray.origin.distanceTo( interRay );
  18800. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18801. intersects.push( {
  18802. distance: distance,
  18803. // What do we want? intersection point on the ray or on the segment??
  18804. // point: raycaster.ray.at( distance ),
  18805. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18806. index: i,
  18807. face: null,
  18808. faceIndex: null,
  18809. object: this
  18810. } );
  18811. }
  18812. }
  18813. }
  18814. updateMorphTargets() {
  18815. const geometry = this.geometry;
  18816. const morphAttributes = geometry.morphAttributes;
  18817. const keys = Object.keys( morphAttributes );
  18818. if ( keys.length > 0 ) {
  18819. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18820. if ( morphAttribute !== undefined ) {
  18821. this.morphTargetInfluences = [];
  18822. this.morphTargetDictionary = {};
  18823. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18824. const name = morphAttribute[ m ].name || String( m );
  18825. this.morphTargetInfluences.push( 0 );
  18826. this.morphTargetDictionary[ name ] = m;
  18827. }
  18828. }
  18829. }
  18830. }
  18831. }
  18832. const _start = /*@__PURE__*/ new Vector3();
  18833. const _end = /*@__PURE__*/ new Vector3();
  18834. class LineSegments extends Line {
  18835. constructor( geometry, material ) {
  18836. super( geometry, material );
  18837. this.isLineSegments = true;
  18838. this.type = 'LineSegments';
  18839. }
  18840. computeLineDistances() {
  18841. const geometry = this.geometry;
  18842. // we assume non-indexed geometry
  18843. if ( geometry.index === null ) {
  18844. const positionAttribute = geometry.attributes.position;
  18845. const lineDistances = [];
  18846. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18847. _start.fromBufferAttribute( positionAttribute, i );
  18848. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18849. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18850. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18851. }
  18852. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18853. } else {
  18854. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18855. }
  18856. return this;
  18857. }
  18858. }
  18859. class LineLoop extends Line {
  18860. constructor( geometry, material ) {
  18861. super( geometry, material );
  18862. this.isLineLoop = true;
  18863. this.type = 'LineLoop';
  18864. }
  18865. }
  18866. class PointsMaterial extends Material {
  18867. constructor( parameters ) {
  18868. super();
  18869. this.isPointsMaterial = true;
  18870. this.type = 'PointsMaterial';
  18871. this.color = new Color( 0xffffff );
  18872. this.map = null;
  18873. this.alphaMap = null;
  18874. this.size = 1;
  18875. this.sizeAttenuation = true;
  18876. this.fog = true;
  18877. this.setValues( parameters );
  18878. }
  18879. copy( source ) {
  18880. super.copy( source );
  18881. this.color.copy( source.color );
  18882. this.map = source.map;
  18883. this.alphaMap = source.alphaMap;
  18884. this.size = source.size;
  18885. this.sizeAttenuation = source.sizeAttenuation;
  18886. this.fog = source.fog;
  18887. return this;
  18888. }
  18889. }
  18890. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18891. const _ray = /*@__PURE__*/ new Ray();
  18892. const _sphere = /*@__PURE__*/ new Sphere();
  18893. const _position$2 = /*@__PURE__*/ new Vector3();
  18894. class Points extends Object3D {
  18895. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18896. super();
  18897. this.isPoints = true;
  18898. this.type = 'Points';
  18899. this.geometry = geometry;
  18900. this.material = material;
  18901. this.updateMorphTargets();
  18902. }
  18903. copy( source, recursive ) {
  18904. super.copy( source, recursive );
  18905. this.material = source.material;
  18906. this.geometry = source.geometry;
  18907. return this;
  18908. }
  18909. raycast( raycaster, intersects ) {
  18910. const geometry = this.geometry;
  18911. const matrixWorld = this.matrixWorld;
  18912. const threshold = raycaster.params.Points.threshold;
  18913. const drawRange = geometry.drawRange;
  18914. // Checking boundingSphere distance to ray
  18915. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18916. _sphere.copy( geometry.boundingSphere );
  18917. _sphere.applyMatrix4( matrixWorld );
  18918. _sphere.radius += threshold;
  18919. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18920. //
  18921. _inverseMatrix.copy( matrixWorld ).invert();
  18922. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18923. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18924. const localThresholdSq = localThreshold * localThreshold;
  18925. const index = geometry.index;
  18926. const attributes = geometry.attributes;
  18927. const positionAttribute = attributes.position;
  18928. if ( index !== null ) {
  18929. const start = Math.max( 0, drawRange.start );
  18930. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18931. for ( let i = start, il = end; i < il; i ++ ) {
  18932. const a = index.getX( i );
  18933. _position$2.fromBufferAttribute( positionAttribute, a );
  18934. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18935. }
  18936. } else {
  18937. const start = Math.max( 0, drawRange.start );
  18938. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18939. for ( let i = start, l = end; i < l; i ++ ) {
  18940. _position$2.fromBufferAttribute( positionAttribute, i );
  18941. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18942. }
  18943. }
  18944. }
  18945. updateMorphTargets() {
  18946. const geometry = this.geometry;
  18947. const morphAttributes = geometry.morphAttributes;
  18948. const keys = Object.keys( morphAttributes );
  18949. if ( keys.length > 0 ) {
  18950. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18951. if ( morphAttribute !== undefined ) {
  18952. this.morphTargetInfluences = [];
  18953. this.morphTargetDictionary = {};
  18954. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18955. const name = morphAttribute[ m ].name || String( m );
  18956. this.morphTargetInfluences.push( 0 );
  18957. this.morphTargetDictionary[ name ] = m;
  18958. }
  18959. }
  18960. }
  18961. }
  18962. }
  18963. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18964. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18965. if ( rayPointDistanceSq < localThresholdSq ) {
  18966. const intersectPoint = new Vector3();
  18967. _ray.closestPointToPoint( point, intersectPoint );
  18968. intersectPoint.applyMatrix4( matrixWorld );
  18969. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18970. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18971. intersects.push( {
  18972. distance: distance,
  18973. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18974. point: intersectPoint,
  18975. index: index,
  18976. face: null,
  18977. object: object
  18978. } );
  18979. }
  18980. }
  18981. class VideoTexture extends Texture {
  18982. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18983. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18984. this.isVideoTexture = true;
  18985. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18986. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18987. this.generateMipmaps = false;
  18988. const scope = this;
  18989. function updateVideo() {
  18990. scope.needsUpdate = true;
  18991. video.requestVideoFrameCallback( updateVideo );
  18992. }
  18993. if ( 'requestVideoFrameCallback' in video ) {
  18994. video.requestVideoFrameCallback( updateVideo );
  18995. }
  18996. }
  18997. clone() {
  18998. return new this.constructor( this.image ).copy( this );
  18999. }
  19000. update() {
  19001. const video = this.image;
  19002. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  19003. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  19004. this.needsUpdate = true;
  19005. }
  19006. }
  19007. }
  19008. class FramebufferTexture extends Texture {
  19009. constructor( width, height, format ) {
  19010. super( { width, height } );
  19011. this.isFramebufferTexture = true;
  19012. this.format = format;
  19013. this.magFilter = NearestFilter;
  19014. this.minFilter = NearestFilter;
  19015. this.generateMipmaps = false;
  19016. this.needsUpdate = true;
  19017. }
  19018. }
  19019. class CompressedTexture extends Texture {
  19020. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  19021. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  19022. this.isCompressedTexture = true;
  19023. this.image = { width: width, height: height };
  19024. this.mipmaps = mipmaps;
  19025. // no flipping for cube textures
  19026. // (also flipping doesn't work for compressed textures )
  19027. this.flipY = false;
  19028. // can't generate mipmaps for compressed textures
  19029. // mips must be embedded in DDS files
  19030. this.generateMipmaps = false;
  19031. }
  19032. }
  19033. class CompressedArrayTexture extends CompressedTexture {
  19034. constructor( mipmaps, width, height, depth, format, type ) {
  19035. super( mipmaps, width, height, format, type );
  19036. this.isCompressedArrayTexture = true;
  19037. this.image.depth = depth;
  19038. this.wrapR = ClampToEdgeWrapping;
  19039. }
  19040. }
  19041. class CanvasTexture extends Texture {
  19042. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19043. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19044. this.isCanvasTexture = true;
  19045. this.needsUpdate = true;
  19046. }
  19047. }
  19048. /**
  19049. * Extensible curve object.
  19050. *
  19051. * Some common of curve methods:
  19052. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  19053. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  19054. * .getPoints(), .getSpacedPoints()
  19055. * .getLength()
  19056. * .updateArcLengths()
  19057. *
  19058. * This following curves inherit from THREE.Curve:
  19059. *
  19060. * -- 2D curves --
  19061. * THREE.ArcCurve
  19062. * THREE.CubicBezierCurve
  19063. * THREE.EllipseCurve
  19064. * THREE.LineCurve
  19065. * THREE.QuadraticBezierCurve
  19066. * THREE.SplineCurve
  19067. *
  19068. * -- 3D curves --
  19069. * THREE.CatmullRomCurve3
  19070. * THREE.CubicBezierCurve3
  19071. * THREE.LineCurve3
  19072. * THREE.QuadraticBezierCurve3
  19073. *
  19074. * A series of curves can be represented as a THREE.CurvePath.
  19075. *
  19076. **/
  19077. class Curve {
  19078. constructor() {
  19079. this.type = 'Curve';
  19080. this.arcLengthDivisions = 200;
  19081. }
  19082. // Virtual base class method to overwrite and implement in subclasses
  19083. // - t [0 .. 1]
  19084. getPoint( /* t, optionalTarget */ ) {
  19085. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  19086. return null;
  19087. }
  19088. // Get point at relative position in curve according to arc length
  19089. // - u [0 .. 1]
  19090. getPointAt( u, optionalTarget ) {
  19091. const t = this.getUtoTmapping( u );
  19092. return this.getPoint( t, optionalTarget );
  19093. }
  19094. // Get sequence of points using getPoint( t )
  19095. getPoints( divisions = 5 ) {
  19096. const points = [];
  19097. for ( let d = 0; d <= divisions; d ++ ) {
  19098. points.push( this.getPoint( d / divisions ) );
  19099. }
  19100. return points;
  19101. }
  19102. // Get sequence of points using getPointAt( u )
  19103. getSpacedPoints( divisions = 5 ) {
  19104. const points = [];
  19105. for ( let d = 0; d <= divisions; d ++ ) {
  19106. points.push( this.getPointAt( d / divisions ) );
  19107. }
  19108. return points;
  19109. }
  19110. // Get total curve arc length
  19111. getLength() {
  19112. const lengths = this.getLengths();
  19113. return lengths[ lengths.length - 1 ];
  19114. }
  19115. // Get list of cumulative segment lengths
  19116. getLengths( divisions = this.arcLengthDivisions ) {
  19117. if ( this.cacheArcLengths &&
  19118. ( this.cacheArcLengths.length === divisions + 1 ) &&
  19119. ! this.needsUpdate ) {
  19120. return this.cacheArcLengths;
  19121. }
  19122. this.needsUpdate = false;
  19123. const cache = [];
  19124. let current, last = this.getPoint( 0 );
  19125. let sum = 0;
  19126. cache.push( 0 );
  19127. for ( let p = 1; p <= divisions; p ++ ) {
  19128. current = this.getPoint( p / divisions );
  19129. sum += current.distanceTo( last );
  19130. cache.push( sum );
  19131. last = current;
  19132. }
  19133. this.cacheArcLengths = cache;
  19134. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  19135. }
  19136. updateArcLengths() {
  19137. this.needsUpdate = true;
  19138. this.getLengths();
  19139. }
  19140. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19141. getUtoTmapping( u, distance ) {
  19142. const arcLengths = this.getLengths();
  19143. let i = 0;
  19144. const il = arcLengths.length;
  19145. let targetArcLength; // The targeted u distance value to get
  19146. if ( distance ) {
  19147. targetArcLength = distance;
  19148. } else {
  19149. targetArcLength = u * arcLengths[ il - 1 ];
  19150. }
  19151. // binary search for the index with largest value smaller than target u distance
  19152. let low = 0, high = il - 1, comparison;
  19153. while ( low <= high ) {
  19154. 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
  19155. comparison = arcLengths[ i ] - targetArcLength;
  19156. if ( comparison < 0 ) {
  19157. low = i + 1;
  19158. } else if ( comparison > 0 ) {
  19159. high = i - 1;
  19160. } else {
  19161. high = i;
  19162. break;
  19163. // DONE
  19164. }
  19165. }
  19166. i = high;
  19167. if ( arcLengths[ i ] === targetArcLength ) {
  19168. return i / ( il - 1 );
  19169. }
  19170. // we could get finer grain at lengths, or use simple interpolation between two points
  19171. const lengthBefore = arcLengths[ i ];
  19172. const lengthAfter = arcLengths[ i + 1 ];
  19173. const segmentLength = lengthAfter - lengthBefore;
  19174. // determine where we are between the 'before' and 'after' points
  19175. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  19176. // add that fractional amount to t
  19177. const t = ( i + segmentFraction ) / ( il - 1 );
  19178. return t;
  19179. }
  19180. // Returns a unit vector tangent at t
  19181. // In case any sub curve does not implement its tangent derivation,
  19182. // 2 points a small delta apart will be used to find its gradient
  19183. // which seems to give a reasonable approximation
  19184. getTangent( t, optionalTarget ) {
  19185. const delta = 0.0001;
  19186. let t1 = t - delta;
  19187. let t2 = t + delta;
  19188. // Capping in case of danger
  19189. if ( t1 < 0 ) t1 = 0;
  19190. if ( t2 > 1 ) t2 = 1;
  19191. const pt1 = this.getPoint( t1 );
  19192. const pt2 = this.getPoint( t2 );
  19193. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  19194. tangent.copy( pt2 ).sub( pt1 ).normalize();
  19195. return tangent;
  19196. }
  19197. getTangentAt( u, optionalTarget ) {
  19198. const t = this.getUtoTmapping( u );
  19199. return this.getTangent( t, optionalTarget );
  19200. }
  19201. computeFrenetFrames( segments, closed ) {
  19202. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19203. const normal = new Vector3();
  19204. const tangents = [];
  19205. const normals = [];
  19206. const binormals = [];
  19207. const vec = new Vector3();
  19208. const mat = new Matrix4();
  19209. // compute the tangent vectors for each segment on the curve
  19210. for ( let i = 0; i <= segments; i ++ ) {
  19211. const u = i / segments;
  19212. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  19213. }
  19214. // select an initial normal vector perpendicular to the first tangent vector,
  19215. // and in the direction of the minimum tangent xyz component
  19216. normals[ 0 ] = new Vector3();
  19217. binormals[ 0 ] = new Vector3();
  19218. let min = Number.MAX_VALUE;
  19219. const tx = Math.abs( tangents[ 0 ].x );
  19220. const ty = Math.abs( tangents[ 0 ].y );
  19221. const tz = Math.abs( tangents[ 0 ].z );
  19222. if ( tx <= min ) {
  19223. min = tx;
  19224. normal.set( 1, 0, 0 );
  19225. }
  19226. if ( ty <= min ) {
  19227. min = ty;
  19228. normal.set( 0, 1, 0 );
  19229. }
  19230. if ( tz <= min ) {
  19231. normal.set( 0, 0, 1 );
  19232. }
  19233. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19234. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19235. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19236. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  19237. for ( let i = 1; i <= segments; i ++ ) {
  19238. normals[ i ] = normals[ i - 1 ].clone();
  19239. binormals[ i ] = binormals[ i - 1 ].clone();
  19240. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19241. if ( vec.length() > Number.EPSILON ) {
  19242. vec.normalize();
  19243. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19244. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19245. }
  19246. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19247. }
  19248. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19249. if ( closed === true ) {
  19250. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  19251. theta /= segments;
  19252. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  19253. theta = - theta;
  19254. }
  19255. for ( let i = 1; i <= segments; i ++ ) {
  19256. // twist a little...
  19257. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19258. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19259. }
  19260. }
  19261. return {
  19262. tangents: tangents,
  19263. normals: normals,
  19264. binormals: binormals
  19265. };
  19266. }
  19267. clone() {
  19268. return new this.constructor().copy( this );
  19269. }
  19270. copy( source ) {
  19271. this.arcLengthDivisions = source.arcLengthDivisions;
  19272. return this;
  19273. }
  19274. toJSON() {
  19275. const data = {
  19276. metadata: {
  19277. version: 4.5,
  19278. type: 'Curve',
  19279. generator: 'Curve.toJSON'
  19280. }
  19281. };
  19282. data.arcLengthDivisions = this.arcLengthDivisions;
  19283. data.type = this.type;
  19284. return data;
  19285. }
  19286. fromJSON( json ) {
  19287. this.arcLengthDivisions = json.arcLengthDivisions;
  19288. return this;
  19289. }
  19290. }
  19291. class EllipseCurve extends Curve {
  19292. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  19293. super();
  19294. this.isEllipseCurve = true;
  19295. this.type = 'EllipseCurve';
  19296. this.aX = aX;
  19297. this.aY = aY;
  19298. this.xRadius = xRadius;
  19299. this.yRadius = yRadius;
  19300. this.aStartAngle = aStartAngle;
  19301. this.aEndAngle = aEndAngle;
  19302. this.aClockwise = aClockwise;
  19303. this.aRotation = aRotation;
  19304. }
  19305. getPoint( t, optionalTarget ) {
  19306. const point = optionalTarget || new Vector2();
  19307. const twoPi = Math.PI * 2;
  19308. let deltaAngle = this.aEndAngle - this.aStartAngle;
  19309. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  19310. // ensures that deltaAngle is 0 .. 2 PI
  19311. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  19312. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  19313. if ( deltaAngle < Number.EPSILON ) {
  19314. if ( samePoints ) {
  19315. deltaAngle = 0;
  19316. } else {
  19317. deltaAngle = twoPi;
  19318. }
  19319. }
  19320. if ( this.aClockwise === true && ! samePoints ) {
  19321. if ( deltaAngle === twoPi ) {
  19322. deltaAngle = - twoPi;
  19323. } else {
  19324. deltaAngle = deltaAngle - twoPi;
  19325. }
  19326. }
  19327. const angle = this.aStartAngle + t * deltaAngle;
  19328. let x = this.aX + this.xRadius * Math.cos( angle );
  19329. let y = this.aY + this.yRadius * Math.sin( angle );
  19330. if ( this.aRotation !== 0 ) {
  19331. const cos = Math.cos( this.aRotation );
  19332. const sin = Math.sin( this.aRotation );
  19333. const tx = x - this.aX;
  19334. const ty = y - this.aY;
  19335. // Rotate the point about the center of the ellipse.
  19336. x = tx * cos - ty * sin + this.aX;
  19337. y = tx * sin + ty * cos + this.aY;
  19338. }
  19339. return point.set( x, y );
  19340. }
  19341. copy( source ) {
  19342. super.copy( source );
  19343. this.aX = source.aX;
  19344. this.aY = source.aY;
  19345. this.xRadius = source.xRadius;
  19346. this.yRadius = source.yRadius;
  19347. this.aStartAngle = source.aStartAngle;
  19348. this.aEndAngle = source.aEndAngle;
  19349. this.aClockwise = source.aClockwise;
  19350. this.aRotation = source.aRotation;
  19351. return this;
  19352. }
  19353. toJSON() {
  19354. const data = super.toJSON();
  19355. data.aX = this.aX;
  19356. data.aY = this.aY;
  19357. data.xRadius = this.xRadius;
  19358. data.yRadius = this.yRadius;
  19359. data.aStartAngle = this.aStartAngle;
  19360. data.aEndAngle = this.aEndAngle;
  19361. data.aClockwise = this.aClockwise;
  19362. data.aRotation = this.aRotation;
  19363. return data;
  19364. }
  19365. fromJSON( json ) {
  19366. super.fromJSON( json );
  19367. this.aX = json.aX;
  19368. this.aY = json.aY;
  19369. this.xRadius = json.xRadius;
  19370. this.yRadius = json.yRadius;
  19371. this.aStartAngle = json.aStartAngle;
  19372. this.aEndAngle = json.aEndAngle;
  19373. this.aClockwise = json.aClockwise;
  19374. this.aRotation = json.aRotation;
  19375. return this;
  19376. }
  19377. }
  19378. class ArcCurve extends EllipseCurve {
  19379. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19380. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19381. this.isArcCurve = true;
  19382. this.type = 'ArcCurve';
  19383. }
  19384. }
  19385. /**
  19386. * Centripetal CatmullRom Curve - which is useful for avoiding
  19387. * cusps and self-intersections in non-uniform catmull rom curves.
  19388. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19389. *
  19390. * curve.type accepts centripetal(default), chordal and catmullrom
  19391. * curve.tension is used for catmullrom which defaults to 0.5
  19392. */
  19393. /*
  19394. Based on an optimized c++ solution in
  19395. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19396. - http://ideone.com/NoEbVM
  19397. This CubicPoly class could be used for reusing some variables and calculations,
  19398. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19399. which can be placed in CurveUtils.
  19400. */
  19401. function CubicPoly() {
  19402. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  19403. /*
  19404. * Compute coefficients for a cubic polynomial
  19405. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19406. * such that
  19407. * p(0) = x0, p(1) = x1
  19408. * and
  19409. * p'(0) = t0, p'(1) = t1.
  19410. */
  19411. function init( x0, x1, t0, t1 ) {
  19412. c0 = x0;
  19413. c1 = t0;
  19414. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19415. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19416. }
  19417. return {
  19418. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19419. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19420. },
  19421. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19422. // compute tangents when parameterized in [t1,t2]
  19423. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19424. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19425. // rescale tangents for parametrization in [0,1]
  19426. t1 *= dt1;
  19427. t2 *= dt1;
  19428. init( x1, x2, t1, t2 );
  19429. },
  19430. calc: function ( t ) {
  19431. const t2 = t * t;
  19432. const t3 = t2 * t;
  19433. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19434. }
  19435. };
  19436. }
  19437. //
  19438. const tmp = /*@__PURE__*/ new Vector3();
  19439. const px = /*@__PURE__*/ new CubicPoly();
  19440. const py = /*@__PURE__*/ new CubicPoly();
  19441. const pz = /*@__PURE__*/ new CubicPoly();
  19442. class CatmullRomCurve3 extends Curve {
  19443. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19444. super();
  19445. this.isCatmullRomCurve3 = true;
  19446. this.type = 'CatmullRomCurve3';
  19447. this.points = points;
  19448. this.closed = closed;
  19449. this.curveType = curveType;
  19450. this.tension = tension;
  19451. }
  19452. getPoint( t, optionalTarget = new Vector3() ) {
  19453. const point = optionalTarget;
  19454. const points = this.points;
  19455. const l = points.length;
  19456. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19457. let intPoint = Math.floor( p );
  19458. let weight = p - intPoint;
  19459. if ( this.closed ) {
  19460. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19461. } else if ( weight === 0 && intPoint === l - 1 ) {
  19462. intPoint = l - 2;
  19463. weight = 1;
  19464. }
  19465. let p0, p3; // 4 points (p1 & p2 defined below)
  19466. if ( this.closed || intPoint > 0 ) {
  19467. p0 = points[ ( intPoint - 1 ) % l ];
  19468. } else {
  19469. // extrapolate first point
  19470. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19471. p0 = tmp;
  19472. }
  19473. const p1 = points[ intPoint % l ];
  19474. const p2 = points[ ( intPoint + 1 ) % l ];
  19475. if ( this.closed || intPoint + 2 < l ) {
  19476. p3 = points[ ( intPoint + 2 ) % l ];
  19477. } else {
  19478. // extrapolate last point
  19479. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19480. p3 = tmp;
  19481. }
  19482. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19483. // init Centripetal / Chordal Catmull-Rom
  19484. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19485. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19486. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19487. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19488. // safety check for repeated points
  19489. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19490. if ( dt0 < 1e-4 ) dt0 = dt1;
  19491. if ( dt2 < 1e-4 ) dt2 = dt1;
  19492. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19493. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19494. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19495. } else if ( this.curveType === 'catmullrom' ) {
  19496. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19497. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19498. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19499. }
  19500. point.set(
  19501. px.calc( weight ),
  19502. py.calc( weight ),
  19503. pz.calc( weight )
  19504. );
  19505. return point;
  19506. }
  19507. copy( source ) {
  19508. super.copy( source );
  19509. this.points = [];
  19510. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19511. const point = source.points[ i ];
  19512. this.points.push( point.clone() );
  19513. }
  19514. this.closed = source.closed;
  19515. this.curveType = source.curveType;
  19516. this.tension = source.tension;
  19517. return this;
  19518. }
  19519. toJSON() {
  19520. const data = super.toJSON();
  19521. data.points = [];
  19522. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19523. const point = this.points[ i ];
  19524. data.points.push( point.toArray() );
  19525. }
  19526. data.closed = this.closed;
  19527. data.curveType = this.curveType;
  19528. data.tension = this.tension;
  19529. return data;
  19530. }
  19531. fromJSON( json ) {
  19532. super.fromJSON( json );
  19533. this.points = [];
  19534. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19535. const point = json.points[ i ];
  19536. this.points.push( new Vector3().fromArray( point ) );
  19537. }
  19538. this.closed = json.closed;
  19539. this.curveType = json.curveType;
  19540. this.tension = json.tension;
  19541. return this;
  19542. }
  19543. }
  19544. /**
  19545. * Bezier Curves formulas obtained from
  19546. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19547. */
  19548. function CatmullRom( t, p0, p1, p2, p3 ) {
  19549. const v0 = ( p2 - p0 ) * 0.5;
  19550. const v1 = ( p3 - p1 ) * 0.5;
  19551. const t2 = t * t;
  19552. const t3 = t * t2;
  19553. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19554. }
  19555. //
  19556. function QuadraticBezierP0( t, p ) {
  19557. const k = 1 - t;
  19558. return k * k * p;
  19559. }
  19560. function QuadraticBezierP1( t, p ) {
  19561. return 2 * ( 1 - t ) * t * p;
  19562. }
  19563. function QuadraticBezierP2( t, p ) {
  19564. return t * t * p;
  19565. }
  19566. function QuadraticBezier( t, p0, p1, p2 ) {
  19567. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19568. QuadraticBezierP2( t, p2 );
  19569. }
  19570. //
  19571. function CubicBezierP0( t, p ) {
  19572. const k = 1 - t;
  19573. return k * k * k * p;
  19574. }
  19575. function CubicBezierP1( t, p ) {
  19576. const k = 1 - t;
  19577. return 3 * k * k * t * p;
  19578. }
  19579. function CubicBezierP2( t, p ) {
  19580. return 3 * ( 1 - t ) * t * t * p;
  19581. }
  19582. function CubicBezierP3( t, p ) {
  19583. return t * t * t * p;
  19584. }
  19585. function CubicBezier( t, p0, p1, p2, p3 ) {
  19586. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19587. CubicBezierP3( t, p3 );
  19588. }
  19589. class CubicBezierCurve extends Curve {
  19590. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19591. super();
  19592. this.isCubicBezierCurve = true;
  19593. this.type = 'CubicBezierCurve';
  19594. this.v0 = v0;
  19595. this.v1 = v1;
  19596. this.v2 = v2;
  19597. this.v3 = v3;
  19598. }
  19599. getPoint( t, optionalTarget = new Vector2() ) {
  19600. const point = optionalTarget;
  19601. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19602. point.set(
  19603. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19604. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19605. );
  19606. return point;
  19607. }
  19608. copy( source ) {
  19609. super.copy( source );
  19610. this.v0.copy( source.v0 );
  19611. this.v1.copy( source.v1 );
  19612. this.v2.copy( source.v2 );
  19613. this.v3.copy( source.v3 );
  19614. return this;
  19615. }
  19616. toJSON() {
  19617. const data = super.toJSON();
  19618. data.v0 = this.v0.toArray();
  19619. data.v1 = this.v1.toArray();
  19620. data.v2 = this.v2.toArray();
  19621. data.v3 = this.v3.toArray();
  19622. return data;
  19623. }
  19624. fromJSON( json ) {
  19625. super.fromJSON( json );
  19626. this.v0.fromArray( json.v0 );
  19627. this.v1.fromArray( json.v1 );
  19628. this.v2.fromArray( json.v2 );
  19629. this.v3.fromArray( json.v3 );
  19630. return this;
  19631. }
  19632. }
  19633. class CubicBezierCurve3 extends Curve {
  19634. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19635. super();
  19636. this.isCubicBezierCurve3 = true;
  19637. this.type = 'CubicBezierCurve3';
  19638. this.v0 = v0;
  19639. this.v1 = v1;
  19640. this.v2 = v2;
  19641. this.v3 = v3;
  19642. }
  19643. getPoint( t, optionalTarget = new Vector3() ) {
  19644. const point = optionalTarget;
  19645. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19646. point.set(
  19647. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19648. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19649. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19650. );
  19651. return point;
  19652. }
  19653. copy( source ) {
  19654. super.copy( source );
  19655. this.v0.copy( source.v0 );
  19656. this.v1.copy( source.v1 );
  19657. this.v2.copy( source.v2 );
  19658. this.v3.copy( source.v3 );
  19659. return this;
  19660. }
  19661. toJSON() {
  19662. const data = super.toJSON();
  19663. data.v0 = this.v0.toArray();
  19664. data.v1 = this.v1.toArray();
  19665. data.v2 = this.v2.toArray();
  19666. data.v3 = this.v3.toArray();
  19667. return data;
  19668. }
  19669. fromJSON( json ) {
  19670. super.fromJSON( json );
  19671. this.v0.fromArray( json.v0 );
  19672. this.v1.fromArray( json.v1 );
  19673. this.v2.fromArray( json.v2 );
  19674. this.v3.fromArray( json.v3 );
  19675. return this;
  19676. }
  19677. }
  19678. class LineCurve extends Curve {
  19679. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19680. super();
  19681. this.isLineCurve = true;
  19682. this.type = 'LineCurve';
  19683. this.v1 = v1;
  19684. this.v2 = v2;
  19685. }
  19686. getPoint( t, optionalTarget = new Vector2() ) {
  19687. const point = optionalTarget;
  19688. if ( t === 1 ) {
  19689. point.copy( this.v2 );
  19690. } else {
  19691. point.copy( this.v2 ).sub( this.v1 );
  19692. point.multiplyScalar( t ).add( this.v1 );
  19693. }
  19694. return point;
  19695. }
  19696. // Line curve is linear, so we can overwrite default getPointAt
  19697. getPointAt( u, optionalTarget ) {
  19698. return this.getPoint( u, optionalTarget );
  19699. }
  19700. getTangent( t, optionalTarget = new Vector2() ) {
  19701. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  19702. }
  19703. getTangentAt( u, optionalTarget ) {
  19704. return this.getTangent( u, optionalTarget );
  19705. }
  19706. copy( source ) {
  19707. super.copy( source );
  19708. this.v1.copy( source.v1 );
  19709. this.v2.copy( source.v2 );
  19710. return this;
  19711. }
  19712. toJSON() {
  19713. const data = super.toJSON();
  19714. data.v1 = this.v1.toArray();
  19715. data.v2 = this.v2.toArray();
  19716. return data;
  19717. }
  19718. fromJSON( json ) {
  19719. super.fromJSON( json );
  19720. this.v1.fromArray( json.v1 );
  19721. this.v2.fromArray( json.v2 );
  19722. return this;
  19723. }
  19724. }
  19725. class LineCurve3 extends Curve {
  19726. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19727. super();
  19728. this.isLineCurve3 = true;
  19729. this.type = 'LineCurve3';
  19730. this.v1 = v1;
  19731. this.v2 = v2;
  19732. }
  19733. getPoint( t, optionalTarget = new Vector3() ) {
  19734. const point = optionalTarget;
  19735. if ( t === 1 ) {
  19736. point.copy( this.v2 );
  19737. } else {
  19738. point.copy( this.v2 ).sub( this.v1 );
  19739. point.multiplyScalar( t ).add( this.v1 );
  19740. }
  19741. return point;
  19742. }
  19743. // Line curve is linear, so we can overwrite default getPointAt
  19744. getPointAt( u, optionalTarget ) {
  19745. return this.getPoint( u, optionalTarget );
  19746. }
  19747. getTangent( t, optionalTarget = new Vector3() ) {
  19748. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  19749. }
  19750. getTangentAt( u, optionalTarget ) {
  19751. return this.getTangent( u, optionalTarget );
  19752. }
  19753. copy( source ) {
  19754. super.copy( source );
  19755. this.v1.copy( source.v1 );
  19756. this.v2.copy( source.v2 );
  19757. return this;
  19758. }
  19759. toJSON() {
  19760. const data = super.toJSON();
  19761. data.v1 = this.v1.toArray();
  19762. data.v2 = this.v2.toArray();
  19763. return data;
  19764. }
  19765. fromJSON( json ) {
  19766. super.fromJSON( json );
  19767. this.v1.fromArray( json.v1 );
  19768. this.v2.fromArray( json.v2 );
  19769. return this;
  19770. }
  19771. }
  19772. class QuadraticBezierCurve extends Curve {
  19773. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19774. super();
  19775. this.isQuadraticBezierCurve = true;
  19776. this.type = 'QuadraticBezierCurve';
  19777. this.v0 = v0;
  19778. this.v1 = v1;
  19779. this.v2 = v2;
  19780. }
  19781. getPoint( t, optionalTarget = new Vector2() ) {
  19782. const point = optionalTarget;
  19783. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19784. point.set(
  19785. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19786. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19787. );
  19788. return point;
  19789. }
  19790. copy( source ) {
  19791. super.copy( source );
  19792. this.v0.copy( source.v0 );
  19793. this.v1.copy( source.v1 );
  19794. this.v2.copy( source.v2 );
  19795. return this;
  19796. }
  19797. toJSON() {
  19798. const data = super.toJSON();
  19799. data.v0 = this.v0.toArray();
  19800. data.v1 = this.v1.toArray();
  19801. data.v2 = this.v2.toArray();
  19802. return data;
  19803. }
  19804. fromJSON( json ) {
  19805. super.fromJSON( json );
  19806. this.v0.fromArray( json.v0 );
  19807. this.v1.fromArray( json.v1 );
  19808. this.v2.fromArray( json.v2 );
  19809. return this;
  19810. }
  19811. }
  19812. class QuadraticBezierCurve3 extends Curve {
  19813. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19814. super();
  19815. this.isQuadraticBezierCurve3 = true;
  19816. this.type = 'QuadraticBezierCurve3';
  19817. this.v0 = v0;
  19818. this.v1 = v1;
  19819. this.v2 = v2;
  19820. }
  19821. getPoint( t, optionalTarget = new Vector3() ) {
  19822. const point = optionalTarget;
  19823. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19824. point.set(
  19825. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19826. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19827. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19828. );
  19829. return point;
  19830. }
  19831. copy( source ) {
  19832. super.copy( source );
  19833. this.v0.copy( source.v0 );
  19834. this.v1.copy( source.v1 );
  19835. this.v2.copy( source.v2 );
  19836. return this;
  19837. }
  19838. toJSON() {
  19839. const data = super.toJSON();
  19840. data.v0 = this.v0.toArray();
  19841. data.v1 = this.v1.toArray();
  19842. data.v2 = this.v2.toArray();
  19843. return data;
  19844. }
  19845. fromJSON( json ) {
  19846. super.fromJSON( json );
  19847. this.v0.fromArray( json.v0 );
  19848. this.v1.fromArray( json.v1 );
  19849. this.v2.fromArray( json.v2 );
  19850. return this;
  19851. }
  19852. }
  19853. class SplineCurve extends Curve {
  19854. constructor( points = [] ) {
  19855. super();
  19856. this.isSplineCurve = true;
  19857. this.type = 'SplineCurve';
  19858. this.points = points;
  19859. }
  19860. getPoint( t, optionalTarget = new Vector2() ) {
  19861. const point = optionalTarget;
  19862. const points = this.points;
  19863. const p = ( points.length - 1 ) * t;
  19864. const intPoint = Math.floor( p );
  19865. const weight = p - intPoint;
  19866. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19867. const p1 = points[ intPoint ];
  19868. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19869. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19870. point.set(
  19871. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19872. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19873. );
  19874. return point;
  19875. }
  19876. copy( source ) {
  19877. super.copy( source );
  19878. this.points = [];
  19879. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19880. const point = source.points[ i ];
  19881. this.points.push( point.clone() );
  19882. }
  19883. return this;
  19884. }
  19885. toJSON() {
  19886. const data = super.toJSON();
  19887. data.points = [];
  19888. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19889. const point = this.points[ i ];
  19890. data.points.push( point.toArray() );
  19891. }
  19892. return data;
  19893. }
  19894. fromJSON( json ) {
  19895. super.fromJSON( json );
  19896. this.points = [];
  19897. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19898. const point = json.points[ i ];
  19899. this.points.push( new Vector2().fromArray( point ) );
  19900. }
  19901. return this;
  19902. }
  19903. }
  19904. var Curves = /*#__PURE__*/Object.freeze({
  19905. __proto__: null,
  19906. ArcCurve: ArcCurve,
  19907. CatmullRomCurve3: CatmullRomCurve3,
  19908. CubicBezierCurve: CubicBezierCurve,
  19909. CubicBezierCurve3: CubicBezierCurve3,
  19910. EllipseCurve: EllipseCurve,
  19911. LineCurve: LineCurve,
  19912. LineCurve3: LineCurve3,
  19913. QuadraticBezierCurve: QuadraticBezierCurve,
  19914. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19915. SplineCurve: SplineCurve
  19916. });
  19917. /**************************************************************
  19918. * Curved Path - a curve path is simply a array of connected
  19919. * curves, but retains the api of a curve
  19920. **************************************************************/
  19921. class CurvePath extends Curve {
  19922. constructor() {
  19923. super();
  19924. this.type = 'CurvePath';
  19925. this.curves = [];
  19926. this.autoClose = false; // Automatically closes the path
  19927. }
  19928. add( curve ) {
  19929. this.curves.push( curve );
  19930. }
  19931. closePath() {
  19932. // Add a line curve if start and end of lines are not connected
  19933. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19934. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19935. if ( ! startPoint.equals( endPoint ) ) {
  19936. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19937. }
  19938. }
  19939. // To get accurate point with reference to
  19940. // entire path distance at time t,
  19941. // following has to be done:
  19942. // 1. Length of each sub path have to be known
  19943. // 2. Locate and identify type of curve
  19944. // 3. Get t for the curve
  19945. // 4. Return curve.getPointAt(t')
  19946. getPoint( t, optionalTarget ) {
  19947. const d = t * this.getLength();
  19948. const curveLengths = this.getCurveLengths();
  19949. let i = 0;
  19950. // To think about boundaries points.
  19951. while ( i < curveLengths.length ) {
  19952. if ( curveLengths[ i ] >= d ) {
  19953. const diff = curveLengths[ i ] - d;
  19954. const curve = this.curves[ i ];
  19955. const segmentLength = curve.getLength();
  19956. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19957. return curve.getPointAt( u, optionalTarget );
  19958. }
  19959. i ++;
  19960. }
  19961. return null;
  19962. // loop where sum != 0, sum > d , sum+1 <d
  19963. }
  19964. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19965. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19966. // getPoint() depends on getLength
  19967. getLength() {
  19968. const lens = this.getCurveLengths();
  19969. return lens[ lens.length - 1 ];
  19970. }
  19971. // cacheLengths must be recalculated.
  19972. updateArcLengths() {
  19973. this.needsUpdate = true;
  19974. this.cacheLengths = null;
  19975. this.getCurveLengths();
  19976. }
  19977. // Compute lengths and cache them
  19978. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19979. getCurveLengths() {
  19980. // We use cache values if curves and cache array are same length
  19981. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19982. return this.cacheLengths;
  19983. }
  19984. // Get length of sub-curve
  19985. // Push sums into cached array
  19986. const lengths = [];
  19987. let sums = 0;
  19988. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19989. sums += this.curves[ i ].getLength();
  19990. lengths.push( sums );
  19991. }
  19992. this.cacheLengths = lengths;
  19993. return lengths;
  19994. }
  19995. getSpacedPoints( divisions = 40 ) {
  19996. const points = [];
  19997. for ( let i = 0; i <= divisions; i ++ ) {
  19998. points.push( this.getPoint( i / divisions ) );
  19999. }
  20000. if ( this.autoClose ) {
  20001. points.push( points[ 0 ] );
  20002. }
  20003. return points;
  20004. }
  20005. getPoints( divisions = 12 ) {
  20006. const points = [];
  20007. let last;
  20008. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20009. const curve = curves[ i ];
  20010. const resolution = curve.isEllipseCurve ? divisions * 2
  20011. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  20012. : curve.isSplineCurve ? divisions * curve.points.length
  20013. : divisions;
  20014. const pts = curve.getPoints( resolution );
  20015. for ( let j = 0; j < pts.length; j ++ ) {
  20016. const point = pts[ j ];
  20017. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20018. points.push( point );
  20019. last = point;
  20020. }
  20021. }
  20022. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20023. points.push( points[ 0 ] );
  20024. }
  20025. return points;
  20026. }
  20027. copy( source ) {
  20028. super.copy( source );
  20029. this.curves = [];
  20030. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  20031. const curve = source.curves[ i ];
  20032. this.curves.push( curve.clone() );
  20033. }
  20034. this.autoClose = source.autoClose;
  20035. return this;
  20036. }
  20037. toJSON() {
  20038. const data = super.toJSON();
  20039. data.autoClose = this.autoClose;
  20040. data.curves = [];
  20041. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  20042. const curve = this.curves[ i ];
  20043. data.curves.push( curve.toJSON() );
  20044. }
  20045. return data;
  20046. }
  20047. fromJSON( json ) {
  20048. super.fromJSON( json );
  20049. this.autoClose = json.autoClose;
  20050. this.curves = [];
  20051. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  20052. const curve = json.curves[ i ];
  20053. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  20054. }
  20055. return this;
  20056. }
  20057. }
  20058. class Path extends CurvePath {
  20059. constructor( points ) {
  20060. super();
  20061. this.type = 'Path';
  20062. this.currentPoint = new Vector2();
  20063. if ( points ) {
  20064. this.setFromPoints( points );
  20065. }
  20066. }
  20067. setFromPoints( points ) {
  20068. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  20069. for ( let i = 1, l = points.length; i < l; i ++ ) {
  20070. this.lineTo( points[ i ].x, points[ i ].y );
  20071. }
  20072. return this;
  20073. }
  20074. moveTo( x, y ) {
  20075. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  20076. return this;
  20077. }
  20078. lineTo( x, y ) {
  20079. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  20080. this.curves.push( curve );
  20081. this.currentPoint.set( x, y );
  20082. return this;
  20083. }
  20084. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  20085. const curve = new QuadraticBezierCurve(
  20086. this.currentPoint.clone(),
  20087. new Vector2( aCPx, aCPy ),
  20088. new Vector2( aX, aY )
  20089. );
  20090. this.curves.push( curve );
  20091. this.currentPoint.set( aX, aY );
  20092. return this;
  20093. }
  20094. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20095. const curve = new CubicBezierCurve(
  20096. this.currentPoint.clone(),
  20097. new Vector2( aCP1x, aCP1y ),
  20098. new Vector2( aCP2x, aCP2y ),
  20099. new Vector2( aX, aY )
  20100. );
  20101. this.curves.push( curve );
  20102. this.currentPoint.set( aX, aY );
  20103. return this;
  20104. }
  20105. splineThru( pts /*Array of Vector*/ ) {
  20106. const npts = [ this.currentPoint.clone() ].concat( pts );
  20107. const curve = new SplineCurve( npts );
  20108. this.curves.push( curve );
  20109. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20110. return this;
  20111. }
  20112. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20113. const x0 = this.currentPoint.x;
  20114. const y0 = this.currentPoint.y;
  20115. this.absarc( aX + x0, aY + y0, aRadius,
  20116. aStartAngle, aEndAngle, aClockwise );
  20117. return this;
  20118. }
  20119. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20120. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20121. return this;
  20122. }
  20123. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20124. const x0 = this.currentPoint.x;
  20125. const y0 = this.currentPoint.y;
  20126. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20127. return this;
  20128. }
  20129. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20130. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20131. if ( this.curves.length > 0 ) {
  20132. // if a previous curve is present, attempt to join
  20133. const firstPoint = curve.getPoint( 0 );
  20134. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20135. this.lineTo( firstPoint.x, firstPoint.y );
  20136. }
  20137. }
  20138. this.curves.push( curve );
  20139. const lastPoint = curve.getPoint( 1 );
  20140. this.currentPoint.copy( lastPoint );
  20141. return this;
  20142. }
  20143. copy( source ) {
  20144. super.copy( source );
  20145. this.currentPoint.copy( source.currentPoint );
  20146. return this;
  20147. }
  20148. toJSON() {
  20149. const data = super.toJSON();
  20150. data.currentPoint = this.currentPoint.toArray();
  20151. return data;
  20152. }
  20153. fromJSON( json ) {
  20154. super.fromJSON( json );
  20155. this.currentPoint.fromArray( json.currentPoint );
  20156. return this;
  20157. }
  20158. }
  20159. class LatheGeometry extends BufferGeometry {
  20160. 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 ) {
  20161. super();
  20162. this.type = 'LatheGeometry';
  20163. this.parameters = {
  20164. points: points,
  20165. segments: segments,
  20166. phiStart: phiStart,
  20167. phiLength: phiLength
  20168. };
  20169. segments = Math.floor( segments );
  20170. // clamp phiLength so it's in range of [ 0, 2PI ]
  20171. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  20172. // buffers
  20173. const indices = [];
  20174. const vertices = [];
  20175. const uvs = [];
  20176. const initNormals = [];
  20177. const normals = [];
  20178. // helper variables
  20179. const inverseSegments = 1.0 / segments;
  20180. const vertex = new Vector3();
  20181. const uv = new Vector2();
  20182. const normal = new Vector3();
  20183. const curNormal = new Vector3();
  20184. const prevNormal = new Vector3();
  20185. let dx = 0;
  20186. let dy = 0;
  20187. // pre-compute normals for initial "meridian"
  20188. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20189. switch ( j ) {
  20190. case 0: // special handling for 1st vertex on path
  20191. dx = points[ j + 1 ].x - points[ j ].x;
  20192. dy = points[ j + 1 ].y - points[ j ].y;
  20193. normal.x = dy * 1.0;
  20194. normal.y = - dx;
  20195. normal.z = dy * 0.0;
  20196. prevNormal.copy( normal );
  20197. normal.normalize();
  20198. initNormals.push( normal.x, normal.y, normal.z );
  20199. break;
  20200. case ( points.length - 1 ): // special handling for last Vertex on path
  20201. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  20202. break;
  20203. default: // default handling for all vertices in between
  20204. dx = points[ j + 1 ].x - points[ j ].x;
  20205. dy = points[ j + 1 ].y - points[ j ].y;
  20206. normal.x = dy * 1.0;
  20207. normal.y = - dx;
  20208. normal.z = dy * 0.0;
  20209. curNormal.copy( normal );
  20210. normal.x += prevNormal.x;
  20211. normal.y += prevNormal.y;
  20212. normal.z += prevNormal.z;
  20213. normal.normalize();
  20214. initNormals.push( normal.x, normal.y, normal.z );
  20215. prevNormal.copy( curNormal );
  20216. }
  20217. }
  20218. // generate vertices, uvs and normals
  20219. for ( let i = 0; i <= segments; i ++ ) {
  20220. const phi = phiStart + i * inverseSegments * phiLength;
  20221. const sin = Math.sin( phi );
  20222. const cos = Math.cos( phi );
  20223. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20224. // vertex
  20225. vertex.x = points[ j ].x * sin;
  20226. vertex.y = points[ j ].y;
  20227. vertex.z = points[ j ].x * cos;
  20228. vertices.push( vertex.x, vertex.y, vertex.z );
  20229. // uv
  20230. uv.x = i / segments;
  20231. uv.y = j / ( points.length - 1 );
  20232. uvs.push( uv.x, uv.y );
  20233. // normal
  20234. const x = initNormals[ 3 * j + 0 ] * sin;
  20235. const y = initNormals[ 3 * j + 1 ];
  20236. const z = initNormals[ 3 * j + 0 ] * cos;
  20237. normals.push( x, y, z );
  20238. }
  20239. }
  20240. // indices
  20241. for ( let i = 0; i < segments; i ++ ) {
  20242. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  20243. const base = j + i * points.length;
  20244. const a = base;
  20245. const b = base + points.length;
  20246. const c = base + points.length + 1;
  20247. const d = base + 1;
  20248. // faces
  20249. indices.push( a, b, d );
  20250. indices.push( c, d, b );
  20251. }
  20252. }
  20253. // build geometry
  20254. this.setIndex( indices );
  20255. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20256. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20257. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20258. }
  20259. copy( source ) {
  20260. super.copy( source );
  20261. this.parameters = Object.assign( {}, source.parameters );
  20262. return this;
  20263. }
  20264. static fromJSON( data ) {
  20265. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  20266. }
  20267. }
  20268. class CapsuleGeometry extends LatheGeometry {
  20269. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  20270. const path = new Path();
  20271. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  20272. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  20273. super( path.getPoints( capSegments ), radialSegments );
  20274. this.type = 'CapsuleGeometry';
  20275. this.parameters = {
  20276. radius: radius,
  20277. height: length,
  20278. capSegments: capSegments,
  20279. radialSegments: radialSegments,
  20280. };
  20281. }
  20282. static fromJSON( data ) {
  20283. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  20284. }
  20285. }
  20286. class CircleGeometry extends BufferGeometry {
  20287. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20288. super();
  20289. this.type = 'CircleGeometry';
  20290. this.parameters = {
  20291. radius: radius,
  20292. segments: segments,
  20293. thetaStart: thetaStart,
  20294. thetaLength: thetaLength
  20295. };
  20296. segments = Math.max( 3, segments );
  20297. // buffers
  20298. const indices = [];
  20299. const vertices = [];
  20300. const normals = [];
  20301. const uvs = [];
  20302. // helper variables
  20303. const vertex = new Vector3();
  20304. const uv = new Vector2();
  20305. // center point
  20306. vertices.push( 0, 0, 0 );
  20307. normals.push( 0, 0, 1 );
  20308. uvs.push( 0.5, 0.5 );
  20309. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  20310. const segment = thetaStart + s / segments * thetaLength;
  20311. // vertex
  20312. vertex.x = radius * Math.cos( segment );
  20313. vertex.y = radius * Math.sin( segment );
  20314. vertices.push( vertex.x, vertex.y, vertex.z );
  20315. // normal
  20316. normals.push( 0, 0, 1 );
  20317. // uvs
  20318. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  20319. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  20320. uvs.push( uv.x, uv.y );
  20321. }
  20322. // indices
  20323. for ( let i = 1; i <= segments; i ++ ) {
  20324. indices.push( i, i + 1, 0 );
  20325. }
  20326. // build geometry
  20327. this.setIndex( indices );
  20328. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20329. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20330. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20331. }
  20332. copy( source ) {
  20333. super.copy( source );
  20334. this.parameters = Object.assign( {}, source.parameters );
  20335. return this;
  20336. }
  20337. static fromJSON( data ) {
  20338. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  20339. }
  20340. }
  20341. class CylinderGeometry extends BufferGeometry {
  20342. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20343. super();
  20344. this.type = 'CylinderGeometry';
  20345. this.parameters = {
  20346. radiusTop: radiusTop,
  20347. radiusBottom: radiusBottom,
  20348. height: height,
  20349. radialSegments: radialSegments,
  20350. heightSegments: heightSegments,
  20351. openEnded: openEnded,
  20352. thetaStart: thetaStart,
  20353. thetaLength: thetaLength
  20354. };
  20355. const scope = this;
  20356. radialSegments = Math.floor( radialSegments );
  20357. heightSegments = Math.floor( heightSegments );
  20358. // buffers
  20359. const indices = [];
  20360. const vertices = [];
  20361. const normals = [];
  20362. const uvs = [];
  20363. // helper variables
  20364. let index = 0;
  20365. const indexArray = [];
  20366. const halfHeight = height / 2;
  20367. let groupStart = 0;
  20368. // generate geometry
  20369. generateTorso();
  20370. if ( openEnded === false ) {
  20371. if ( radiusTop > 0 ) generateCap( true );
  20372. if ( radiusBottom > 0 ) generateCap( false );
  20373. }
  20374. // build geometry
  20375. this.setIndex( indices );
  20376. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20377. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20378. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20379. function generateTorso() {
  20380. const normal = new Vector3();
  20381. const vertex = new Vector3();
  20382. let groupCount = 0;
  20383. // this will be used to calculate the normal
  20384. const slope = ( radiusBottom - radiusTop ) / height;
  20385. // generate vertices, normals and uvs
  20386. for ( let y = 0; y <= heightSegments; y ++ ) {
  20387. const indexRow = [];
  20388. const v = y / heightSegments;
  20389. // calculate the radius of the current row
  20390. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20391. for ( let x = 0; x <= radialSegments; x ++ ) {
  20392. const u = x / radialSegments;
  20393. const theta = u * thetaLength + thetaStart;
  20394. const sinTheta = Math.sin( theta );
  20395. const cosTheta = Math.cos( theta );
  20396. // vertex
  20397. vertex.x = radius * sinTheta;
  20398. vertex.y = - v * height + halfHeight;
  20399. vertex.z = radius * cosTheta;
  20400. vertices.push( vertex.x, vertex.y, vertex.z );
  20401. // normal
  20402. normal.set( sinTheta, slope, cosTheta ).normalize();
  20403. normals.push( normal.x, normal.y, normal.z );
  20404. // uv
  20405. uvs.push( u, 1 - v );
  20406. // save index of vertex in respective row
  20407. indexRow.push( index ++ );
  20408. }
  20409. // now save vertices of the row in our index array
  20410. indexArray.push( indexRow );
  20411. }
  20412. // generate indices
  20413. for ( let x = 0; x < radialSegments; x ++ ) {
  20414. for ( let y = 0; y < heightSegments; y ++ ) {
  20415. // we use the index array to access the correct indices
  20416. const a = indexArray[ y ][ x ];
  20417. const b = indexArray[ y + 1 ][ x ];
  20418. const c = indexArray[ y + 1 ][ x + 1 ];
  20419. const d = indexArray[ y ][ x + 1 ];
  20420. // faces
  20421. indices.push( a, b, d );
  20422. indices.push( b, c, d );
  20423. // update group counter
  20424. groupCount += 6;
  20425. }
  20426. }
  20427. // add a group to the geometry. this will ensure multi material support
  20428. scope.addGroup( groupStart, groupCount, 0 );
  20429. // calculate new start value for groups
  20430. groupStart += groupCount;
  20431. }
  20432. function generateCap( top ) {
  20433. // save the index of the first center vertex
  20434. const centerIndexStart = index;
  20435. const uv = new Vector2();
  20436. const vertex = new Vector3();
  20437. let groupCount = 0;
  20438. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20439. const sign = ( top === true ) ? 1 : - 1;
  20440. // first we generate the center vertex data of the cap.
  20441. // because the geometry needs one set of uvs per face,
  20442. // we must generate a center vertex per face/segment
  20443. for ( let x = 1; x <= radialSegments; x ++ ) {
  20444. // vertex
  20445. vertices.push( 0, halfHeight * sign, 0 );
  20446. // normal
  20447. normals.push( 0, sign, 0 );
  20448. // uv
  20449. uvs.push( 0.5, 0.5 );
  20450. // increase index
  20451. index ++;
  20452. }
  20453. // save the index of the last center vertex
  20454. const centerIndexEnd = index;
  20455. // now we generate the surrounding vertices, normals and uvs
  20456. for ( let x = 0; x <= radialSegments; x ++ ) {
  20457. const u = x / radialSegments;
  20458. const theta = u * thetaLength + thetaStart;
  20459. const cosTheta = Math.cos( theta );
  20460. const sinTheta = Math.sin( theta );
  20461. // vertex
  20462. vertex.x = radius * sinTheta;
  20463. vertex.y = halfHeight * sign;
  20464. vertex.z = radius * cosTheta;
  20465. vertices.push( vertex.x, vertex.y, vertex.z );
  20466. // normal
  20467. normals.push( 0, sign, 0 );
  20468. // uv
  20469. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20470. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20471. uvs.push( uv.x, uv.y );
  20472. // increase index
  20473. index ++;
  20474. }
  20475. // generate indices
  20476. for ( let x = 0; x < radialSegments; x ++ ) {
  20477. const c = centerIndexStart + x;
  20478. const i = centerIndexEnd + x;
  20479. if ( top === true ) {
  20480. // face top
  20481. indices.push( i, i + 1, c );
  20482. } else {
  20483. // face bottom
  20484. indices.push( i + 1, i, c );
  20485. }
  20486. groupCount += 3;
  20487. }
  20488. // add a group to the geometry. this will ensure multi material support
  20489. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20490. // calculate new start value for groups
  20491. groupStart += groupCount;
  20492. }
  20493. }
  20494. copy( source ) {
  20495. super.copy( source );
  20496. this.parameters = Object.assign( {}, source.parameters );
  20497. return this;
  20498. }
  20499. static fromJSON( data ) {
  20500. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20501. }
  20502. }
  20503. class ConeGeometry extends CylinderGeometry {
  20504. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20505. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20506. this.type = 'ConeGeometry';
  20507. this.parameters = {
  20508. radius: radius,
  20509. height: height,
  20510. radialSegments: radialSegments,
  20511. heightSegments: heightSegments,
  20512. openEnded: openEnded,
  20513. thetaStart: thetaStart,
  20514. thetaLength: thetaLength
  20515. };
  20516. }
  20517. static fromJSON( data ) {
  20518. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20519. }
  20520. }
  20521. class PolyhedronGeometry extends BufferGeometry {
  20522. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20523. super();
  20524. this.type = 'PolyhedronGeometry';
  20525. this.parameters = {
  20526. vertices: vertices,
  20527. indices: indices,
  20528. radius: radius,
  20529. detail: detail
  20530. };
  20531. // default buffer data
  20532. const vertexBuffer = [];
  20533. const uvBuffer = [];
  20534. // the subdivision creates the vertex buffer data
  20535. subdivide( detail );
  20536. // all vertices should lie on a conceptual sphere with a given radius
  20537. applyRadius( radius );
  20538. // finally, create the uv data
  20539. generateUVs();
  20540. // build non-indexed geometry
  20541. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20542. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20543. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20544. if ( detail === 0 ) {
  20545. this.computeVertexNormals(); // flat normals
  20546. } else {
  20547. this.normalizeNormals(); // smooth normals
  20548. }
  20549. // helper functions
  20550. function subdivide( detail ) {
  20551. const a = new Vector3();
  20552. const b = new Vector3();
  20553. const c = new Vector3();
  20554. // iterate over all faces and apply a subdivision with the given detail value
  20555. for ( let i = 0; i < indices.length; i += 3 ) {
  20556. // get the vertices of the face
  20557. getVertexByIndex( indices[ i + 0 ], a );
  20558. getVertexByIndex( indices[ i + 1 ], b );
  20559. getVertexByIndex( indices[ i + 2 ], c );
  20560. // perform subdivision
  20561. subdivideFace( a, b, c, detail );
  20562. }
  20563. }
  20564. function subdivideFace( a, b, c, detail ) {
  20565. const cols = detail + 1;
  20566. // we use this multidimensional array as a data structure for creating the subdivision
  20567. const v = [];
  20568. // construct all of the vertices for this subdivision
  20569. for ( let i = 0; i <= cols; i ++ ) {
  20570. v[ i ] = [];
  20571. const aj = a.clone().lerp( c, i / cols );
  20572. const bj = b.clone().lerp( c, i / cols );
  20573. const rows = cols - i;
  20574. for ( let j = 0; j <= rows; j ++ ) {
  20575. if ( j === 0 && i === cols ) {
  20576. v[ i ][ j ] = aj;
  20577. } else {
  20578. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20579. }
  20580. }
  20581. }
  20582. // construct all of the faces
  20583. for ( let i = 0; i < cols; i ++ ) {
  20584. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20585. const k = Math.floor( j / 2 );
  20586. if ( j % 2 === 0 ) {
  20587. pushVertex( v[ i ][ k + 1 ] );
  20588. pushVertex( v[ i + 1 ][ k ] );
  20589. pushVertex( v[ i ][ k ] );
  20590. } else {
  20591. pushVertex( v[ i ][ k + 1 ] );
  20592. pushVertex( v[ i + 1 ][ k + 1 ] );
  20593. pushVertex( v[ i + 1 ][ k ] );
  20594. }
  20595. }
  20596. }
  20597. }
  20598. function applyRadius( radius ) {
  20599. const vertex = new Vector3();
  20600. // iterate over the entire buffer and apply the radius to each vertex
  20601. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20602. vertex.x = vertexBuffer[ i + 0 ];
  20603. vertex.y = vertexBuffer[ i + 1 ];
  20604. vertex.z = vertexBuffer[ i + 2 ];
  20605. vertex.normalize().multiplyScalar( radius );
  20606. vertexBuffer[ i + 0 ] = vertex.x;
  20607. vertexBuffer[ i + 1 ] = vertex.y;
  20608. vertexBuffer[ i + 2 ] = vertex.z;
  20609. }
  20610. }
  20611. function generateUVs() {
  20612. const vertex = new Vector3();
  20613. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20614. vertex.x = vertexBuffer[ i + 0 ];
  20615. vertex.y = vertexBuffer[ i + 1 ];
  20616. vertex.z = vertexBuffer[ i + 2 ];
  20617. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20618. const v = inclination( vertex ) / Math.PI + 0.5;
  20619. uvBuffer.push( u, 1 - v );
  20620. }
  20621. correctUVs();
  20622. correctSeam();
  20623. }
  20624. function correctSeam() {
  20625. // handle case when face straddles the seam, see #3269
  20626. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20627. // uv data of a single face
  20628. const x0 = uvBuffer[ i + 0 ];
  20629. const x1 = uvBuffer[ i + 2 ];
  20630. const x2 = uvBuffer[ i + 4 ];
  20631. const max = Math.max( x0, x1, x2 );
  20632. const min = Math.min( x0, x1, x2 );
  20633. // 0.9 is somewhat arbitrary
  20634. if ( max > 0.9 && min < 0.1 ) {
  20635. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20636. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20637. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20638. }
  20639. }
  20640. }
  20641. function pushVertex( vertex ) {
  20642. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20643. }
  20644. function getVertexByIndex( index, vertex ) {
  20645. const stride = index * 3;
  20646. vertex.x = vertices[ stride + 0 ];
  20647. vertex.y = vertices[ stride + 1 ];
  20648. vertex.z = vertices[ stride + 2 ];
  20649. }
  20650. function correctUVs() {
  20651. const a = new Vector3();
  20652. const b = new Vector3();
  20653. const c = new Vector3();
  20654. const centroid = new Vector3();
  20655. const uvA = new Vector2();
  20656. const uvB = new Vector2();
  20657. const uvC = new Vector2();
  20658. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20659. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20660. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20661. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20662. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20663. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20664. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20665. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20666. const azi = azimuth( centroid );
  20667. correctUV( uvA, j + 0, a, azi );
  20668. correctUV( uvB, j + 2, b, azi );
  20669. correctUV( uvC, j + 4, c, azi );
  20670. }
  20671. }
  20672. function correctUV( uv, stride, vector, azimuth ) {
  20673. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20674. uvBuffer[ stride ] = uv.x - 1;
  20675. }
  20676. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20677. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20678. }
  20679. }
  20680. // Angle around the Y axis, counter-clockwise when looking from above.
  20681. function azimuth( vector ) {
  20682. return Math.atan2( vector.z, - vector.x );
  20683. }
  20684. // Angle above the XZ plane.
  20685. function inclination( vector ) {
  20686. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20687. }
  20688. }
  20689. copy( source ) {
  20690. super.copy( source );
  20691. this.parameters = Object.assign( {}, source.parameters );
  20692. return this;
  20693. }
  20694. static fromJSON( data ) {
  20695. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20696. }
  20697. }
  20698. class DodecahedronGeometry extends PolyhedronGeometry {
  20699. constructor( radius = 1, detail = 0 ) {
  20700. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20701. const r = 1 / t;
  20702. const vertices = [
  20703. // (±1, ±1, ±1)
  20704. - 1, - 1, - 1, - 1, - 1, 1,
  20705. - 1, 1, - 1, - 1, 1, 1,
  20706. 1, - 1, - 1, 1, - 1, 1,
  20707. 1, 1, - 1, 1, 1, 1,
  20708. // (0, ±1/φ, ±φ)
  20709. 0, - r, - t, 0, - r, t,
  20710. 0, r, - t, 0, r, t,
  20711. // (±1/φ, ±φ, 0)
  20712. - r, - t, 0, - r, t, 0,
  20713. r, - t, 0, r, t, 0,
  20714. // (±φ, 0, ±1/φ)
  20715. - t, 0, - r, t, 0, - r,
  20716. - t, 0, r, t, 0, r
  20717. ];
  20718. const indices = [
  20719. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20720. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20721. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20722. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20723. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20724. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20725. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20726. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20727. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20728. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20729. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20730. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20731. ];
  20732. super( vertices, indices, radius, detail );
  20733. this.type = 'DodecahedronGeometry';
  20734. this.parameters = {
  20735. radius: radius,
  20736. detail: detail
  20737. };
  20738. }
  20739. static fromJSON( data ) {
  20740. return new DodecahedronGeometry( data.radius, data.detail );
  20741. }
  20742. }
  20743. const _v0 = /*@__PURE__*/ new Vector3();
  20744. const _v1$1 = /*@__PURE__*/ new Vector3();
  20745. const _normal = /*@__PURE__*/ new Vector3();
  20746. const _triangle = /*@__PURE__*/ new Triangle();
  20747. class EdgesGeometry extends BufferGeometry {
  20748. constructor( geometry = null, thresholdAngle = 1 ) {
  20749. super();
  20750. this.type = 'EdgesGeometry';
  20751. this.parameters = {
  20752. geometry: geometry,
  20753. thresholdAngle: thresholdAngle
  20754. };
  20755. if ( geometry !== null ) {
  20756. const precisionPoints = 4;
  20757. const precision = Math.pow( 10, precisionPoints );
  20758. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20759. const indexAttr = geometry.getIndex();
  20760. const positionAttr = geometry.getAttribute( 'position' );
  20761. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20762. const indexArr = [ 0, 0, 0 ];
  20763. const vertKeys = [ 'a', 'b', 'c' ];
  20764. const hashes = new Array( 3 );
  20765. const edgeData = {};
  20766. const vertices = [];
  20767. for ( let i = 0; i < indexCount; i += 3 ) {
  20768. if ( indexAttr ) {
  20769. indexArr[ 0 ] = indexAttr.getX( i );
  20770. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20771. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20772. } else {
  20773. indexArr[ 0 ] = i;
  20774. indexArr[ 1 ] = i + 1;
  20775. indexArr[ 2 ] = i + 2;
  20776. }
  20777. const { a, b, c } = _triangle;
  20778. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20779. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20780. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20781. _triangle.getNormal( _normal );
  20782. // create hashes for the edge from the vertices
  20783. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20784. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20785. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20786. // skip degenerate triangles
  20787. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20788. continue;
  20789. }
  20790. // iterate over every edge
  20791. for ( let j = 0; j < 3; j ++ ) {
  20792. // get the first and next vertex making up the edge
  20793. const jNext = ( j + 1 ) % 3;
  20794. const vecHash0 = hashes[ j ];
  20795. const vecHash1 = hashes[ jNext ];
  20796. const v0 = _triangle[ vertKeys[ j ] ];
  20797. const v1 = _triangle[ vertKeys[ jNext ] ];
  20798. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20799. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20800. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20801. // if we found a sibling edge add it into the vertex array if
  20802. // it meets the angle threshold and delete the edge from the map.
  20803. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20804. vertices.push( v0.x, v0.y, v0.z );
  20805. vertices.push( v1.x, v1.y, v1.z );
  20806. }
  20807. edgeData[ reverseHash ] = null;
  20808. } else if ( ! ( hash in edgeData ) ) {
  20809. // if we've already got an edge here then skip adding a new one
  20810. edgeData[ hash ] = {
  20811. index0: indexArr[ j ],
  20812. index1: indexArr[ jNext ],
  20813. normal: _normal.clone(),
  20814. };
  20815. }
  20816. }
  20817. }
  20818. // iterate over all remaining, unmatched edges and add them to the vertex array
  20819. for ( const key in edgeData ) {
  20820. if ( edgeData[ key ] ) {
  20821. const { index0, index1 } = edgeData[ key ];
  20822. _v0.fromBufferAttribute( positionAttr, index0 );
  20823. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20824. vertices.push( _v0.x, _v0.y, _v0.z );
  20825. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20826. }
  20827. }
  20828. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20829. }
  20830. }
  20831. copy( source ) {
  20832. super.copy( source );
  20833. this.parameters = Object.assign( {}, source.parameters );
  20834. return this;
  20835. }
  20836. }
  20837. class Shape extends Path {
  20838. constructor( points ) {
  20839. super( points );
  20840. this.uuid = generateUUID();
  20841. this.type = 'Shape';
  20842. this.holes = [];
  20843. }
  20844. getPointsHoles( divisions ) {
  20845. const holesPts = [];
  20846. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20847. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20848. }
  20849. return holesPts;
  20850. }
  20851. // get points of shape and holes (keypoints based on segments parameter)
  20852. extractPoints( divisions ) {
  20853. return {
  20854. shape: this.getPoints( divisions ),
  20855. holes: this.getPointsHoles( divisions )
  20856. };
  20857. }
  20858. copy( source ) {
  20859. super.copy( source );
  20860. this.holes = [];
  20861. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20862. const hole = source.holes[ i ];
  20863. this.holes.push( hole.clone() );
  20864. }
  20865. return this;
  20866. }
  20867. toJSON() {
  20868. const data = super.toJSON();
  20869. data.uuid = this.uuid;
  20870. data.holes = [];
  20871. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20872. const hole = this.holes[ i ];
  20873. data.holes.push( hole.toJSON() );
  20874. }
  20875. return data;
  20876. }
  20877. fromJSON( json ) {
  20878. super.fromJSON( json );
  20879. this.uuid = json.uuid;
  20880. this.holes = [];
  20881. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20882. const hole = json.holes[ i ];
  20883. this.holes.push( new Path().fromJSON( hole ) );
  20884. }
  20885. return this;
  20886. }
  20887. }
  20888. /**
  20889. * Port from https://github.com/mapbox/earcut (v2.2.4)
  20890. */
  20891. const Earcut = {
  20892. triangulate: function ( data, holeIndices, dim = 2 ) {
  20893. const hasHoles = holeIndices && holeIndices.length;
  20894. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20895. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20896. const triangles = [];
  20897. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20898. let minX, minY, maxX, maxY, x, y, invSize;
  20899. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20900. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20901. if ( data.length > 80 * dim ) {
  20902. minX = maxX = data[ 0 ];
  20903. minY = maxY = data[ 1 ];
  20904. for ( let i = dim; i < outerLen; i += dim ) {
  20905. x = data[ i ];
  20906. y = data[ i + 1 ];
  20907. if ( x < minX ) minX = x;
  20908. if ( y < minY ) minY = y;
  20909. if ( x > maxX ) maxX = x;
  20910. if ( y > maxY ) maxY = y;
  20911. }
  20912. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20913. invSize = Math.max( maxX - minX, maxY - minY );
  20914. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20915. }
  20916. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  20917. return triangles;
  20918. }
  20919. };
  20920. // create a circular doubly linked list from polygon points in the specified winding order
  20921. function linkedList( data, start, end, dim, clockwise ) {
  20922. let i, last;
  20923. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20924. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20925. } else {
  20926. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20927. }
  20928. if ( last && equals( last, last.next ) ) {
  20929. removeNode( last );
  20930. last = last.next;
  20931. }
  20932. return last;
  20933. }
  20934. // eliminate colinear or duplicate points
  20935. function filterPoints( start, end ) {
  20936. if ( ! start ) return start;
  20937. if ( ! end ) end = start;
  20938. let p = start,
  20939. again;
  20940. do {
  20941. again = false;
  20942. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20943. removeNode( p );
  20944. p = end = p.prev;
  20945. if ( p === p.next ) break;
  20946. again = true;
  20947. } else {
  20948. p = p.next;
  20949. }
  20950. } while ( again || p !== end );
  20951. return end;
  20952. }
  20953. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20954. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20955. if ( ! ear ) return;
  20956. // interlink polygon nodes in z-order
  20957. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20958. let stop = ear,
  20959. prev, next;
  20960. // iterate through ears, slicing them one by one
  20961. while ( ear.prev !== ear.next ) {
  20962. prev = ear.prev;
  20963. next = ear.next;
  20964. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20965. // cut off the triangle
  20966. triangles.push( prev.i / dim | 0 );
  20967. triangles.push( ear.i / dim | 0 );
  20968. triangles.push( next.i / dim | 0 );
  20969. removeNode( ear );
  20970. // skipping the next vertex leads to less sliver triangles
  20971. ear = next.next;
  20972. stop = next.next;
  20973. continue;
  20974. }
  20975. ear = next;
  20976. // if we looped through the whole remaining polygon and can't find any more ears
  20977. if ( ear === stop ) {
  20978. // try filtering points and slicing again
  20979. if ( ! pass ) {
  20980. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20981. // if this didn't work, try curing all small self-intersections locally
  20982. } else if ( pass === 1 ) {
  20983. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20984. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20985. // as a last resort, try splitting the remaining polygon into two
  20986. } else if ( pass === 2 ) {
  20987. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20988. }
  20989. break;
  20990. }
  20991. }
  20992. }
  20993. // check whether a polygon node forms a valid ear with adjacent nodes
  20994. function isEar( ear ) {
  20995. const a = ear.prev,
  20996. b = ear,
  20997. c = ear.next;
  20998. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20999. // now make sure we don't have other points inside the potential ear
  21000. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  21001. // triangle bbox; min & max are calculated like this for speed
  21002. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  21003. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  21004. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  21005. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  21006. let p = c.next;
  21007. while ( p !== a ) {
  21008. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  21009. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  21010. area( p.prev, p, p.next ) >= 0 ) return false;
  21011. p = p.next;
  21012. }
  21013. return true;
  21014. }
  21015. function isEarHashed( ear, minX, minY, invSize ) {
  21016. const a = ear.prev,
  21017. b = ear,
  21018. c = ear.next;
  21019. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21020. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  21021. // triangle bbox; min & max are calculated like this for speed
  21022. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  21023. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  21024. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  21025. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  21026. // z-order range for the current triangle bbox;
  21027. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  21028. maxZ = zOrder( x1, y1, minX, minY, invSize );
  21029. let p = ear.prevZ,
  21030. n = ear.nextZ;
  21031. // look for points inside the triangle in both directions
  21032. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  21033. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  21034. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  21035. p = p.prevZ;
  21036. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  21037. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  21038. n = n.nextZ;
  21039. }
  21040. // look for remaining points in decreasing z-order
  21041. while ( p && p.z >= minZ ) {
  21042. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  21043. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  21044. p = p.prevZ;
  21045. }
  21046. // look for remaining points in increasing z-order
  21047. while ( n && n.z <= maxZ ) {
  21048. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  21049. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  21050. n = n.nextZ;
  21051. }
  21052. return true;
  21053. }
  21054. // go through all polygon nodes and cure small local self-intersections
  21055. function cureLocalIntersections( start, triangles, dim ) {
  21056. let p = start;
  21057. do {
  21058. const a = p.prev,
  21059. b = p.next.next;
  21060. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  21061. triangles.push( a.i / dim | 0 );
  21062. triangles.push( p.i / dim | 0 );
  21063. triangles.push( b.i / dim | 0 );
  21064. // remove two nodes involved
  21065. removeNode( p );
  21066. removeNode( p.next );
  21067. p = start = b;
  21068. }
  21069. p = p.next;
  21070. } while ( p !== start );
  21071. return filterPoints( p );
  21072. }
  21073. // try splitting polygon into two and triangulate them independently
  21074. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  21075. // look for a valid diagonal that divides the polygon into two
  21076. let a = start;
  21077. do {
  21078. let b = a.next.next;
  21079. while ( b !== a.prev ) {
  21080. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  21081. // split the polygon in two by the diagonal
  21082. let c = splitPolygon( a, b );
  21083. // filter colinear points around the cuts
  21084. a = filterPoints( a, a.next );
  21085. c = filterPoints( c, c.next );
  21086. // run earcut on each half
  21087. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  21088. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  21089. return;
  21090. }
  21091. b = b.next;
  21092. }
  21093. a = a.next;
  21094. } while ( a !== start );
  21095. }
  21096. // link every hole into the outer loop, producing a single-ring polygon without holes
  21097. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  21098. const queue = [];
  21099. let i, len, start, end, list;
  21100. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  21101. start = holeIndices[ i ] * dim;
  21102. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  21103. list = linkedList( data, start, end, dim, false );
  21104. if ( list === list.next ) list.steiner = true;
  21105. queue.push( getLeftmost( list ) );
  21106. }
  21107. queue.sort( compareX );
  21108. // process holes from left to right
  21109. for ( i = 0; i < queue.length; i ++ ) {
  21110. outerNode = eliminateHole( queue[ i ], outerNode );
  21111. }
  21112. return outerNode;
  21113. }
  21114. function compareX( a, b ) {
  21115. return a.x - b.x;
  21116. }
  21117. // find a bridge between vertices that connects hole with an outer ring and link it
  21118. function eliminateHole( hole, outerNode ) {
  21119. const bridge = findHoleBridge( hole, outerNode );
  21120. if ( ! bridge ) {
  21121. return outerNode;
  21122. }
  21123. const bridgeReverse = splitPolygon( bridge, hole );
  21124. // filter collinear points around the cuts
  21125. filterPoints( bridgeReverse, bridgeReverse.next );
  21126. return filterPoints( bridge, bridge.next );
  21127. }
  21128. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  21129. function findHoleBridge( hole, outerNode ) {
  21130. let p = outerNode,
  21131. qx = - Infinity,
  21132. m;
  21133. const hx = hole.x, hy = hole.y;
  21134. // find a segment intersected by a ray from the hole's leftmost point to the left;
  21135. // segment's endpoint with lesser x will be potential connection point
  21136. do {
  21137. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  21138. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  21139. if ( x <= hx && x > qx ) {
  21140. qx = x;
  21141. m = p.x < p.next.x ? p : p.next;
  21142. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  21143. }
  21144. }
  21145. p = p.next;
  21146. } while ( p !== outerNode );
  21147. if ( ! m ) return null;
  21148. // look for points inside the triangle of hole point, segment intersection and endpoint;
  21149. // if there are no points found, we have a valid connection;
  21150. // otherwise choose the point of the minimum angle with the ray as connection point
  21151. const stop = m,
  21152. mx = m.x,
  21153. my = m.y;
  21154. let tanMin = Infinity, tan;
  21155. p = m;
  21156. do {
  21157. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  21158. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  21159. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  21160. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  21161. m = p;
  21162. tanMin = tan;
  21163. }
  21164. }
  21165. p = p.next;
  21166. } while ( p !== stop );
  21167. return m;
  21168. }
  21169. // whether sector in vertex m contains sector in vertex p in the same coordinates
  21170. function sectorContainsSector( m, p ) {
  21171. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  21172. }
  21173. // interlink polygon nodes in z-order
  21174. function indexCurve( start, minX, minY, invSize ) {
  21175. let p = start;
  21176. do {
  21177. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  21178. p.prevZ = p.prev;
  21179. p.nextZ = p.next;
  21180. p = p.next;
  21181. } while ( p !== start );
  21182. p.prevZ.nextZ = null;
  21183. p.prevZ = null;
  21184. sortLinked( p );
  21185. }
  21186. // Simon Tatham's linked list merge sort algorithm
  21187. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  21188. function sortLinked( list ) {
  21189. let i, p, q, e, tail, numMerges, pSize, qSize,
  21190. inSize = 1;
  21191. do {
  21192. p = list;
  21193. list = null;
  21194. tail = null;
  21195. numMerges = 0;
  21196. while ( p ) {
  21197. numMerges ++;
  21198. q = p;
  21199. pSize = 0;
  21200. for ( i = 0; i < inSize; i ++ ) {
  21201. pSize ++;
  21202. q = q.nextZ;
  21203. if ( ! q ) break;
  21204. }
  21205. qSize = inSize;
  21206. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  21207. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  21208. e = p;
  21209. p = p.nextZ;
  21210. pSize --;
  21211. } else {
  21212. e = q;
  21213. q = q.nextZ;
  21214. qSize --;
  21215. }
  21216. if ( tail ) tail.nextZ = e;
  21217. else list = e;
  21218. e.prevZ = tail;
  21219. tail = e;
  21220. }
  21221. p = q;
  21222. }
  21223. tail.nextZ = null;
  21224. inSize *= 2;
  21225. } while ( numMerges > 1 );
  21226. return list;
  21227. }
  21228. // z-order of a point given coords and inverse of the longer side of data bbox
  21229. function zOrder( x, y, minX, minY, invSize ) {
  21230. // coords are transformed into non-negative 15-bit integer range
  21231. x = ( x - minX ) * invSize | 0;
  21232. y = ( y - minY ) * invSize | 0;
  21233. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  21234. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  21235. x = ( x | ( x << 2 ) ) & 0x33333333;
  21236. x = ( x | ( x << 1 ) ) & 0x55555555;
  21237. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  21238. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  21239. y = ( y | ( y << 2 ) ) & 0x33333333;
  21240. y = ( y | ( y << 1 ) ) & 0x55555555;
  21241. return x | ( y << 1 );
  21242. }
  21243. // find the leftmost node of a polygon ring
  21244. function getLeftmost( start ) {
  21245. let p = start,
  21246. leftmost = start;
  21247. do {
  21248. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  21249. p = p.next;
  21250. } while ( p !== start );
  21251. return leftmost;
  21252. }
  21253. // check if a point lies within a convex triangle
  21254. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  21255. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  21256. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  21257. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  21258. }
  21259. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  21260. function isValidDiagonal( a, b ) {
  21261. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  21262. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  21263. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  21264. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  21265. }
  21266. // signed area of a triangle
  21267. function area( p, q, r ) {
  21268. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  21269. }
  21270. // check if two points are equal
  21271. function equals( p1, p2 ) {
  21272. return p1.x === p2.x && p1.y === p2.y;
  21273. }
  21274. // check if two segments intersect
  21275. function intersects( p1, q1, p2, q2 ) {
  21276. const o1 = sign( area( p1, q1, p2 ) );
  21277. const o2 = sign( area( p1, q1, q2 ) );
  21278. const o3 = sign( area( p2, q2, p1 ) );
  21279. const o4 = sign( area( p2, q2, q1 ) );
  21280. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  21281. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  21282. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  21283. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  21284. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  21285. return false;
  21286. }
  21287. // for collinear points p, q, r, check if point q lies on segment pr
  21288. function onSegment( p, q, r ) {
  21289. 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 );
  21290. }
  21291. function sign( num ) {
  21292. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  21293. }
  21294. // check if a polygon diagonal intersects any polygon segments
  21295. function intersectsPolygon( a, b ) {
  21296. let p = a;
  21297. do {
  21298. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  21299. intersects( p, p.next, a, b ) ) return true;
  21300. p = p.next;
  21301. } while ( p !== a );
  21302. return false;
  21303. }
  21304. // check if a polygon diagonal is locally inside the polygon
  21305. function locallyInside( a, b ) {
  21306. return area( a.prev, a, a.next ) < 0 ?
  21307. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  21308. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  21309. }
  21310. // check if the middle point of a polygon diagonal is inside the polygon
  21311. function middleInside( a, b ) {
  21312. let p = a,
  21313. inside = false;
  21314. const px = ( a.x + b.x ) / 2,
  21315. py = ( a.y + b.y ) / 2;
  21316. do {
  21317. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  21318. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  21319. inside = ! inside;
  21320. p = p.next;
  21321. } while ( p !== a );
  21322. return inside;
  21323. }
  21324. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  21325. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  21326. function splitPolygon( a, b ) {
  21327. const a2 = new Node( a.i, a.x, a.y ),
  21328. b2 = new Node( b.i, b.x, b.y ),
  21329. an = a.next,
  21330. bp = b.prev;
  21331. a.next = b;
  21332. b.prev = a;
  21333. a2.next = an;
  21334. an.prev = a2;
  21335. b2.next = a2;
  21336. a2.prev = b2;
  21337. bp.next = b2;
  21338. b2.prev = bp;
  21339. return b2;
  21340. }
  21341. // create a node and optionally link it with previous one (in a circular doubly linked list)
  21342. function insertNode( i, x, y, last ) {
  21343. const p = new Node( i, x, y );
  21344. if ( ! last ) {
  21345. p.prev = p;
  21346. p.next = p;
  21347. } else {
  21348. p.next = last.next;
  21349. p.prev = last;
  21350. last.next.prev = p;
  21351. last.next = p;
  21352. }
  21353. return p;
  21354. }
  21355. function removeNode( p ) {
  21356. p.next.prev = p.prev;
  21357. p.prev.next = p.next;
  21358. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  21359. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  21360. }
  21361. function Node( i, x, y ) {
  21362. // vertex index in coordinates array
  21363. this.i = i;
  21364. // vertex coordinates
  21365. this.x = x;
  21366. this.y = y;
  21367. // previous and next vertex nodes in a polygon ring
  21368. this.prev = null;
  21369. this.next = null;
  21370. // z-order curve value
  21371. this.z = 0;
  21372. // previous and next nodes in z-order
  21373. this.prevZ = null;
  21374. this.nextZ = null;
  21375. // indicates whether this is a steiner point
  21376. this.steiner = false;
  21377. }
  21378. function signedArea( data, start, end, dim ) {
  21379. let sum = 0;
  21380. for ( let i = start, j = end - dim; i < end; i += dim ) {
  21381. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  21382. j = i;
  21383. }
  21384. return sum;
  21385. }
  21386. class ShapeUtils {
  21387. // calculate area of the contour polygon
  21388. static area( contour ) {
  21389. const n = contour.length;
  21390. let a = 0.0;
  21391. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  21392. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  21393. }
  21394. return a * 0.5;
  21395. }
  21396. static isClockWise( pts ) {
  21397. return ShapeUtils.area( pts ) < 0;
  21398. }
  21399. static triangulateShape( contour, holes ) {
  21400. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  21401. const holeIndices = []; // array of hole indices
  21402. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  21403. removeDupEndPts( contour );
  21404. addContour( vertices, contour );
  21405. //
  21406. let holeIndex = contour.length;
  21407. holes.forEach( removeDupEndPts );
  21408. for ( let i = 0; i < holes.length; i ++ ) {
  21409. holeIndices.push( holeIndex );
  21410. holeIndex += holes[ i ].length;
  21411. addContour( vertices, holes[ i ] );
  21412. }
  21413. //
  21414. const triangles = Earcut.triangulate( vertices, holeIndices );
  21415. //
  21416. for ( let i = 0; i < triangles.length; i += 3 ) {
  21417. faces.push( triangles.slice( i, i + 3 ) );
  21418. }
  21419. return faces;
  21420. }
  21421. }
  21422. function removeDupEndPts( points ) {
  21423. const l = points.length;
  21424. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  21425. points.pop();
  21426. }
  21427. }
  21428. function addContour( vertices, contour ) {
  21429. for ( let i = 0; i < contour.length; i ++ ) {
  21430. vertices.push( contour[ i ].x );
  21431. vertices.push( contour[ i ].y );
  21432. }
  21433. }
  21434. /**
  21435. * Creates extruded geometry from a path shape.
  21436. *
  21437. * parameters = {
  21438. *
  21439. * curveSegments: <int>, // number of points on the curves
  21440. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21441. * depth: <float>, // Depth to extrude the shape
  21442. *
  21443. * bevelEnabled: <bool>, // turn on bevel
  21444. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21445. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21446. * bevelOffset: <float>, // how far from shape outline does bevel start
  21447. * bevelSegments: <int>, // number of bevel layers
  21448. *
  21449. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21450. *
  21451. * UVGenerator: <Object> // object that provides UV generator functions
  21452. *
  21453. * }
  21454. */
  21455. class ExtrudeGeometry extends BufferGeometry {
  21456. 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 = {} ) {
  21457. super();
  21458. this.type = 'ExtrudeGeometry';
  21459. this.parameters = {
  21460. shapes: shapes,
  21461. options: options
  21462. };
  21463. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21464. const scope = this;
  21465. const verticesArray = [];
  21466. const uvArray = [];
  21467. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21468. const shape = shapes[ i ];
  21469. addShape( shape );
  21470. }
  21471. // build geometry
  21472. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21473. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21474. this.computeVertexNormals();
  21475. // functions
  21476. function addShape( shape ) {
  21477. const placeholder = [];
  21478. // options
  21479. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21480. const steps = options.steps !== undefined ? options.steps : 1;
  21481. const depth = options.depth !== undefined ? options.depth : 1;
  21482. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21483. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21484. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21485. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21486. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21487. const extrudePath = options.extrudePath;
  21488. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21489. //
  21490. let extrudePts, extrudeByPath = false;
  21491. let splineTube, binormal, normal, position2;
  21492. if ( extrudePath ) {
  21493. extrudePts = extrudePath.getSpacedPoints( steps );
  21494. extrudeByPath = true;
  21495. bevelEnabled = false; // bevels not supported for path extrusion
  21496. // SETUP TNB variables
  21497. // TODO1 - have a .isClosed in spline?
  21498. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21499. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21500. binormal = new Vector3();
  21501. normal = new Vector3();
  21502. position2 = new Vector3();
  21503. }
  21504. // Safeguards if bevels are not enabled
  21505. if ( ! bevelEnabled ) {
  21506. bevelSegments = 0;
  21507. bevelThickness = 0;
  21508. bevelSize = 0;
  21509. bevelOffset = 0;
  21510. }
  21511. // Variables initialization
  21512. const shapePoints = shape.extractPoints( curveSegments );
  21513. let vertices = shapePoints.shape;
  21514. const holes = shapePoints.holes;
  21515. const reverse = ! ShapeUtils.isClockWise( vertices );
  21516. if ( reverse ) {
  21517. vertices = vertices.reverse();
  21518. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21519. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21520. const ahole = holes[ h ];
  21521. if ( ShapeUtils.isClockWise( ahole ) ) {
  21522. holes[ h ] = ahole.reverse();
  21523. }
  21524. }
  21525. }
  21526. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21527. /* Vertices */
  21528. const contour = vertices; // vertices has all points but contour has only points of circumference
  21529. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21530. const ahole = holes[ h ];
  21531. vertices = vertices.concat( ahole );
  21532. }
  21533. function scalePt2( pt, vec, size ) {
  21534. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21535. return pt.clone().addScaledVector( vec, size );
  21536. }
  21537. const vlen = vertices.length, flen = faces.length;
  21538. // Find directions for point movement
  21539. function getBevelVec( inPt, inPrev, inNext ) {
  21540. // computes for inPt the corresponding point inPt' on a new contour
  21541. // shifted by 1 unit (length of normalized vector) to the left
  21542. // if we walk along contour clockwise, this new contour is outside the old one
  21543. //
  21544. // inPt' is the intersection of the two lines parallel to the two
  21545. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21546. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21547. // good reading for geometry algorithms (here: line-line intersection)
  21548. // http://geomalgorithms.com/a05-_intersect-1.html
  21549. const v_prev_x = inPt.x - inPrev.x,
  21550. v_prev_y = inPt.y - inPrev.y;
  21551. const v_next_x = inNext.x - inPt.x,
  21552. v_next_y = inNext.y - inPt.y;
  21553. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21554. // check for collinear edges
  21555. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21556. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21557. // not collinear
  21558. // length of vectors for normalizing
  21559. const v_prev_len = Math.sqrt( v_prev_lensq );
  21560. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21561. // shift adjacent points by unit vectors to the left
  21562. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21563. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21564. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21565. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21566. // scaling factor for v_prev to intersection point
  21567. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21568. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21569. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21570. // vector from inPt to intersection point
  21571. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21572. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21573. // Don't normalize!, otherwise sharp corners become ugly
  21574. // but prevent crazy spikes
  21575. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21576. if ( v_trans_lensq <= 2 ) {
  21577. return new Vector2( v_trans_x, v_trans_y );
  21578. } else {
  21579. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21580. }
  21581. } else {
  21582. // handle special case of collinear edges
  21583. let direction_eq = false; // assumes: opposite
  21584. if ( v_prev_x > Number.EPSILON ) {
  21585. if ( v_next_x > Number.EPSILON ) {
  21586. direction_eq = true;
  21587. }
  21588. } else {
  21589. if ( v_prev_x < - Number.EPSILON ) {
  21590. if ( v_next_x < - Number.EPSILON ) {
  21591. direction_eq = true;
  21592. }
  21593. } else {
  21594. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21595. direction_eq = true;
  21596. }
  21597. }
  21598. }
  21599. if ( direction_eq ) {
  21600. // console.log("Warning: lines are a straight sequence");
  21601. v_trans_x = - v_prev_y;
  21602. v_trans_y = v_prev_x;
  21603. shrink_by = Math.sqrt( v_prev_lensq );
  21604. } else {
  21605. // console.log("Warning: lines are a straight spike");
  21606. v_trans_x = v_prev_x;
  21607. v_trans_y = v_prev_y;
  21608. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21609. }
  21610. }
  21611. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21612. }
  21613. const contourMovements = [];
  21614. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21615. if ( j === il ) j = 0;
  21616. if ( k === il ) k = 0;
  21617. // (j)---(i)---(k)
  21618. // console.log('i,j,k', i, j , k)
  21619. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21620. }
  21621. const holesMovements = [];
  21622. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21623. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21624. const ahole = holes[ h ];
  21625. oneHoleMovements = [];
  21626. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21627. if ( j === il ) j = 0;
  21628. if ( k === il ) k = 0;
  21629. // (j)---(i)---(k)
  21630. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21631. }
  21632. holesMovements.push( oneHoleMovements );
  21633. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21634. }
  21635. // Loop bevelSegments, 1 for the front, 1 for the back
  21636. for ( let b = 0; b < bevelSegments; b ++ ) {
  21637. //for ( b = bevelSegments; b > 0; b -- ) {
  21638. const t = b / bevelSegments;
  21639. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21640. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21641. // contract shape
  21642. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21643. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21644. v( vert.x, vert.y, - z );
  21645. }
  21646. // expand holes
  21647. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21648. const ahole = holes[ h ];
  21649. oneHoleMovements = holesMovements[ h ];
  21650. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21651. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21652. v( vert.x, vert.y, - z );
  21653. }
  21654. }
  21655. }
  21656. const bs = bevelSize + bevelOffset;
  21657. // Back facing vertices
  21658. for ( let i = 0; i < vlen; i ++ ) {
  21659. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21660. if ( ! extrudeByPath ) {
  21661. v( vert.x, vert.y, 0 );
  21662. } else {
  21663. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21664. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21665. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21666. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21667. v( position2.x, position2.y, position2.z );
  21668. }
  21669. }
  21670. // Add stepped vertices...
  21671. // Including front facing vertices
  21672. for ( let s = 1; s <= steps; s ++ ) {
  21673. for ( let i = 0; i < vlen; i ++ ) {
  21674. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21675. if ( ! extrudeByPath ) {
  21676. v( vert.x, vert.y, depth / steps * s );
  21677. } else {
  21678. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21679. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21680. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21681. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21682. v( position2.x, position2.y, position2.z );
  21683. }
  21684. }
  21685. }
  21686. // Add bevel segments planes
  21687. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21688. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21689. const t = b / bevelSegments;
  21690. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21691. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21692. // contract shape
  21693. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21694. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21695. v( vert.x, vert.y, depth + z );
  21696. }
  21697. // expand holes
  21698. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21699. const ahole = holes[ h ];
  21700. oneHoleMovements = holesMovements[ h ];
  21701. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21702. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21703. if ( ! extrudeByPath ) {
  21704. v( vert.x, vert.y, depth + z );
  21705. } else {
  21706. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21707. }
  21708. }
  21709. }
  21710. }
  21711. /* Faces */
  21712. // Top and bottom faces
  21713. buildLidFaces();
  21714. // Sides faces
  21715. buildSideFaces();
  21716. ///// Internal functions
  21717. function buildLidFaces() {
  21718. const start = verticesArray.length / 3;
  21719. if ( bevelEnabled ) {
  21720. let layer = 0; // steps + 1
  21721. let offset = vlen * layer;
  21722. // Bottom faces
  21723. for ( let i = 0; i < flen; i ++ ) {
  21724. const face = faces[ i ];
  21725. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21726. }
  21727. layer = steps + bevelSegments * 2;
  21728. offset = vlen * layer;
  21729. // Top faces
  21730. for ( let i = 0; i < flen; i ++ ) {
  21731. const face = faces[ i ];
  21732. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21733. }
  21734. } else {
  21735. // Bottom faces
  21736. for ( let i = 0; i < flen; i ++ ) {
  21737. const face = faces[ i ];
  21738. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21739. }
  21740. // Top faces
  21741. for ( let i = 0; i < flen; i ++ ) {
  21742. const face = faces[ i ];
  21743. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21744. }
  21745. }
  21746. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21747. }
  21748. // Create faces for the z-sides of the shape
  21749. function buildSideFaces() {
  21750. const start = verticesArray.length / 3;
  21751. let layeroffset = 0;
  21752. sidewalls( contour, layeroffset );
  21753. layeroffset += contour.length;
  21754. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21755. const ahole = holes[ h ];
  21756. sidewalls( ahole, layeroffset );
  21757. //, true
  21758. layeroffset += ahole.length;
  21759. }
  21760. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21761. }
  21762. function sidewalls( contour, layeroffset ) {
  21763. let i = contour.length;
  21764. while ( -- i >= 0 ) {
  21765. const j = i;
  21766. let k = i - 1;
  21767. if ( k < 0 ) k = contour.length - 1;
  21768. //console.log('b', i,j, i-1, k,vertices.length);
  21769. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21770. const slen1 = vlen * s;
  21771. const slen2 = vlen * ( s + 1 );
  21772. const a = layeroffset + j + slen1,
  21773. b = layeroffset + k + slen1,
  21774. c = layeroffset + k + slen2,
  21775. d = layeroffset + j + slen2;
  21776. f4( a, b, c, d );
  21777. }
  21778. }
  21779. }
  21780. function v( x, y, z ) {
  21781. placeholder.push( x );
  21782. placeholder.push( y );
  21783. placeholder.push( z );
  21784. }
  21785. function f3( a, b, c ) {
  21786. addVertex( a );
  21787. addVertex( b );
  21788. addVertex( c );
  21789. const nextIndex = verticesArray.length / 3;
  21790. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21791. addUV( uvs[ 0 ] );
  21792. addUV( uvs[ 1 ] );
  21793. addUV( uvs[ 2 ] );
  21794. }
  21795. function f4( a, b, c, d ) {
  21796. addVertex( a );
  21797. addVertex( b );
  21798. addVertex( d );
  21799. addVertex( b );
  21800. addVertex( c );
  21801. addVertex( d );
  21802. const nextIndex = verticesArray.length / 3;
  21803. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21804. addUV( uvs[ 0 ] );
  21805. addUV( uvs[ 1 ] );
  21806. addUV( uvs[ 3 ] );
  21807. addUV( uvs[ 1 ] );
  21808. addUV( uvs[ 2 ] );
  21809. addUV( uvs[ 3 ] );
  21810. }
  21811. function addVertex( index ) {
  21812. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21813. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21814. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21815. }
  21816. function addUV( vector2 ) {
  21817. uvArray.push( vector2.x );
  21818. uvArray.push( vector2.y );
  21819. }
  21820. }
  21821. }
  21822. copy( source ) {
  21823. super.copy( source );
  21824. this.parameters = Object.assign( {}, source.parameters );
  21825. return this;
  21826. }
  21827. toJSON() {
  21828. const data = super.toJSON();
  21829. const shapes = this.parameters.shapes;
  21830. const options = this.parameters.options;
  21831. return toJSON$1( shapes, options, data );
  21832. }
  21833. static fromJSON( data, shapes ) {
  21834. const geometryShapes = [];
  21835. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21836. const shape = shapes[ data.shapes[ j ] ];
  21837. geometryShapes.push( shape );
  21838. }
  21839. const extrudePath = data.options.extrudePath;
  21840. if ( extrudePath !== undefined ) {
  21841. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21842. }
  21843. return new ExtrudeGeometry( geometryShapes, data.options );
  21844. }
  21845. }
  21846. const WorldUVGenerator = {
  21847. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21848. const a_x = vertices[ indexA * 3 ];
  21849. const a_y = vertices[ indexA * 3 + 1 ];
  21850. const b_x = vertices[ indexB * 3 ];
  21851. const b_y = vertices[ indexB * 3 + 1 ];
  21852. const c_x = vertices[ indexC * 3 ];
  21853. const c_y = vertices[ indexC * 3 + 1 ];
  21854. return [
  21855. new Vector2( a_x, a_y ),
  21856. new Vector2( b_x, b_y ),
  21857. new Vector2( c_x, c_y )
  21858. ];
  21859. },
  21860. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21861. const a_x = vertices[ indexA * 3 ];
  21862. const a_y = vertices[ indexA * 3 + 1 ];
  21863. const a_z = vertices[ indexA * 3 + 2 ];
  21864. const b_x = vertices[ indexB * 3 ];
  21865. const b_y = vertices[ indexB * 3 + 1 ];
  21866. const b_z = vertices[ indexB * 3 + 2 ];
  21867. const c_x = vertices[ indexC * 3 ];
  21868. const c_y = vertices[ indexC * 3 + 1 ];
  21869. const c_z = vertices[ indexC * 3 + 2 ];
  21870. const d_x = vertices[ indexD * 3 ];
  21871. const d_y = vertices[ indexD * 3 + 1 ];
  21872. const d_z = vertices[ indexD * 3 + 2 ];
  21873. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21874. return [
  21875. new Vector2( a_x, 1 - a_z ),
  21876. new Vector2( b_x, 1 - b_z ),
  21877. new Vector2( c_x, 1 - c_z ),
  21878. new Vector2( d_x, 1 - d_z )
  21879. ];
  21880. } else {
  21881. return [
  21882. new Vector2( a_y, 1 - a_z ),
  21883. new Vector2( b_y, 1 - b_z ),
  21884. new Vector2( c_y, 1 - c_z ),
  21885. new Vector2( d_y, 1 - d_z )
  21886. ];
  21887. }
  21888. }
  21889. };
  21890. function toJSON$1( shapes, options, data ) {
  21891. data.shapes = [];
  21892. if ( Array.isArray( shapes ) ) {
  21893. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21894. const shape = shapes[ i ];
  21895. data.shapes.push( shape.uuid );
  21896. }
  21897. } else {
  21898. data.shapes.push( shapes.uuid );
  21899. }
  21900. data.options = Object.assign( {}, options );
  21901. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21902. return data;
  21903. }
  21904. class IcosahedronGeometry extends PolyhedronGeometry {
  21905. constructor( radius = 1, detail = 0 ) {
  21906. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21907. const vertices = [
  21908. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21909. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21910. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21911. ];
  21912. const indices = [
  21913. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21914. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21915. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21916. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21917. ];
  21918. super( vertices, indices, radius, detail );
  21919. this.type = 'IcosahedronGeometry';
  21920. this.parameters = {
  21921. radius: radius,
  21922. detail: detail
  21923. };
  21924. }
  21925. static fromJSON( data ) {
  21926. return new IcosahedronGeometry( data.radius, data.detail );
  21927. }
  21928. }
  21929. class OctahedronGeometry extends PolyhedronGeometry {
  21930. constructor( radius = 1, detail = 0 ) {
  21931. const vertices = [
  21932. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21933. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21934. ];
  21935. const indices = [
  21936. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21937. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21938. 1, 3, 4, 1, 4, 2
  21939. ];
  21940. super( vertices, indices, radius, detail );
  21941. this.type = 'OctahedronGeometry';
  21942. this.parameters = {
  21943. radius: radius,
  21944. detail: detail
  21945. };
  21946. }
  21947. static fromJSON( data ) {
  21948. return new OctahedronGeometry( data.radius, data.detail );
  21949. }
  21950. }
  21951. class RingGeometry extends BufferGeometry {
  21952. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21953. super();
  21954. this.type = 'RingGeometry';
  21955. this.parameters = {
  21956. innerRadius: innerRadius,
  21957. outerRadius: outerRadius,
  21958. thetaSegments: thetaSegments,
  21959. phiSegments: phiSegments,
  21960. thetaStart: thetaStart,
  21961. thetaLength: thetaLength
  21962. };
  21963. thetaSegments = Math.max( 3, thetaSegments );
  21964. phiSegments = Math.max( 1, phiSegments );
  21965. // buffers
  21966. const indices = [];
  21967. const vertices = [];
  21968. const normals = [];
  21969. const uvs = [];
  21970. // some helper variables
  21971. let radius = innerRadius;
  21972. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21973. const vertex = new Vector3();
  21974. const uv = new Vector2();
  21975. // generate vertices, normals and uvs
  21976. for ( let j = 0; j <= phiSegments; j ++ ) {
  21977. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21978. // values are generate from the inside of the ring to the outside
  21979. const segment = thetaStart + i / thetaSegments * thetaLength;
  21980. // vertex
  21981. vertex.x = radius * Math.cos( segment );
  21982. vertex.y = radius * Math.sin( segment );
  21983. vertices.push( vertex.x, vertex.y, vertex.z );
  21984. // normal
  21985. normals.push( 0, 0, 1 );
  21986. // uv
  21987. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21988. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21989. uvs.push( uv.x, uv.y );
  21990. }
  21991. // increase the radius for next row of vertices
  21992. radius += radiusStep;
  21993. }
  21994. // indices
  21995. for ( let j = 0; j < phiSegments; j ++ ) {
  21996. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21997. for ( let i = 0; i < thetaSegments; i ++ ) {
  21998. const segment = i + thetaSegmentLevel;
  21999. const a = segment;
  22000. const b = segment + thetaSegments + 1;
  22001. const c = segment + thetaSegments + 2;
  22002. const d = segment + 1;
  22003. // faces
  22004. indices.push( a, b, d );
  22005. indices.push( b, c, d );
  22006. }
  22007. }
  22008. // build geometry
  22009. this.setIndex( indices );
  22010. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22011. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22012. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22013. }
  22014. copy( source ) {
  22015. super.copy( source );
  22016. this.parameters = Object.assign( {}, source.parameters );
  22017. return this;
  22018. }
  22019. static fromJSON( data ) {
  22020. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  22021. }
  22022. }
  22023. class ShapeGeometry extends BufferGeometry {
  22024. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  22025. super();
  22026. this.type = 'ShapeGeometry';
  22027. this.parameters = {
  22028. shapes: shapes,
  22029. curveSegments: curveSegments
  22030. };
  22031. // buffers
  22032. const indices = [];
  22033. const vertices = [];
  22034. const normals = [];
  22035. const uvs = [];
  22036. // helper variables
  22037. let groupStart = 0;
  22038. let groupCount = 0;
  22039. // allow single and array values for "shapes" parameter
  22040. if ( Array.isArray( shapes ) === false ) {
  22041. addShape( shapes );
  22042. } else {
  22043. for ( let i = 0; i < shapes.length; i ++ ) {
  22044. addShape( shapes[ i ] );
  22045. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  22046. groupStart += groupCount;
  22047. groupCount = 0;
  22048. }
  22049. }
  22050. // build geometry
  22051. this.setIndex( indices );
  22052. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22053. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22054. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22055. // helper functions
  22056. function addShape( shape ) {
  22057. const indexOffset = vertices.length / 3;
  22058. const points = shape.extractPoints( curveSegments );
  22059. let shapeVertices = points.shape;
  22060. const shapeHoles = points.holes;
  22061. // check direction of vertices
  22062. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  22063. shapeVertices = shapeVertices.reverse();
  22064. }
  22065. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  22066. const shapeHole = shapeHoles[ i ];
  22067. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  22068. shapeHoles[ i ] = shapeHole.reverse();
  22069. }
  22070. }
  22071. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  22072. // join vertices of inner and outer paths to a single array
  22073. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  22074. const shapeHole = shapeHoles[ i ];
  22075. shapeVertices = shapeVertices.concat( shapeHole );
  22076. }
  22077. // vertices, normals, uvs
  22078. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  22079. const vertex = shapeVertices[ i ];
  22080. vertices.push( vertex.x, vertex.y, 0 );
  22081. normals.push( 0, 0, 1 );
  22082. uvs.push( vertex.x, vertex.y ); // world uvs
  22083. }
  22084. // indices
  22085. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  22086. const face = faces[ i ];
  22087. const a = face[ 0 ] + indexOffset;
  22088. const b = face[ 1 ] + indexOffset;
  22089. const c = face[ 2 ] + indexOffset;
  22090. indices.push( a, b, c );
  22091. groupCount += 3;
  22092. }
  22093. }
  22094. }
  22095. copy( source ) {
  22096. super.copy( source );
  22097. this.parameters = Object.assign( {}, source.parameters );
  22098. return this;
  22099. }
  22100. toJSON() {
  22101. const data = super.toJSON();
  22102. const shapes = this.parameters.shapes;
  22103. return toJSON( shapes, data );
  22104. }
  22105. static fromJSON( data, shapes ) {
  22106. const geometryShapes = [];
  22107. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  22108. const shape = shapes[ data.shapes[ j ] ];
  22109. geometryShapes.push( shape );
  22110. }
  22111. return new ShapeGeometry( geometryShapes, data.curveSegments );
  22112. }
  22113. }
  22114. function toJSON( shapes, data ) {
  22115. data.shapes = [];
  22116. if ( Array.isArray( shapes ) ) {
  22117. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22118. const shape = shapes[ i ];
  22119. data.shapes.push( shape.uuid );
  22120. }
  22121. } else {
  22122. data.shapes.push( shapes.uuid );
  22123. }
  22124. return data;
  22125. }
  22126. class SphereGeometry extends BufferGeometry {
  22127. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  22128. super();
  22129. this.type = 'SphereGeometry';
  22130. this.parameters = {
  22131. radius: radius,
  22132. widthSegments: widthSegments,
  22133. heightSegments: heightSegments,
  22134. phiStart: phiStart,
  22135. phiLength: phiLength,
  22136. thetaStart: thetaStart,
  22137. thetaLength: thetaLength
  22138. };
  22139. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  22140. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  22141. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  22142. let index = 0;
  22143. const grid = [];
  22144. const vertex = new Vector3();
  22145. const normal = new Vector3();
  22146. // buffers
  22147. const indices = [];
  22148. const vertices = [];
  22149. const normals = [];
  22150. const uvs = [];
  22151. // generate vertices, normals and uvs
  22152. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  22153. const verticesRow = [];
  22154. const v = iy / heightSegments;
  22155. // special case for the poles
  22156. let uOffset = 0;
  22157. if ( iy === 0 && thetaStart === 0 ) {
  22158. uOffset = 0.5 / widthSegments;
  22159. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  22160. uOffset = - 0.5 / widthSegments;
  22161. }
  22162. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  22163. const u = ix / widthSegments;
  22164. // vertex
  22165. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22166. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22167. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22168. vertices.push( vertex.x, vertex.y, vertex.z );
  22169. // normal
  22170. normal.copy( vertex ).normalize();
  22171. normals.push( normal.x, normal.y, normal.z );
  22172. // uv
  22173. uvs.push( u + uOffset, 1 - v );
  22174. verticesRow.push( index ++ );
  22175. }
  22176. grid.push( verticesRow );
  22177. }
  22178. // indices
  22179. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  22180. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  22181. const a = grid[ iy ][ ix + 1 ];
  22182. const b = grid[ iy ][ ix ];
  22183. const c = grid[ iy + 1 ][ ix ];
  22184. const d = grid[ iy + 1 ][ ix + 1 ];
  22185. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22186. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  22187. }
  22188. }
  22189. // build geometry
  22190. this.setIndex( indices );
  22191. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22192. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22193. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22194. }
  22195. copy( source ) {
  22196. super.copy( source );
  22197. this.parameters = Object.assign( {}, source.parameters );
  22198. return this;
  22199. }
  22200. static fromJSON( data ) {
  22201. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  22202. }
  22203. }
  22204. class TetrahedronGeometry extends PolyhedronGeometry {
  22205. constructor( radius = 1, detail = 0 ) {
  22206. const vertices = [
  22207. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22208. ];
  22209. const indices = [
  22210. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22211. ];
  22212. super( vertices, indices, radius, detail );
  22213. this.type = 'TetrahedronGeometry';
  22214. this.parameters = {
  22215. radius: radius,
  22216. detail: detail
  22217. };
  22218. }
  22219. static fromJSON( data ) {
  22220. return new TetrahedronGeometry( data.radius, data.detail );
  22221. }
  22222. }
  22223. class TorusGeometry extends BufferGeometry {
  22224. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  22225. super();
  22226. this.type = 'TorusGeometry';
  22227. this.parameters = {
  22228. radius: radius,
  22229. tube: tube,
  22230. radialSegments: radialSegments,
  22231. tubularSegments: tubularSegments,
  22232. arc: arc
  22233. };
  22234. radialSegments = Math.floor( radialSegments );
  22235. tubularSegments = Math.floor( tubularSegments );
  22236. // buffers
  22237. const indices = [];
  22238. const vertices = [];
  22239. const normals = [];
  22240. const uvs = [];
  22241. // helper variables
  22242. const center = new Vector3();
  22243. const vertex = new Vector3();
  22244. const normal = new Vector3();
  22245. // generate vertices, normals and uvs
  22246. for ( let j = 0; j <= radialSegments; j ++ ) {
  22247. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22248. const u = i / tubularSegments * arc;
  22249. const v = j / radialSegments * Math.PI * 2;
  22250. // vertex
  22251. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22252. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22253. vertex.z = tube * Math.sin( v );
  22254. vertices.push( vertex.x, vertex.y, vertex.z );
  22255. // normal
  22256. center.x = radius * Math.cos( u );
  22257. center.y = radius * Math.sin( u );
  22258. normal.subVectors( vertex, center ).normalize();
  22259. normals.push( normal.x, normal.y, normal.z );
  22260. // uv
  22261. uvs.push( i / tubularSegments );
  22262. uvs.push( j / radialSegments );
  22263. }
  22264. }
  22265. // generate indices
  22266. for ( let j = 1; j <= radialSegments; j ++ ) {
  22267. for ( let i = 1; i <= tubularSegments; i ++ ) {
  22268. // indices
  22269. const a = ( tubularSegments + 1 ) * j + i - 1;
  22270. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22271. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22272. const d = ( tubularSegments + 1 ) * j + i;
  22273. // faces
  22274. indices.push( a, b, d );
  22275. indices.push( b, c, d );
  22276. }
  22277. }
  22278. // build geometry
  22279. this.setIndex( indices );
  22280. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22281. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22282. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22283. }
  22284. copy( source ) {
  22285. super.copy( source );
  22286. this.parameters = Object.assign( {}, source.parameters );
  22287. return this;
  22288. }
  22289. static fromJSON( data ) {
  22290. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  22291. }
  22292. }
  22293. class TorusKnotGeometry extends BufferGeometry {
  22294. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  22295. super();
  22296. this.type = 'TorusKnotGeometry';
  22297. this.parameters = {
  22298. radius: radius,
  22299. tube: tube,
  22300. tubularSegments: tubularSegments,
  22301. radialSegments: radialSegments,
  22302. p: p,
  22303. q: q
  22304. };
  22305. tubularSegments = Math.floor( tubularSegments );
  22306. radialSegments = Math.floor( radialSegments );
  22307. // buffers
  22308. const indices = [];
  22309. const vertices = [];
  22310. const normals = [];
  22311. const uvs = [];
  22312. // helper variables
  22313. const vertex = new Vector3();
  22314. const normal = new Vector3();
  22315. const P1 = new Vector3();
  22316. const P2 = new Vector3();
  22317. const B = new Vector3();
  22318. const T = new Vector3();
  22319. const N = new Vector3();
  22320. // generate vertices, normals and uvs
  22321. for ( let i = 0; i <= tubularSegments; ++ i ) {
  22322. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  22323. const u = i / tubularSegments * p * Math.PI * 2;
  22324. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22325. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22326. calculatePositionOnCurve( u, p, q, radius, P1 );
  22327. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  22328. // calculate orthonormal basis
  22329. T.subVectors( P2, P1 );
  22330. N.addVectors( P2, P1 );
  22331. B.crossVectors( T, N );
  22332. N.crossVectors( B, T );
  22333. // normalize B, N. T can be ignored, we don't use it
  22334. B.normalize();
  22335. N.normalize();
  22336. for ( let j = 0; j <= radialSegments; ++ j ) {
  22337. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22338. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22339. const v = j / radialSegments * Math.PI * 2;
  22340. const cx = - tube * Math.cos( v );
  22341. const cy = tube * Math.sin( v );
  22342. // now calculate the final vertex position.
  22343. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  22344. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  22345. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  22346. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  22347. vertices.push( vertex.x, vertex.y, vertex.z );
  22348. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22349. normal.subVectors( vertex, P1 ).normalize();
  22350. normals.push( normal.x, normal.y, normal.z );
  22351. // uv
  22352. uvs.push( i / tubularSegments );
  22353. uvs.push( j / radialSegments );
  22354. }
  22355. }
  22356. // generate indices
  22357. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22358. for ( let i = 1; i <= radialSegments; i ++ ) {
  22359. // indices
  22360. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22361. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22362. const c = ( radialSegments + 1 ) * j + i;
  22363. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22364. // faces
  22365. indices.push( a, b, d );
  22366. indices.push( b, c, d );
  22367. }
  22368. }
  22369. // build geometry
  22370. this.setIndex( indices );
  22371. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22372. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22373. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22374. // this function calculates the current position on the torus curve
  22375. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22376. const cu = Math.cos( u );
  22377. const su = Math.sin( u );
  22378. const quOverP = q / p * u;
  22379. const cs = Math.cos( quOverP );
  22380. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22381. position.y = radius * ( 2 + cs ) * su * 0.5;
  22382. position.z = radius * Math.sin( quOverP ) * 0.5;
  22383. }
  22384. }
  22385. copy( source ) {
  22386. super.copy( source );
  22387. this.parameters = Object.assign( {}, source.parameters );
  22388. return this;
  22389. }
  22390. static fromJSON( data ) {
  22391. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  22392. }
  22393. }
  22394. class TubeGeometry extends BufferGeometry {
  22395. 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 ) {
  22396. super();
  22397. this.type = 'TubeGeometry';
  22398. this.parameters = {
  22399. path: path,
  22400. tubularSegments: tubularSegments,
  22401. radius: radius,
  22402. radialSegments: radialSegments,
  22403. closed: closed
  22404. };
  22405. const frames = path.computeFrenetFrames( tubularSegments, closed );
  22406. // expose internals
  22407. this.tangents = frames.tangents;
  22408. this.normals = frames.normals;
  22409. this.binormals = frames.binormals;
  22410. // helper variables
  22411. const vertex = new Vector3();
  22412. const normal = new Vector3();
  22413. const uv = new Vector2();
  22414. let P = new Vector3();
  22415. // buffer
  22416. const vertices = [];
  22417. const normals = [];
  22418. const uvs = [];
  22419. const indices = [];
  22420. // create buffer data
  22421. generateBufferData();
  22422. // build geometry
  22423. this.setIndex( indices );
  22424. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22425. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22426. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22427. // functions
  22428. function generateBufferData() {
  22429. for ( let i = 0; i < tubularSegments; i ++ ) {
  22430. generateSegment( i );
  22431. }
  22432. // if the geometry is not closed, generate the last row of vertices and normals
  22433. // at the regular position on the given path
  22434. //
  22435. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22436. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22437. // uvs are generated in a separate function.
  22438. // this makes it easy compute correct values for closed geometries
  22439. generateUVs();
  22440. // finally create faces
  22441. generateIndices();
  22442. }
  22443. function generateSegment( i ) {
  22444. // we use getPointAt to sample evenly distributed points from the given path
  22445. P = path.getPointAt( i / tubularSegments, P );
  22446. // retrieve corresponding normal and binormal
  22447. const N = frames.normals[ i ];
  22448. const B = frames.binormals[ i ];
  22449. // generate normals and vertices for the current segment
  22450. for ( let j = 0; j <= radialSegments; j ++ ) {
  22451. const v = j / radialSegments * Math.PI * 2;
  22452. const sin = Math.sin( v );
  22453. const cos = - Math.cos( v );
  22454. // normal
  22455. normal.x = ( cos * N.x + sin * B.x );
  22456. normal.y = ( cos * N.y + sin * B.y );
  22457. normal.z = ( cos * N.z + sin * B.z );
  22458. normal.normalize();
  22459. normals.push( normal.x, normal.y, normal.z );
  22460. // vertex
  22461. vertex.x = P.x + radius * normal.x;
  22462. vertex.y = P.y + radius * normal.y;
  22463. vertex.z = P.z + radius * normal.z;
  22464. vertices.push( vertex.x, vertex.y, vertex.z );
  22465. }
  22466. }
  22467. function generateIndices() {
  22468. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22469. for ( let i = 1; i <= radialSegments; i ++ ) {
  22470. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22471. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22472. const c = ( radialSegments + 1 ) * j + i;
  22473. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22474. // faces
  22475. indices.push( a, b, d );
  22476. indices.push( b, c, d );
  22477. }
  22478. }
  22479. }
  22480. function generateUVs() {
  22481. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22482. for ( let j = 0; j <= radialSegments; j ++ ) {
  22483. uv.x = i / tubularSegments;
  22484. uv.y = j / radialSegments;
  22485. uvs.push( uv.x, uv.y );
  22486. }
  22487. }
  22488. }
  22489. }
  22490. copy( source ) {
  22491. super.copy( source );
  22492. this.parameters = Object.assign( {}, source.parameters );
  22493. return this;
  22494. }
  22495. toJSON() {
  22496. const data = super.toJSON();
  22497. data.path = this.parameters.path.toJSON();
  22498. return data;
  22499. }
  22500. static fromJSON( data ) {
  22501. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22502. // User defined curves or instances of CurvePath will not be deserialized.
  22503. return new TubeGeometry(
  22504. new Curves[ data.path.type ]().fromJSON( data.path ),
  22505. data.tubularSegments,
  22506. data.radius,
  22507. data.radialSegments,
  22508. data.closed
  22509. );
  22510. }
  22511. }
  22512. class WireframeGeometry extends BufferGeometry {
  22513. constructor( geometry = null ) {
  22514. super();
  22515. this.type = 'WireframeGeometry';
  22516. this.parameters = {
  22517. geometry: geometry
  22518. };
  22519. if ( geometry !== null ) {
  22520. // buffer
  22521. const vertices = [];
  22522. const edges = new Set();
  22523. // helper variables
  22524. const start = new Vector3();
  22525. const end = new Vector3();
  22526. if ( geometry.index !== null ) {
  22527. // indexed BufferGeometry
  22528. const position = geometry.attributes.position;
  22529. const indices = geometry.index;
  22530. let groups = geometry.groups;
  22531. if ( groups.length === 0 ) {
  22532. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22533. }
  22534. // create a data structure that contains all edges without duplicates
  22535. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22536. const group = groups[ o ];
  22537. const groupStart = group.start;
  22538. const groupCount = group.count;
  22539. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22540. for ( let j = 0; j < 3; j ++ ) {
  22541. const index1 = indices.getX( i + j );
  22542. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22543. start.fromBufferAttribute( position, index1 );
  22544. end.fromBufferAttribute( position, index2 );
  22545. if ( isUniqueEdge( start, end, edges ) === true ) {
  22546. vertices.push( start.x, start.y, start.z );
  22547. vertices.push( end.x, end.y, end.z );
  22548. }
  22549. }
  22550. }
  22551. }
  22552. } else {
  22553. // non-indexed BufferGeometry
  22554. const position = geometry.attributes.position;
  22555. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22556. for ( let j = 0; j < 3; j ++ ) {
  22557. // three edges per triangle, an edge is represented as (index1, index2)
  22558. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22559. const index1 = 3 * i + j;
  22560. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22561. start.fromBufferAttribute( position, index1 );
  22562. end.fromBufferAttribute( position, index2 );
  22563. if ( isUniqueEdge( start, end, edges ) === true ) {
  22564. vertices.push( start.x, start.y, start.z );
  22565. vertices.push( end.x, end.y, end.z );
  22566. }
  22567. }
  22568. }
  22569. }
  22570. // build geometry
  22571. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22572. }
  22573. }
  22574. copy( source ) {
  22575. super.copy( source );
  22576. this.parameters = Object.assign( {}, source.parameters );
  22577. return this;
  22578. }
  22579. }
  22580. function isUniqueEdge( start, end, edges ) {
  22581. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22582. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22583. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22584. return false;
  22585. } else {
  22586. edges.add( hash1 );
  22587. edges.add( hash2 );
  22588. return true;
  22589. }
  22590. }
  22591. var Geometries = /*#__PURE__*/Object.freeze({
  22592. __proto__: null,
  22593. BoxGeometry: BoxGeometry,
  22594. CapsuleGeometry: CapsuleGeometry,
  22595. CircleGeometry: CircleGeometry,
  22596. ConeGeometry: ConeGeometry,
  22597. CylinderGeometry: CylinderGeometry,
  22598. DodecahedronGeometry: DodecahedronGeometry,
  22599. EdgesGeometry: EdgesGeometry,
  22600. ExtrudeGeometry: ExtrudeGeometry,
  22601. IcosahedronGeometry: IcosahedronGeometry,
  22602. LatheGeometry: LatheGeometry,
  22603. OctahedronGeometry: OctahedronGeometry,
  22604. PlaneGeometry: PlaneGeometry,
  22605. PolyhedronGeometry: PolyhedronGeometry,
  22606. RingGeometry: RingGeometry,
  22607. ShapeGeometry: ShapeGeometry,
  22608. SphereGeometry: SphereGeometry,
  22609. TetrahedronGeometry: TetrahedronGeometry,
  22610. TorusGeometry: TorusGeometry,
  22611. TorusKnotGeometry: TorusKnotGeometry,
  22612. TubeGeometry: TubeGeometry,
  22613. WireframeGeometry: WireframeGeometry
  22614. });
  22615. class ShadowMaterial extends Material {
  22616. constructor( parameters ) {
  22617. super();
  22618. this.isShadowMaterial = true;
  22619. this.type = 'ShadowMaterial';
  22620. this.color = new Color( 0x000000 );
  22621. this.transparent = true;
  22622. this.fog = true;
  22623. this.setValues( parameters );
  22624. }
  22625. copy( source ) {
  22626. super.copy( source );
  22627. this.color.copy( source.color );
  22628. this.fog = source.fog;
  22629. return this;
  22630. }
  22631. }
  22632. class RawShaderMaterial extends ShaderMaterial {
  22633. constructor( parameters ) {
  22634. super( parameters );
  22635. this.isRawShaderMaterial = true;
  22636. this.type = 'RawShaderMaterial';
  22637. }
  22638. }
  22639. class MeshStandardMaterial extends Material {
  22640. constructor( parameters ) {
  22641. super();
  22642. this.isMeshStandardMaterial = true;
  22643. this.defines = { 'STANDARD': '' };
  22644. this.type = 'MeshStandardMaterial';
  22645. this.color = new Color( 0xffffff ); // diffuse
  22646. this.roughness = 1.0;
  22647. this.metalness = 0.0;
  22648. this.map = null;
  22649. this.lightMap = null;
  22650. this.lightMapIntensity = 1.0;
  22651. this.aoMap = null;
  22652. this.aoMapIntensity = 1.0;
  22653. this.emissive = new Color( 0x000000 );
  22654. this.emissiveIntensity = 1.0;
  22655. this.emissiveMap = null;
  22656. this.bumpMap = null;
  22657. this.bumpScale = 1;
  22658. this.normalMap = null;
  22659. this.normalMapType = TangentSpaceNormalMap;
  22660. this.normalScale = new Vector2( 1, 1 );
  22661. this.displacementMap = null;
  22662. this.displacementScale = 1;
  22663. this.displacementBias = 0;
  22664. this.roughnessMap = null;
  22665. this.metalnessMap = null;
  22666. this.alphaMap = null;
  22667. this.envMap = null;
  22668. this.envMapIntensity = 1.0;
  22669. this.wireframe = false;
  22670. this.wireframeLinewidth = 1;
  22671. this.wireframeLinecap = 'round';
  22672. this.wireframeLinejoin = 'round';
  22673. this.flatShading = false;
  22674. this.fog = true;
  22675. this.setValues( parameters );
  22676. }
  22677. copy( source ) {
  22678. super.copy( source );
  22679. this.defines = { 'STANDARD': '' };
  22680. this.color.copy( source.color );
  22681. this.roughness = source.roughness;
  22682. this.metalness = source.metalness;
  22683. this.map = source.map;
  22684. this.lightMap = source.lightMap;
  22685. this.lightMapIntensity = source.lightMapIntensity;
  22686. this.aoMap = source.aoMap;
  22687. this.aoMapIntensity = source.aoMapIntensity;
  22688. this.emissive.copy( source.emissive );
  22689. this.emissiveMap = source.emissiveMap;
  22690. this.emissiveIntensity = source.emissiveIntensity;
  22691. this.bumpMap = source.bumpMap;
  22692. this.bumpScale = source.bumpScale;
  22693. this.normalMap = source.normalMap;
  22694. this.normalMapType = source.normalMapType;
  22695. this.normalScale.copy( source.normalScale );
  22696. this.displacementMap = source.displacementMap;
  22697. this.displacementScale = source.displacementScale;
  22698. this.displacementBias = source.displacementBias;
  22699. this.roughnessMap = source.roughnessMap;
  22700. this.metalnessMap = source.metalnessMap;
  22701. this.alphaMap = source.alphaMap;
  22702. this.envMap = source.envMap;
  22703. this.envMapIntensity = source.envMapIntensity;
  22704. this.wireframe = source.wireframe;
  22705. this.wireframeLinewidth = source.wireframeLinewidth;
  22706. this.wireframeLinecap = source.wireframeLinecap;
  22707. this.wireframeLinejoin = source.wireframeLinejoin;
  22708. this.flatShading = source.flatShading;
  22709. this.fog = source.fog;
  22710. return this;
  22711. }
  22712. }
  22713. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22714. constructor( parameters ) {
  22715. super();
  22716. this.isMeshPhysicalMaterial = true;
  22717. this.defines = {
  22718. 'STANDARD': '',
  22719. 'PHYSICAL': ''
  22720. };
  22721. this.type = 'MeshPhysicalMaterial';
  22722. this.clearcoatMap = null;
  22723. this.clearcoatRoughness = 0.0;
  22724. this.clearcoatRoughnessMap = null;
  22725. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22726. this.clearcoatNormalMap = null;
  22727. this.ior = 1.5;
  22728. Object.defineProperty( this, 'reflectivity', {
  22729. get: function () {
  22730. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22731. },
  22732. set: function ( reflectivity ) {
  22733. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22734. }
  22735. } );
  22736. this.iridescenceMap = null;
  22737. this.iridescenceIOR = 1.3;
  22738. this.iridescenceThicknessRange = [ 100, 400 ];
  22739. this.iridescenceThicknessMap = null;
  22740. this.sheenColor = new Color( 0x000000 );
  22741. this.sheenColorMap = null;
  22742. this.sheenRoughness = 1.0;
  22743. this.sheenRoughnessMap = null;
  22744. this.transmissionMap = null;
  22745. this.thickness = 0;
  22746. this.thicknessMap = null;
  22747. this.attenuationDistance = Infinity;
  22748. this.attenuationColor = new Color( 1, 1, 1 );
  22749. this.specularIntensity = 1.0;
  22750. this.specularIntensityMap = null;
  22751. this.specularColor = new Color( 1, 1, 1 );
  22752. this.specularColorMap = null;
  22753. this._sheen = 0.0;
  22754. this._clearcoat = 0;
  22755. this._iridescence = 0;
  22756. this._transmission = 0;
  22757. this.setValues( parameters );
  22758. }
  22759. get sheen() {
  22760. return this._sheen;
  22761. }
  22762. set sheen( value ) {
  22763. if ( this._sheen > 0 !== value > 0 ) {
  22764. this.version ++;
  22765. }
  22766. this._sheen = value;
  22767. }
  22768. get clearcoat() {
  22769. return this._clearcoat;
  22770. }
  22771. set clearcoat( value ) {
  22772. if ( this._clearcoat > 0 !== value > 0 ) {
  22773. this.version ++;
  22774. }
  22775. this._clearcoat = value;
  22776. }
  22777. get iridescence() {
  22778. return this._iridescence;
  22779. }
  22780. set iridescence( value ) {
  22781. if ( this._iridescence > 0 !== value > 0 ) {
  22782. this.version ++;
  22783. }
  22784. this._iridescence = value;
  22785. }
  22786. get transmission() {
  22787. return this._transmission;
  22788. }
  22789. set transmission( value ) {
  22790. if ( this._transmission > 0 !== value > 0 ) {
  22791. this.version ++;
  22792. }
  22793. this._transmission = value;
  22794. }
  22795. copy( source ) {
  22796. super.copy( source );
  22797. this.defines = {
  22798. 'STANDARD': '',
  22799. 'PHYSICAL': ''
  22800. };
  22801. this.clearcoat = source.clearcoat;
  22802. this.clearcoatMap = source.clearcoatMap;
  22803. this.clearcoatRoughness = source.clearcoatRoughness;
  22804. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22805. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22806. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22807. this.ior = source.ior;
  22808. this.iridescence = source.iridescence;
  22809. this.iridescenceMap = source.iridescenceMap;
  22810. this.iridescenceIOR = source.iridescenceIOR;
  22811. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22812. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22813. this.sheen = source.sheen;
  22814. this.sheenColor.copy( source.sheenColor );
  22815. this.sheenColorMap = source.sheenColorMap;
  22816. this.sheenRoughness = source.sheenRoughness;
  22817. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22818. this.transmission = source.transmission;
  22819. this.transmissionMap = source.transmissionMap;
  22820. this.thickness = source.thickness;
  22821. this.thicknessMap = source.thicknessMap;
  22822. this.attenuationDistance = source.attenuationDistance;
  22823. this.attenuationColor.copy( source.attenuationColor );
  22824. this.specularIntensity = source.specularIntensity;
  22825. this.specularIntensityMap = source.specularIntensityMap;
  22826. this.specularColor.copy( source.specularColor );
  22827. this.specularColorMap = source.specularColorMap;
  22828. return this;
  22829. }
  22830. }
  22831. class MeshPhongMaterial extends Material {
  22832. constructor( parameters ) {
  22833. super();
  22834. this.isMeshPhongMaterial = true;
  22835. this.type = 'MeshPhongMaterial';
  22836. this.color = new Color( 0xffffff ); // diffuse
  22837. this.specular = new Color( 0x111111 );
  22838. this.shininess = 30;
  22839. this.map = null;
  22840. this.lightMap = null;
  22841. this.lightMapIntensity = 1.0;
  22842. this.aoMap = null;
  22843. this.aoMapIntensity = 1.0;
  22844. this.emissive = new Color( 0x000000 );
  22845. this.emissiveIntensity = 1.0;
  22846. this.emissiveMap = null;
  22847. this.bumpMap = null;
  22848. this.bumpScale = 1;
  22849. this.normalMap = null;
  22850. this.normalMapType = TangentSpaceNormalMap;
  22851. this.normalScale = new Vector2( 1, 1 );
  22852. this.displacementMap = null;
  22853. this.displacementScale = 1;
  22854. this.displacementBias = 0;
  22855. this.specularMap = null;
  22856. this.alphaMap = null;
  22857. this.envMap = null;
  22858. this.combine = MultiplyOperation;
  22859. this.reflectivity = 1;
  22860. this.refractionRatio = 0.98;
  22861. this.wireframe = false;
  22862. this.wireframeLinewidth = 1;
  22863. this.wireframeLinecap = 'round';
  22864. this.wireframeLinejoin = 'round';
  22865. this.flatShading = false;
  22866. this.fog = true;
  22867. this.setValues( parameters );
  22868. }
  22869. copy( source ) {
  22870. super.copy( source );
  22871. this.color.copy( source.color );
  22872. this.specular.copy( source.specular );
  22873. this.shininess = source.shininess;
  22874. this.map = source.map;
  22875. this.lightMap = source.lightMap;
  22876. this.lightMapIntensity = source.lightMapIntensity;
  22877. this.aoMap = source.aoMap;
  22878. this.aoMapIntensity = source.aoMapIntensity;
  22879. this.emissive.copy( source.emissive );
  22880. this.emissiveMap = source.emissiveMap;
  22881. this.emissiveIntensity = source.emissiveIntensity;
  22882. this.bumpMap = source.bumpMap;
  22883. this.bumpScale = source.bumpScale;
  22884. this.normalMap = source.normalMap;
  22885. this.normalMapType = source.normalMapType;
  22886. this.normalScale.copy( source.normalScale );
  22887. this.displacementMap = source.displacementMap;
  22888. this.displacementScale = source.displacementScale;
  22889. this.displacementBias = source.displacementBias;
  22890. this.specularMap = source.specularMap;
  22891. this.alphaMap = source.alphaMap;
  22892. this.envMap = source.envMap;
  22893. this.combine = source.combine;
  22894. this.reflectivity = source.reflectivity;
  22895. this.refractionRatio = source.refractionRatio;
  22896. this.wireframe = source.wireframe;
  22897. this.wireframeLinewidth = source.wireframeLinewidth;
  22898. this.wireframeLinecap = source.wireframeLinecap;
  22899. this.wireframeLinejoin = source.wireframeLinejoin;
  22900. this.flatShading = source.flatShading;
  22901. this.fog = source.fog;
  22902. return this;
  22903. }
  22904. }
  22905. class MeshToonMaterial extends Material {
  22906. constructor( parameters ) {
  22907. super();
  22908. this.isMeshToonMaterial = true;
  22909. this.defines = { 'TOON': '' };
  22910. this.type = 'MeshToonMaterial';
  22911. this.color = new Color( 0xffffff );
  22912. this.map = null;
  22913. this.gradientMap = null;
  22914. this.lightMap = null;
  22915. this.lightMapIntensity = 1.0;
  22916. this.aoMap = null;
  22917. this.aoMapIntensity = 1.0;
  22918. this.emissive = new Color( 0x000000 );
  22919. this.emissiveIntensity = 1.0;
  22920. this.emissiveMap = null;
  22921. this.bumpMap = null;
  22922. this.bumpScale = 1;
  22923. this.normalMap = null;
  22924. this.normalMapType = TangentSpaceNormalMap;
  22925. this.normalScale = new Vector2( 1, 1 );
  22926. this.displacementMap = null;
  22927. this.displacementScale = 1;
  22928. this.displacementBias = 0;
  22929. this.alphaMap = null;
  22930. this.wireframe = false;
  22931. this.wireframeLinewidth = 1;
  22932. this.wireframeLinecap = 'round';
  22933. this.wireframeLinejoin = 'round';
  22934. this.fog = true;
  22935. this.setValues( parameters );
  22936. }
  22937. copy( source ) {
  22938. super.copy( source );
  22939. this.color.copy( source.color );
  22940. this.map = source.map;
  22941. this.gradientMap = source.gradientMap;
  22942. this.lightMap = source.lightMap;
  22943. this.lightMapIntensity = source.lightMapIntensity;
  22944. this.aoMap = source.aoMap;
  22945. this.aoMapIntensity = source.aoMapIntensity;
  22946. this.emissive.copy( source.emissive );
  22947. this.emissiveMap = source.emissiveMap;
  22948. this.emissiveIntensity = source.emissiveIntensity;
  22949. this.bumpMap = source.bumpMap;
  22950. this.bumpScale = source.bumpScale;
  22951. this.normalMap = source.normalMap;
  22952. this.normalMapType = source.normalMapType;
  22953. this.normalScale.copy( source.normalScale );
  22954. this.displacementMap = source.displacementMap;
  22955. this.displacementScale = source.displacementScale;
  22956. this.displacementBias = source.displacementBias;
  22957. this.alphaMap = source.alphaMap;
  22958. this.wireframe = source.wireframe;
  22959. this.wireframeLinewidth = source.wireframeLinewidth;
  22960. this.wireframeLinecap = source.wireframeLinecap;
  22961. this.wireframeLinejoin = source.wireframeLinejoin;
  22962. this.fog = source.fog;
  22963. return this;
  22964. }
  22965. }
  22966. class MeshNormalMaterial extends Material {
  22967. constructor( parameters ) {
  22968. super();
  22969. this.isMeshNormalMaterial = true;
  22970. this.type = 'MeshNormalMaterial';
  22971. this.bumpMap = null;
  22972. this.bumpScale = 1;
  22973. this.normalMap = null;
  22974. this.normalMapType = TangentSpaceNormalMap;
  22975. this.normalScale = new Vector2( 1, 1 );
  22976. this.displacementMap = null;
  22977. this.displacementScale = 1;
  22978. this.displacementBias = 0;
  22979. this.wireframe = false;
  22980. this.wireframeLinewidth = 1;
  22981. this.flatShading = false;
  22982. this.setValues( parameters );
  22983. }
  22984. copy( source ) {
  22985. super.copy( source );
  22986. this.bumpMap = source.bumpMap;
  22987. this.bumpScale = source.bumpScale;
  22988. this.normalMap = source.normalMap;
  22989. this.normalMapType = source.normalMapType;
  22990. this.normalScale.copy( source.normalScale );
  22991. this.displacementMap = source.displacementMap;
  22992. this.displacementScale = source.displacementScale;
  22993. this.displacementBias = source.displacementBias;
  22994. this.wireframe = source.wireframe;
  22995. this.wireframeLinewidth = source.wireframeLinewidth;
  22996. this.flatShading = source.flatShading;
  22997. return this;
  22998. }
  22999. }
  23000. class MeshLambertMaterial extends Material {
  23001. constructor( parameters ) {
  23002. super();
  23003. this.isMeshLambertMaterial = true;
  23004. this.type = 'MeshLambertMaterial';
  23005. this.color = new Color( 0xffffff ); // diffuse
  23006. this.map = null;
  23007. this.lightMap = null;
  23008. this.lightMapIntensity = 1.0;
  23009. this.aoMap = null;
  23010. this.aoMapIntensity = 1.0;
  23011. this.emissive = new Color( 0x000000 );
  23012. this.emissiveIntensity = 1.0;
  23013. this.emissiveMap = null;
  23014. this.bumpMap = null;
  23015. this.bumpScale = 1;
  23016. this.normalMap = null;
  23017. this.normalMapType = TangentSpaceNormalMap;
  23018. this.normalScale = new Vector2( 1, 1 );
  23019. this.displacementMap = null;
  23020. this.displacementScale = 1;
  23021. this.displacementBias = 0;
  23022. this.specularMap = null;
  23023. this.alphaMap = null;
  23024. this.envMap = null;
  23025. this.combine = MultiplyOperation;
  23026. this.reflectivity = 1;
  23027. this.refractionRatio = 0.98;
  23028. this.wireframe = false;
  23029. this.wireframeLinewidth = 1;
  23030. this.wireframeLinecap = 'round';
  23031. this.wireframeLinejoin = 'round';
  23032. this.flatShading = false;
  23033. this.fog = true;
  23034. this.setValues( parameters );
  23035. }
  23036. copy( source ) {
  23037. super.copy( source );
  23038. this.color.copy( source.color );
  23039. this.map = source.map;
  23040. this.lightMap = source.lightMap;
  23041. this.lightMapIntensity = source.lightMapIntensity;
  23042. this.aoMap = source.aoMap;
  23043. this.aoMapIntensity = source.aoMapIntensity;
  23044. this.emissive.copy( source.emissive );
  23045. this.emissiveMap = source.emissiveMap;
  23046. this.emissiveIntensity = source.emissiveIntensity;
  23047. this.bumpMap = source.bumpMap;
  23048. this.bumpScale = source.bumpScale;
  23049. this.normalMap = source.normalMap;
  23050. this.normalMapType = source.normalMapType;
  23051. this.normalScale.copy( source.normalScale );
  23052. this.displacementMap = source.displacementMap;
  23053. this.displacementScale = source.displacementScale;
  23054. this.displacementBias = source.displacementBias;
  23055. this.specularMap = source.specularMap;
  23056. this.alphaMap = source.alphaMap;
  23057. this.envMap = source.envMap;
  23058. this.combine = source.combine;
  23059. this.reflectivity = source.reflectivity;
  23060. this.refractionRatio = source.refractionRatio;
  23061. this.wireframe = source.wireframe;
  23062. this.wireframeLinewidth = source.wireframeLinewidth;
  23063. this.wireframeLinecap = source.wireframeLinecap;
  23064. this.wireframeLinejoin = source.wireframeLinejoin;
  23065. this.flatShading = source.flatShading;
  23066. this.fog = source.fog;
  23067. return this;
  23068. }
  23069. }
  23070. class MeshMatcapMaterial extends Material {
  23071. constructor( parameters ) {
  23072. super();
  23073. this.isMeshMatcapMaterial = true;
  23074. this.defines = { 'MATCAP': '' };
  23075. this.type = 'MeshMatcapMaterial';
  23076. this.color = new Color( 0xffffff ); // diffuse
  23077. this.matcap = null;
  23078. this.map = null;
  23079. this.bumpMap = null;
  23080. this.bumpScale = 1;
  23081. this.normalMap = null;
  23082. this.normalMapType = TangentSpaceNormalMap;
  23083. this.normalScale = new Vector2( 1, 1 );
  23084. this.displacementMap = null;
  23085. this.displacementScale = 1;
  23086. this.displacementBias = 0;
  23087. this.alphaMap = null;
  23088. this.flatShading = false;
  23089. this.fog = true;
  23090. this.setValues( parameters );
  23091. }
  23092. copy( source ) {
  23093. super.copy( source );
  23094. this.defines = { 'MATCAP': '' };
  23095. this.color.copy( source.color );
  23096. this.matcap = source.matcap;
  23097. this.map = source.map;
  23098. this.bumpMap = source.bumpMap;
  23099. this.bumpScale = source.bumpScale;
  23100. this.normalMap = source.normalMap;
  23101. this.normalMapType = source.normalMapType;
  23102. this.normalScale.copy( source.normalScale );
  23103. this.displacementMap = source.displacementMap;
  23104. this.displacementScale = source.displacementScale;
  23105. this.displacementBias = source.displacementBias;
  23106. this.alphaMap = source.alphaMap;
  23107. this.flatShading = source.flatShading;
  23108. this.fog = source.fog;
  23109. return this;
  23110. }
  23111. }
  23112. class LineDashedMaterial extends LineBasicMaterial {
  23113. constructor( parameters ) {
  23114. super();
  23115. this.isLineDashedMaterial = true;
  23116. this.type = 'LineDashedMaterial';
  23117. this.scale = 1;
  23118. this.dashSize = 3;
  23119. this.gapSize = 1;
  23120. this.setValues( parameters );
  23121. }
  23122. copy( source ) {
  23123. super.copy( source );
  23124. this.scale = source.scale;
  23125. this.dashSize = source.dashSize;
  23126. this.gapSize = source.gapSize;
  23127. return this;
  23128. }
  23129. }
  23130. // same as Array.prototype.slice, but also works on typed arrays
  23131. function arraySlice( array, from, to ) {
  23132. if ( isTypedArray( array ) ) {
  23133. // in ios9 array.subarray(from, undefined) will return empty array
  23134. // but array.subarray(from) or array.subarray(from, len) is correct
  23135. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  23136. }
  23137. return array.slice( from, to );
  23138. }
  23139. // converts an array to a specific type
  23140. function convertArray( array, type, forceClone ) {
  23141. if ( ! array || // let 'undefined' and 'null' pass
  23142. ! forceClone && array.constructor === type ) return array;
  23143. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  23144. return new type( array ); // create typed array
  23145. }
  23146. return Array.prototype.slice.call( array ); // create Array
  23147. }
  23148. function isTypedArray( object ) {
  23149. return ArrayBuffer.isView( object ) &&
  23150. ! ( object instanceof DataView );
  23151. }
  23152. // returns an array by which times and values can be sorted
  23153. function getKeyframeOrder( times ) {
  23154. function compareTime( i, j ) {
  23155. return times[ i ] - times[ j ];
  23156. }
  23157. const n = times.length;
  23158. const result = new Array( n );
  23159. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  23160. result.sort( compareTime );
  23161. return result;
  23162. }
  23163. // uses the array previously returned by 'getKeyframeOrder' to sort data
  23164. function sortedArray( values, stride, order ) {
  23165. const nValues = values.length;
  23166. const result = new values.constructor( nValues );
  23167. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  23168. const srcOffset = order[ i ] * stride;
  23169. for ( let j = 0; j !== stride; ++ j ) {
  23170. result[ dstOffset ++ ] = values[ srcOffset + j ];
  23171. }
  23172. }
  23173. return result;
  23174. }
  23175. // function for parsing AOS keyframe formats
  23176. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  23177. let i = 1, key = jsonKeys[ 0 ];
  23178. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  23179. key = jsonKeys[ i ++ ];
  23180. }
  23181. if ( key === undefined ) return; // no data
  23182. let value = key[ valuePropertyName ];
  23183. if ( value === undefined ) return; // no data
  23184. if ( Array.isArray( value ) ) {
  23185. do {
  23186. value = key[ valuePropertyName ];
  23187. if ( value !== undefined ) {
  23188. times.push( key.time );
  23189. values.push.apply( values, value ); // push all elements
  23190. }
  23191. key = jsonKeys[ i ++ ];
  23192. } while ( key !== undefined );
  23193. } else if ( value.toArray !== undefined ) {
  23194. // ...assume THREE.Math-ish
  23195. do {
  23196. value = key[ valuePropertyName ];
  23197. if ( value !== undefined ) {
  23198. times.push( key.time );
  23199. value.toArray( values, values.length );
  23200. }
  23201. key = jsonKeys[ i ++ ];
  23202. } while ( key !== undefined );
  23203. } else {
  23204. // otherwise push as-is
  23205. do {
  23206. value = key[ valuePropertyName ];
  23207. if ( value !== undefined ) {
  23208. times.push( key.time );
  23209. values.push( value );
  23210. }
  23211. key = jsonKeys[ i ++ ];
  23212. } while ( key !== undefined );
  23213. }
  23214. }
  23215. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  23216. const clip = sourceClip.clone();
  23217. clip.name = name;
  23218. const tracks = [];
  23219. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23220. const track = clip.tracks[ i ];
  23221. const valueSize = track.getValueSize();
  23222. const times = [];
  23223. const values = [];
  23224. for ( let j = 0; j < track.times.length; ++ j ) {
  23225. const frame = track.times[ j ] * fps;
  23226. if ( frame < startFrame || frame >= endFrame ) continue;
  23227. times.push( track.times[ j ] );
  23228. for ( let k = 0; k < valueSize; ++ k ) {
  23229. values.push( track.values[ j * valueSize + k ] );
  23230. }
  23231. }
  23232. if ( times.length === 0 ) continue;
  23233. track.times = convertArray( times, track.times.constructor );
  23234. track.values = convertArray( values, track.values.constructor );
  23235. tracks.push( track );
  23236. }
  23237. clip.tracks = tracks;
  23238. // find minimum .times value across all tracks in the trimmed clip
  23239. let minStartTime = Infinity;
  23240. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23241. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  23242. minStartTime = clip.tracks[ i ].times[ 0 ];
  23243. }
  23244. }
  23245. // shift all tracks such that clip begins at t=0
  23246. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23247. clip.tracks[ i ].shift( - 1 * minStartTime );
  23248. }
  23249. clip.resetDuration();
  23250. return clip;
  23251. }
  23252. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  23253. if ( fps <= 0 ) fps = 30;
  23254. const numTracks = referenceClip.tracks.length;
  23255. const referenceTime = referenceFrame / fps;
  23256. // Make each track's values relative to the values at the reference frame
  23257. for ( let i = 0; i < numTracks; ++ i ) {
  23258. const referenceTrack = referenceClip.tracks[ i ];
  23259. const referenceTrackType = referenceTrack.ValueTypeName;
  23260. // Skip this track if it's non-numeric
  23261. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  23262. // Find the track in the target clip whose name and type matches the reference track
  23263. const targetTrack = targetClip.tracks.find( function ( track ) {
  23264. return track.name === referenceTrack.name
  23265. && track.ValueTypeName === referenceTrackType;
  23266. } );
  23267. if ( targetTrack === undefined ) continue;
  23268. let referenceOffset = 0;
  23269. const referenceValueSize = referenceTrack.getValueSize();
  23270. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23271. referenceOffset = referenceValueSize / 3;
  23272. }
  23273. let targetOffset = 0;
  23274. const targetValueSize = targetTrack.getValueSize();
  23275. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23276. targetOffset = targetValueSize / 3;
  23277. }
  23278. const lastIndex = referenceTrack.times.length - 1;
  23279. let referenceValue;
  23280. // Find the value to subtract out of the track
  23281. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  23282. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23283. const startIndex = referenceOffset;
  23284. const endIndex = referenceValueSize - referenceOffset;
  23285. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23286. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  23287. // Reference frame is after the last keyframe, so just use the last keyframe
  23288. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23289. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23290. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23291. } else {
  23292. // Interpolate to the reference value
  23293. const interpolant = referenceTrack.createInterpolant();
  23294. const startIndex = referenceOffset;
  23295. const endIndex = referenceValueSize - referenceOffset;
  23296. interpolant.evaluate( referenceTime );
  23297. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  23298. }
  23299. // Conjugate the quaternion
  23300. if ( referenceTrackType === 'quaternion' ) {
  23301. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  23302. referenceQuat.toArray( referenceValue );
  23303. }
  23304. // Subtract the reference value from all of the track values
  23305. const numTimes = targetTrack.times.length;
  23306. for ( let j = 0; j < numTimes; ++ j ) {
  23307. const valueStart = j * targetValueSize + targetOffset;
  23308. if ( referenceTrackType === 'quaternion' ) {
  23309. // Multiply the conjugate for quaternion track types
  23310. Quaternion.multiplyQuaternionsFlat(
  23311. targetTrack.values,
  23312. valueStart,
  23313. referenceValue,
  23314. 0,
  23315. targetTrack.values,
  23316. valueStart
  23317. );
  23318. } else {
  23319. const valueEnd = targetValueSize - targetOffset * 2;
  23320. // Subtract each value for all other numeric track types
  23321. for ( let k = 0; k < valueEnd; ++ k ) {
  23322. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  23323. }
  23324. }
  23325. }
  23326. }
  23327. targetClip.blendMode = AdditiveAnimationBlendMode;
  23328. return targetClip;
  23329. }
  23330. const AnimationUtils = {
  23331. arraySlice: arraySlice,
  23332. convertArray: convertArray,
  23333. isTypedArray: isTypedArray,
  23334. getKeyframeOrder: getKeyframeOrder,
  23335. sortedArray: sortedArray,
  23336. flattenJSON: flattenJSON,
  23337. subclip: subclip,
  23338. makeClipAdditive: makeClipAdditive
  23339. };
  23340. /**
  23341. * Abstract base class of interpolants over parametric samples.
  23342. *
  23343. * The parameter domain is one dimensional, typically the time or a path
  23344. * along a curve defined by the data.
  23345. *
  23346. * The sample values can have any dimensionality and derived classes may
  23347. * apply special interpretations to the data.
  23348. *
  23349. * This class provides the interval seek in a Template Method, deferring
  23350. * the actual interpolation to derived classes.
  23351. *
  23352. * Time complexity is O(1) for linear access crossing at most two points
  23353. * and O(log N) for random access, where N is the number of positions.
  23354. *
  23355. * References:
  23356. *
  23357. * http://www.oodesign.com/template-method-pattern.html
  23358. *
  23359. */
  23360. class Interpolant {
  23361. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23362. this.parameterPositions = parameterPositions;
  23363. this._cachedIndex = 0;
  23364. this.resultBuffer = resultBuffer !== undefined ?
  23365. resultBuffer : new sampleValues.constructor( sampleSize );
  23366. this.sampleValues = sampleValues;
  23367. this.valueSize = sampleSize;
  23368. this.settings = null;
  23369. this.DefaultSettings_ = {};
  23370. }
  23371. evaluate( t ) {
  23372. const pp = this.parameterPositions;
  23373. let i1 = this._cachedIndex,
  23374. t1 = pp[ i1 ],
  23375. t0 = pp[ i1 - 1 ];
  23376. validate_interval: {
  23377. seek: {
  23378. let right;
  23379. linear_scan: {
  23380. //- See http://jsperf.com/comparison-to-undefined/3
  23381. //- slower code:
  23382. //-
  23383. //- if ( t >= t1 || t1 === undefined ) {
  23384. forward_scan: if ( ! ( t < t1 ) ) {
  23385. for ( let giveUpAt = i1 + 2; ; ) {
  23386. if ( t1 === undefined ) {
  23387. if ( t < t0 ) break forward_scan;
  23388. // after end
  23389. i1 = pp.length;
  23390. this._cachedIndex = i1;
  23391. return this.copySampleValue_( i1 - 1 );
  23392. }
  23393. if ( i1 === giveUpAt ) break; // this loop
  23394. t0 = t1;
  23395. t1 = pp[ ++ i1 ];
  23396. if ( t < t1 ) {
  23397. // we have arrived at the sought interval
  23398. break seek;
  23399. }
  23400. }
  23401. // prepare binary search on the right side of the index
  23402. right = pp.length;
  23403. break linear_scan;
  23404. }
  23405. //- slower code:
  23406. //- if ( t < t0 || t0 === undefined ) {
  23407. if ( ! ( t >= t0 ) ) {
  23408. // looping?
  23409. const t1global = pp[ 1 ];
  23410. if ( t < t1global ) {
  23411. i1 = 2; // + 1, using the scan for the details
  23412. t0 = t1global;
  23413. }
  23414. // linear reverse scan
  23415. for ( let giveUpAt = i1 - 2; ; ) {
  23416. if ( t0 === undefined ) {
  23417. // before start
  23418. this._cachedIndex = 0;
  23419. return this.copySampleValue_( 0 );
  23420. }
  23421. if ( i1 === giveUpAt ) break; // this loop
  23422. t1 = t0;
  23423. t0 = pp[ -- i1 - 1 ];
  23424. if ( t >= t0 ) {
  23425. // we have arrived at the sought interval
  23426. break seek;
  23427. }
  23428. }
  23429. // prepare binary search on the left side of the index
  23430. right = i1;
  23431. i1 = 0;
  23432. break linear_scan;
  23433. }
  23434. // the interval is valid
  23435. break validate_interval;
  23436. } // linear scan
  23437. // binary search
  23438. while ( i1 < right ) {
  23439. const mid = ( i1 + right ) >>> 1;
  23440. if ( t < pp[ mid ] ) {
  23441. right = mid;
  23442. } else {
  23443. i1 = mid + 1;
  23444. }
  23445. }
  23446. t1 = pp[ i1 ];
  23447. t0 = pp[ i1 - 1 ];
  23448. // check boundary cases, again
  23449. if ( t0 === undefined ) {
  23450. this._cachedIndex = 0;
  23451. return this.copySampleValue_( 0 );
  23452. }
  23453. if ( t1 === undefined ) {
  23454. i1 = pp.length;
  23455. this._cachedIndex = i1;
  23456. return this.copySampleValue_( i1 - 1 );
  23457. }
  23458. } // seek
  23459. this._cachedIndex = i1;
  23460. this.intervalChanged_( i1, t0, t1 );
  23461. } // validate_interval
  23462. return this.interpolate_( i1, t0, t, t1 );
  23463. }
  23464. getSettings_() {
  23465. return this.settings || this.DefaultSettings_;
  23466. }
  23467. copySampleValue_( index ) {
  23468. // copies a sample value to the result buffer
  23469. const result = this.resultBuffer,
  23470. values = this.sampleValues,
  23471. stride = this.valueSize,
  23472. offset = index * stride;
  23473. for ( let i = 0; i !== stride; ++ i ) {
  23474. result[ i ] = values[ offset + i ];
  23475. }
  23476. return result;
  23477. }
  23478. // Template methods for derived classes:
  23479. interpolate_( /* i1, t0, t, t1 */ ) {
  23480. throw new Error( 'call to abstract method' );
  23481. // implementations shall return this.resultBuffer
  23482. }
  23483. intervalChanged_( /* i1, t0, t1 */ ) {
  23484. // empty
  23485. }
  23486. }
  23487. /**
  23488. * Fast and simple cubic spline interpolant.
  23489. *
  23490. * It was derived from a Hermitian construction setting the first derivative
  23491. * at each sample position to the linear slope between neighboring positions
  23492. * over their parameter interval.
  23493. */
  23494. class CubicInterpolant extends Interpolant {
  23495. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23496. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23497. this._weightPrev = - 0;
  23498. this._offsetPrev = - 0;
  23499. this._weightNext = - 0;
  23500. this._offsetNext = - 0;
  23501. this.DefaultSettings_ = {
  23502. endingStart: ZeroCurvatureEnding,
  23503. endingEnd: ZeroCurvatureEnding
  23504. };
  23505. }
  23506. intervalChanged_( i1, t0, t1 ) {
  23507. const pp = this.parameterPositions;
  23508. let iPrev = i1 - 2,
  23509. iNext = i1 + 1,
  23510. tPrev = pp[ iPrev ],
  23511. tNext = pp[ iNext ];
  23512. if ( tPrev === undefined ) {
  23513. switch ( this.getSettings_().endingStart ) {
  23514. case ZeroSlopeEnding:
  23515. // f'(t0) = 0
  23516. iPrev = i1;
  23517. tPrev = 2 * t0 - t1;
  23518. break;
  23519. case WrapAroundEnding:
  23520. // use the other end of the curve
  23521. iPrev = pp.length - 2;
  23522. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23523. break;
  23524. default: // ZeroCurvatureEnding
  23525. // f''(t0) = 0 a.k.a. Natural Spline
  23526. iPrev = i1;
  23527. tPrev = t1;
  23528. }
  23529. }
  23530. if ( tNext === undefined ) {
  23531. switch ( this.getSettings_().endingEnd ) {
  23532. case ZeroSlopeEnding:
  23533. // f'(tN) = 0
  23534. iNext = i1;
  23535. tNext = 2 * t1 - t0;
  23536. break;
  23537. case WrapAroundEnding:
  23538. // use the other end of the curve
  23539. iNext = 1;
  23540. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23541. break;
  23542. default: // ZeroCurvatureEnding
  23543. // f''(tN) = 0, a.k.a. Natural Spline
  23544. iNext = i1 - 1;
  23545. tNext = t0;
  23546. }
  23547. }
  23548. const halfDt = ( t1 - t0 ) * 0.5,
  23549. stride = this.valueSize;
  23550. this._weightPrev = halfDt / ( t0 - tPrev );
  23551. this._weightNext = halfDt / ( tNext - t1 );
  23552. this._offsetPrev = iPrev * stride;
  23553. this._offsetNext = iNext * stride;
  23554. }
  23555. interpolate_( i1, t0, t, t1 ) {
  23556. const result = this.resultBuffer,
  23557. values = this.sampleValues,
  23558. stride = this.valueSize,
  23559. o1 = i1 * stride, o0 = o1 - stride,
  23560. oP = this._offsetPrev, oN = this._offsetNext,
  23561. wP = this._weightPrev, wN = this._weightNext,
  23562. p = ( t - t0 ) / ( t1 - t0 ),
  23563. pp = p * p,
  23564. ppp = pp * p;
  23565. // evaluate polynomials
  23566. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23567. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23568. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23569. const sN = wN * ppp - wN * pp;
  23570. // combine data linearly
  23571. for ( let i = 0; i !== stride; ++ i ) {
  23572. result[ i ] =
  23573. sP * values[ oP + i ] +
  23574. s0 * values[ o0 + i ] +
  23575. s1 * values[ o1 + i ] +
  23576. sN * values[ oN + i ];
  23577. }
  23578. return result;
  23579. }
  23580. }
  23581. class LinearInterpolant extends Interpolant {
  23582. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23583. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23584. }
  23585. interpolate_( i1, t0, t, t1 ) {
  23586. const result = this.resultBuffer,
  23587. values = this.sampleValues,
  23588. stride = this.valueSize,
  23589. offset1 = i1 * stride,
  23590. offset0 = offset1 - stride,
  23591. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23592. weight0 = 1 - weight1;
  23593. for ( let i = 0; i !== stride; ++ i ) {
  23594. result[ i ] =
  23595. values[ offset0 + i ] * weight0 +
  23596. values[ offset1 + i ] * weight1;
  23597. }
  23598. return result;
  23599. }
  23600. }
  23601. /**
  23602. *
  23603. * Interpolant that evaluates to the sample value at the position preceding
  23604. * the parameter.
  23605. */
  23606. class DiscreteInterpolant extends Interpolant {
  23607. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23608. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23609. }
  23610. interpolate_( i1 /*, t0, t, t1 */ ) {
  23611. return this.copySampleValue_( i1 - 1 );
  23612. }
  23613. }
  23614. class KeyframeTrack {
  23615. constructor( name, times, values, interpolation ) {
  23616. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23617. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23618. this.name = name;
  23619. this.times = convertArray( times, this.TimeBufferType );
  23620. this.values = convertArray( values, this.ValueBufferType );
  23621. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23622. }
  23623. // Serialization (in static context, because of constructor invocation
  23624. // and automatic invocation of .toJSON):
  23625. static toJSON( track ) {
  23626. const trackType = track.constructor;
  23627. let json;
  23628. // derived classes can define a static toJSON method
  23629. if ( trackType.toJSON !== this.toJSON ) {
  23630. json = trackType.toJSON( track );
  23631. } else {
  23632. // by default, we assume the data can be serialized as-is
  23633. json = {
  23634. 'name': track.name,
  23635. 'times': convertArray( track.times, Array ),
  23636. 'values': convertArray( track.values, Array )
  23637. };
  23638. const interpolation = track.getInterpolation();
  23639. if ( interpolation !== track.DefaultInterpolation ) {
  23640. json.interpolation = interpolation;
  23641. }
  23642. }
  23643. json.type = track.ValueTypeName; // mandatory
  23644. return json;
  23645. }
  23646. InterpolantFactoryMethodDiscrete( result ) {
  23647. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23648. }
  23649. InterpolantFactoryMethodLinear( result ) {
  23650. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23651. }
  23652. InterpolantFactoryMethodSmooth( result ) {
  23653. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23654. }
  23655. setInterpolation( interpolation ) {
  23656. let factoryMethod;
  23657. switch ( interpolation ) {
  23658. case InterpolateDiscrete:
  23659. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23660. break;
  23661. case InterpolateLinear:
  23662. factoryMethod = this.InterpolantFactoryMethodLinear;
  23663. break;
  23664. case InterpolateSmooth:
  23665. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23666. break;
  23667. }
  23668. if ( factoryMethod === undefined ) {
  23669. const message = 'unsupported interpolation for ' +
  23670. this.ValueTypeName + ' keyframe track named ' + this.name;
  23671. if ( this.createInterpolant === undefined ) {
  23672. // fall back to default, unless the default itself is messed up
  23673. if ( interpolation !== this.DefaultInterpolation ) {
  23674. this.setInterpolation( this.DefaultInterpolation );
  23675. } else {
  23676. throw new Error( message ); // fatal, in this case
  23677. }
  23678. }
  23679. console.warn( 'THREE.KeyframeTrack:', message );
  23680. return this;
  23681. }
  23682. this.createInterpolant = factoryMethod;
  23683. return this;
  23684. }
  23685. getInterpolation() {
  23686. switch ( this.createInterpolant ) {
  23687. case this.InterpolantFactoryMethodDiscrete:
  23688. return InterpolateDiscrete;
  23689. case this.InterpolantFactoryMethodLinear:
  23690. return InterpolateLinear;
  23691. case this.InterpolantFactoryMethodSmooth:
  23692. return InterpolateSmooth;
  23693. }
  23694. }
  23695. getValueSize() {
  23696. return this.values.length / this.times.length;
  23697. }
  23698. // move all keyframes either forwards or backwards in time
  23699. shift( timeOffset ) {
  23700. if ( timeOffset !== 0.0 ) {
  23701. const times = this.times;
  23702. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23703. times[ i ] += timeOffset;
  23704. }
  23705. }
  23706. return this;
  23707. }
  23708. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23709. scale( timeScale ) {
  23710. if ( timeScale !== 1.0 ) {
  23711. const times = this.times;
  23712. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23713. times[ i ] *= timeScale;
  23714. }
  23715. }
  23716. return this;
  23717. }
  23718. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23719. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23720. trim( startTime, endTime ) {
  23721. const times = this.times,
  23722. nKeys = times.length;
  23723. let from = 0,
  23724. to = nKeys - 1;
  23725. while ( from !== nKeys && times[ from ] < startTime ) {
  23726. ++ from;
  23727. }
  23728. while ( to !== - 1 && times[ to ] > endTime ) {
  23729. -- to;
  23730. }
  23731. ++ to; // inclusive -> exclusive bound
  23732. if ( from !== 0 || to !== nKeys ) {
  23733. // empty tracks are forbidden, so keep at least one keyframe
  23734. if ( from >= to ) {
  23735. to = Math.max( to, 1 );
  23736. from = to - 1;
  23737. }
  23738. const stride = this.getValueSize();
  23739. this.times = arraySlice( times, from, to );
  23740. this.values = arraySlice( this.values, from * stride, to * stride );
  23741. }
  23742. return this;
  23743. }
  23744. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23745. validate() {
  23746. let valid = true;
  23747. const valueSize = this.getValueSize();
  23748. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23749. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23750. valid = false;
  23751. }
  23752. const times = this.times,
  23753. values = this.values,
  23754. nKeys = times.length;
  23755. if ( nKeys === 0 ) {
  23756. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23757. valid = false;
  23758. }
  23759. let prevTime = null;
  23760. for ( let i = 0; i !== nKeys; i ++ ) {
  23761. const currTime = times[ i ];
  23762. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23763. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23764. valid = false;
  23765. break;
  23766. }
  23767. if ( prevTime !== null && prevTime > currTime ) {
  23768. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23769. valid = false;
  23770. break;
  23771. }
  23772. prevTime = currTime;
  23773. }
  23774. if ( values !== undefined ) {
  23775. if ( isTypedArray( values ) ) {
  23776. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23777. const value = values[ i ];
  23778. if ( isNaN( value ) ) {
  23779. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23780. valid = false;
  23781. break;
  23782. }
  23783. }
  23784. }
  23785. }
  23786. return valid;
  23787. }
  23788. // removes equivalent sequential keys as common in morph target sequences
  23789. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23790. optimize() {
  23791. // times or values may be shared with other tracks, so overwriting is unsafe
  23792. const times = arraySlice( this.times ),
  23793. values = arraySlice( this.values ),
  23794. stride = this.getValueSize(),
  23795. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23796. lastIndex = times.length - 1;
  23797. let writeIndex = 1;
  23798. for ( let i = 1; i < lastIndex; ++ i ) {
  23799. let keep = false;
  23800. const time = times[ i ];
  23801. const timeNext = times[ i + 1 ];
  23802. // remove adjacent keyframes scheduled at the same time
  23803. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23804. if ( ! smoothInterpolation ) {
  23805. // remove unnecessary keyframes same as their neighbors
  23806. const offset = i * stride,
  23807. offsetP = offset - stride,
  23808. offsetN = offset + stride;
  23809. for ( let j = 0; j !== stride; ++ j ) {
  23810. const value = values[ offset + j ];
  23811. if ( value !== values[ offsetP + j ] ||
  23812. value !== values[ offsetN + j ] ) {
  23813. keep = true;
  23814. break;
  23815. }
  23816. }
  23817. } else {
  23818. keep = true;
  23819. }
  23820. }
  23821. // in-place compaction
  23822. if ( keep ) {
  23823. if ( i !== writeIndex ) {
  23824. times[ writeIndex ] = times[ i ];
  23825. const readOffset = i * stride,
  23826. writeOffset = writeIndex * stride;
  23827. for ( let j = 0; j !== stride; ++ j ) {
  23828. values[ writeOffset + j ] = values[ readOffset + j ];
  23829. }
  23830. }
  23831. ++ writeIndex;
  23832. }
  23833. }
  23834. // flush last keyframe (compaction looks ahead)
  23835. if ( lastIndex > 0 ) {
  23836. times[ writeIndex ] = times[ lastIndex ];
  23837. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23838. values[ writeOffset + j ] = values[ readOffset + j ];
  23839. }
  23840. ++ writeIndex;
  23841. }
  23842. if ( writeIndex !== times.length ) {
  23843. this.times = arraySlice( times, 0, writeIndex );
  23844. this.values = arraySlice( values, 0, writeIndex * stride );
  23845. } else {
  23846. this.times = times;
  23847. this.values = values;
  23848. }
  23849. return this;
  23850. }
  23851. clone() {
  23852. const times = arraySlice( this.times, 0 );
  23853. const values = arraySlice( this.values, 0 );
  23854. const TypedKeyframeTrack = this.constructor;
  23855. const track = new TypedKeyframeTrack( this.name, times, values );
  23856. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23857. track.createInterpolant = this.createInterpolant;
  23858. return track;
  23859. }
  23860. }
  23861. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23862. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23863. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23864. /**
  23865. * A Track of Boolean keyframe values.
  23866. */
  23867. class BooleanKeyframeTrack extends KeyframeTrack {}
  23868. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23869. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23870. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23871. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23872. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23873. /**
  23874. * A Track of keyframe values that represent color.
  23875. */
  23876. class ColorKeyframeTrack extends KeyframeTrack {}
  23877. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23878. /**
  23879. * A Track of numeric keyframe values.
  23880. */
  23881. class NumberKeyframeTrack extends KeyframeTrack {}
  23882. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23883. /**
  23884. * Spherical linear unit quaternion interpolant.
  23885. */
  23886. class QuaternionLinearInterpolant extends Interpolant {
  23887. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23888. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23889. }
  23890. interpolate_( i1, t0, t, t1 ) {
  23891. const result = this.resultBuffer,
  23892. values = this.sampleValues,
  23893. stride = this.valueSize,
  23894. alpha = ( t - t0 ) / ( t1 - t0 );
  23895. let offset = i1 * stride;
  23896. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23897. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23898. }
  23899. return result;
  23900. }
  23901. }
  23902. /**
  23903. * A Track of quaternion keyframe values.
  23904. */
  23905. class QuaternionKeyframeTrack extends KeyframeTrack {
  23906. InterpolantFactoryMethodLinear( result ) {
  23907. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23908. }
  23909. }
  23910. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23911. // ValueBufferType is inherited
  23912. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23913. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23914. /**
  23915. * A Track that interpolates Strings
  23916. */
  23917. class StringKeyframeTrack extends KeyframeTrack {}
  23918. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23919. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23920. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23921. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23922. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23923. /**
  23924. * A Track of vectored keyframe values.
  23925. */
  23926. class VectorKeyframeTrack extends KeyframeTrack {}
  23927. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23928. class AnimationClip {
  23929. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23930. this.name = name;
  23931. this.tracks = tracks;
  23932. this.duration = duration;
  23933. this.blendMode = blendMode;
  23934. this.uuid = generateUUID();
  23935. // this means it should figure out its duration by scanning the tracks
  23936. if ( this.duration < 0 ) {
  23937. this.resetDuration();
  23938. }
  23939. }
  23940. static parse( json ) {
  23941. const tracks = [],
  23942. jsonTracks = json.tracks,
  23943. frameTime = 1.0 / ( json.fps || 1.0 );
  23944. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23945. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23946. }
  23947. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23948. clip.uuid = json.uuid;
  23949. return clip;
  23950. }
  23951. static toJSON( clip ) {
  23952. const tracks = [],
  23953. clipTracks = clip.tracks;
  23954. const json = {
  23955. 'name': clip.name,
  23956. 'duration': clip.duration,
  23957. 'tracks': tracks,
  23958. 'uuid': clip.uuid,
  23959. 'blendMode': clip.blendMode
  23960. };
  23961. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23962. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23963. }
  23964. return json;
  23965. }
  23966. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23967. const numMorphTargets = morphTargetSequence.length;
  23968. const tracks = [];
  23969. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23970. let times = [];
  23971. let values = [];
  23972. times.push(
  23973. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23974. i,
  23975. ( i + 1 ) % numMorphTargets );
  23976. values.push( 0, 1, 0 );
  23977. const order = getKeyframeOrder( times );
  23978. times = sortedArray( times, 1, order );
  23979. values = sortedArray( values, 1, order );
  23980. // if there is a key at the first frame, duplicate it as the
  23981. // last frame as well for perfect loop.
  23982. if ( ! noLoop && times[ 0 ] === 0 ) {
  23983. times.push( numMorphTargets );
  23984. values.push( values[ 0 ] );
  23985. }
  23986. tracks.push(
  23987. new NumberKeyframeTrack(
  23988. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23989. times, values
  23990. ).scale( 1.0 / fps ) );
  23991. }
  23992. return new this( name, - 1, tracks );
  23993. }
  23994. static findByName( objectOrClipArray, name ) {
  23995. let clipArray = objectOrClipArray;
  23996. if ( ! Array.isArray( objectOrClipArray ) ) {
  23997. const o = objectOrClipArray;
  23998. clipArray = o.geometry && o.geometry.animations || o.animations;
  23999. }
  24000. for ( let i = 0; i < clipArray.length; i ++ ) {
  24001. if ( clipArray[ i ].name === name ) {
  24002. return clipArray[ i ];
  24003. }
  24004. }
  24005. return null;
  24006. }
  24007. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  24008. const animationToMorphTargets = {};
  24009. // tested with https://regex101.com/ on trick sequences
  24010. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  24011. const pattern = /^([\w-]*?)([\d]+)$/;
  24012. // sort morph target names into animation groups based
  24013. // patterns like Walk_001, Walk_002, Run_001, Run_002
  24014. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  24015. const morphTarget = morphTargets[ i ];
  24016. const parts = morphTarget.name.match( pattern );
  24017. if ( parts && parts.length > 1 ) {
  24018. const name = parts[ 1 ];
  24019. let animationMorphTargets = animationToMorphTargets[ name ];
  24020. if ( ! animationMorphTargets ) {
  24021. animationToMorphTargets[ name ] = animationMorphTargets = [];
  24022. }
  24023. animationMorphTargets.push( morphTarget );
  24024. }
  24025. }
  24026. const clips = [];
  24027. for ( const name in animationToMorphTargets ) {
  24028. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  24029. }
  24030. return clips;
  24031. }
  24032. // parse the animation.hierarchy format
  24033. static parseAnimation( animation, bones ) {
  24034. if ( ! animation ) {
  24035. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  24036. return null;
  24037. }
  24038. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  24039. // only return track if there are actually keys.
  24040. if ( animationKeys.length !== 0 ) {
  24041. const times = [];
  24042. const values = [];
  24043. flattenJSON( animationKeys, times, values, propertyName );
  24044. // empty keys are filtered out, so check again
  24045. if ( times.length !== 0 ) {
  24046. destTracks.push( new trackType( trackName, times, values ) );
  24047. }
  24048. }
  24049. };
  24050. const tracks = [];
  24051. const clipName = animation.name || 'default';
  24052. const fps = animation.fps || 30;
  24053. const blendMode = animation.blendMode;
  24054. // automatic length determination in AnimationClip.
  24055. let duration = animation.length || - 1;
  24056. const hierarchyTracks = animation.hierarchy || [];
  24057. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  24058. const animationKeys = hierarchyTracks[ h ].keys;
  24059. // skip empty tracks
  24060. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  24061. // process morph targets
  24062. if ( animationKeys[ 0 ].morphTargets ) {
  24063. // figure out all morph targets used in this track
  24064. const morphTargetNames = {};
  24065. let k;
  24066. for ( k = 0; k < animationKeys.length; k ++ ) {
  24067. if ( animationKeys[ k ].morphTargets ) {
  24068. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  24069. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  24070. }
  24071. }
  24072. }
  24073. // create a track for each morph target with all zero
  24074. // morphTargetInfluences except for the keys in which
  24075. // the morphTarget is named.
  24076. for ( const morphTargetName in morphTargetNames ) {
  24077. const times = [];
  24078. const values = [];
  24079. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  24080. const animationKey = animationKeys[ k ];
  24081. times.push( animationKey.time );
  24082. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  24083. }
  24084. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  24085. }
  24086. duration = morphTargetNames.length * fps;
  24087. } else {
  24088. // ...assume skeletal animation
  24089. const boneName = '.bones[' + bones[ h ].name + ']';
  24090. addNonemptyTrack(
  24091. VectorKeyframeTrack, boneName + '.position',
  24092. animationKeys, 'pos', tracks );
  24093. addNonemptyTrack(
  24094. QuaternionKeyframeTrack, boneName + '.quaternion',
  24095. animationKeys, 'rot', tracks );
  24096. addNonemptyTrack(
  24097. VectorKeyframeTrack, boneName + '.scale',
  24098. animationKeys, 'scl', tracks );
  24099. }
  24100. }
  24101. if ( tracks.length === 0 ) {
  24102. return null;
  24103. }
  24104. const clip = new this( clipName, duration, tracks, blendMode );
  24105. return clip;
  24106. }
  24107. resetDuration() {
  24108. const tracks = this.tracks;
  24109. let duration = 0;
  24110. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  24111. const track = this.tracks[ i ];
  24112. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  24113. }
  24114. this.duration = duration;
  24115. return this;
  24116. }
  24117. trim() {
  24118. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24119. this.tracks[ i ].trim( 0, this.duration );
  24120. }
  24121. return this;
  24122. }
  24123. validate() {
  24124. let valid = true;
  24125. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24126. valid = valid && this.tracks[ i ].validate();
  24127. }
  24128. return valid;
  24129. }
  24130. optimize() {
  24131. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24132. this.tracks[ i ].optimize();
  24133. }
  24134. return this;
  24135. }
  24136. clone() {
  24137. const tracks = [];
  24138. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24139. tracks.push( this.tracks[ i ].clone() );
  24140. }
  24141. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  24142. }
  24143. toJSON() {
  24144. return this.constructor.toJSON( this );
  24145. }
  24146. }
  24147. function getTrackTypeForValueTypeName( typeName ) {
  24148. switch ( typeName.toLowerCase() ) {
  24149. case 'scalar':
  24150. case 'double':
  24151. case 'float':
  24152. case 'number':
  24153. case 'integer':
  24154. return NumberKeyframeTrack;
  24155. case 'vector':
  24156. case 'vector2':
  24157. case 'vector3':
  24158. case 'vector4':
  24159. return VectorKeyframeTrack;
  24160. case 'color':
  24161. return ColorKeyframeTrack;
  24162. case 'quaternion':
  24163. return QuaternionKeyframeTrack;
  24164. case 'bool':
  24165. case 'boolean':
  24166. return BooleanKeyframeTrack;
  24167. case 'string':
  24168. return StringKeyframeTrack;
  24169. }
  24170. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  24171. }
  24172. function parseKeyframeTrack( json ) {
  24173. if ( json.type === undefined ) {
  24174. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  24175. }
  24176. const trackType = getTrackTypeForValueTypeName( json.type );
  24177. if ( json.times === undefined ) {
  24178. const times = [], values = [];
  24179. flattenJSON( json.keys, times, values, 'value' );
  24180. json.times = times;
  24181. json.values = values;
  24182. }
  24183. // derived classes can define a static parse method
  24184. if ( trackType.parse !== undefined ) {
  24185. return trackType.parse( json );
  24186. } else {
  24187. // by default, we assume a constructor compatible with the base
  24188. return new trackType( json.name, json.times, json.values, json.interpolation );
  24189. }
  24190. }
  24191. const Cache = {
  24192. enabled: false,
  24193. files: {},
  24194. add: function ( key, file ) {
  24195. if ( this.enabled === false ) return;
  24196. // console.log( 'THREE.Cache', 'Adding key:', key );
  24197. this.files[ key ] = file;
  24198. },
  24199. get: function ( key ) {
  24200. if ( this.enabled === false ) return;
  24201. // console.log( 'THREE.Cache', 'Checking key:', key );
  24202. return this.files[ key ];
  24203. },
  24204. remove: function ( key ) {
  24205. delete this.files[ key ];
  24206. },
  24207. clear: function () {
  24208. this.files = {};
  24209. }
  24210. };
  24211. class LoadingManager {
  24212. constructor( onLoad, onProgress, onError ) {
  24213. const scope = this;
  24214. let isLoading = false;
  24215. let itemsLoaded = 0;
  24216. let itemsTotal = 0;
  24217. let urlModifier = undefined;
  24218. const handlers = [];
  24219. // Refer to #5689 for the reason why we don't set .onStart
  24220. // in the constructor
  24221. this.onStart = undefined;
  24222. this.onLoad = onLoad;
  24223. this.onProgress = onProgress;
  24224. this.onError = onError;
  24225. this.itemStart = function ( url ) {
  24226. itemsTotal ++;
  24227. if ( isLoading === false ) {
  24228. if ( scope.onStart !== undefined ) {
  24229. scope.onStart( url, itemsLoaded, itemsTotal );
  24230. }
  24231. }
  24232. isLoading = true;
  24233. };
  24234. this.itemEnd = function ( url ) {
  24235. itemsLoaded ++;
  24236. if ( scope.onProgress !== undefined ) {
  24237. scope.onProgress( url, itemsLoaded, itemsTotal );
  24238. }
  24239. if ( itemsLoaded === itemsTotal ) {
  24240. isLoading = false;
  24241. if ( scope.onLoad !== undefined ) {
  24242. scope.onLoad();
  24243. }
  24244. }
  24245. };
  24246. this.itemError = function ( url ) {
  24247. if ( scope.onError !== undefined ) {
  24248. scope.onError( url );
  24249. }
  24250. };
  24251. this.resolveURL = function ( url ) {
  24252. if ( urlModifier ) {
  24253. return urlModifier( url );
  24254. }
  24255. return url;
  24256. };
  24257. this.setURLModifier = function ( transform ) {
  24258. urlModifier = transform;
  24259. return this;
  24260. };
  24261. this.addHandler = function ( regex, loader ) {
  24262. handlers.push( regex, loader );
  24263. return this;
  24264. };
  24265. this.removeHandler = function ( regex ) {
  24266. const index = handlers.indexOf( regex );
  24267. if ( index !== - 1 ) {
  24268. handlers.splice( index, 2 );
  24269. }
  24270. return this;
  24271. };
  24272. this.getHandler = function ( file ) {
  24273. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  24274. const regex = handlers[ i ];
  24275. const loader = handlers[ i + 1 ];
  24276. if ( regex.global ) regex.lastIndex = 0; // see #17920
  24277. if ( regex.test( file ) ) {
  24278. return loader;
  24279. }
  24280. }
  24281. return null;
  24282. };
  24283. }
  24284. }
  24285. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  24286. class Loader {
  24287. constructor( manager ) {
  24288. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24289. this.crossOrigin = 'anonymous';
  24290. this.withCredentials = false;
  24291. this.path = '';
  24292. this.resourcePath = '';
  24293. this.requestHeader = {};
  24294. }
  24295. load( /* url, onLoad, onProgress, onError */ ) {}
  24296. loadAsync( url, onProgress ) {
  24297. const scope = this;
  24298. return new Promise( function ( resolve, reject ) {
  24299. scope.load( url, resolve, onProgress, reject );
  24300. } );
  24301. }
  24302. parse( /* data */ ) {}
  24303. setCrossOrigin( crossOrigin ) {
  24304. this.crossOrigin = crossOrigin;
  24305. return this;
  24306. }
  24307. setWithCredentials( value ) {
  24308. this.withCredentials = value;
  24309. return this;
  24310. }
  24311. setPath( path ) {
  24312. this.path = path;
  24313. return this;
  24314. }
  24315. setResourcePath( resourcePath ) {
  24316. this.resourcePath = resourcePath;
  24317. return this;
  24318. }
  24319. setRequestHeader( requestHeader ) {
  24320. this.requestHeader = requestHeader;
  24321. return this;
  24322. }
  24323. }
  24324. const loading = {};
  24325. class HttpError extends Error {
  24326. constructor( message, response ) {
  24327. super( message );
  24328. this.response = response;
  24329. }
  24330. }
  24331. class FileLoader extends Loader {
  24332. constructor( manager ) {
  24333. super( manager );
  24334. }
  24335. load( url, onLoad, onProgress, onError ) {
  24336. if ( url === undefined ) url = '';
  24337. if ( this.path !== undefined ) url = this.path + url;
  24338. url = this.manager.resolveURL( url );
  24339. const cached = Cache.get( url );
  24340. if ( cached !== undefined ) {
  24341. this.manager.itemStart( url );
  24342. setTimeout( () => {
  24343. if ( onLoad ) onLoad( cached );
  24344. this.manager.itemEnd( url );
  24345. }, 0 );
  24346. return cached;
  24347. }
  24348. // Check if request is duplicate
  24349. if ( loading[ url ] !== undefined ) {
  24350. loading[ url ].push( {
  24351. onLoad: onLoad,
  24352. onProgress: onProgress,
  24353. onError: onError
  24354. } );
  24355. return;
  24356. }
  24357. // Initialise array for duplicate requests
  24358. loading[ url ] = [];
  24359. loading[ url ].push( {
  24360. onLoad: onLoad,
  24361. onProgress: onProgress,
  24362. onError: onError,
  24363. } );
  24364. // create request
  24365. const req = new Request( url, {
  24366. headers: new Headers( this.requestHeader ),
  24367. credentials: this.withCredentials ? 'include' : 'same-origin',
  24368. // An abort controller could be added within a future PR
  24369. } );
  24370. // record states ( avoid data race )
  24371. const mimeType = this.mimeType;
  24372. const responseType = this.responseType;
  24373. // start the fetch
  24374. fetch( req )
  24375. .then( response => {
  24376. if ( response.status === 200 || response.status === 0 ) {
  24377. // Some browsers return HTTP Status 0 when using non-http protocol
  24378. // e.g. 'file://' or 'data://'. Handle as success.
  24379. if ( response.status === 0 ) {
  24380. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24381. }
  24382. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24383. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  24384. return response;
  24385. }
  24386. const callbacks = loading[ url ];
  24387. const reader = response.body.getReader();
  24388. // Nginx needs X-File-Size check
  24389. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24390. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  24391. const total = contentLength ? parseInt( contentLength ) : 0;
  24392. const lengthComputable = total !== 0;
  24393. let loaded = 0;
  24394. // periodically read data into the new stream tracking while download progress
  24395. const stream = new ReadableStream( {
  24396. start( controller ) {
  24397. readData();
  24398. function readData() {
  24399. reader.read().then( ( { done, value } ) => {
  24400. if ( done ) {
  24401. controller.close();
  24402. } else {
  24403. loaded += value.byteLength;
  24404. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  24405. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24406. const callback = callbacks[ i ];
  24407. if ( callback.onProgress ) callback.onProgress( event );
  24408. }
  24409. controller.enqueue( value );
  24410. readData();
  24411. }
  24412. } );
  24413. }
  24414. }
  24415. } );
  24416. return new Response( stream );
  24417. } else {
  24418. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  24419. }
  24420. } )
  24421. .then( response => {
  24422. switch ( responseType ) {
  24423. case 'arraybuffer':
  24424. return response.arrayBuffer();
  24425. case 'blob':
  24426. return response.blob();
  24427. case 'document':
  24428. return response.text()
  24429. .then( text => {
  24430. const parser = new DOMParser();
  24431. return parser.parseFromString( text, mimeType );
  24432. } );
  24433. case 'json':
  24434. return response.json();
  24435. default:
  24436. if ( mimeType === undefined ) {
  24437. return response.text();
  24438. } else {
  24439. // sniff encoding
  24440. const re = /charset="?([^;"\s]*)"?/i;
  24441. const exec = re.exec( mimeType );
  24442. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  24443. const decoder = new TextDecoder( label );
  24444. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  24445. }
  24446. }
  24447. } )
  24448. .then( data => {
  24449. // Add to cache only on HTTP success, so that we do not cache
  24450. // error response bodies as proper responses to requests.
  24451. Cache.add( url, data );
  24452. const callbacks = loading[ url ];
  24453. delete loading[ url ];
  24454. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24455. const callback = callbacks[ i ];
  24456. if ( callback.onLoad ) callback.onLoad( data );
  24457. }
  24458. } )
  24459. .catch( err => {
  24460. // Abort errors and other errors are handled the same
  24461. const callbacks = loading[ url ];
  24462. if ( callbacks === undefined ) {
  24463. // When onLoad was called and url was deleted in `loading`
  24464. this.manager.itemError( url );
  24465. throw err;
  24466. }
  24467. delete loading[ url ];
  24468. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24469. const callback = callbacks[ i ];
  24470. if ( callback.onError ) callback.onError( err );
  24471. }
  24472. this.manager.itemError( url );
  24473. } )
  24474. .finally( () => {
  24475. this.manager.itemEnd( url );
  24476. } );
  24477. this.manager.itemStart( url );
  24478. }
  24479. setResponseType( value ) {
  24480. this.responseType = value;
  24481. return this;
  24482. }
  24483. setMimeType( value ) {
  24484. this.mimeType = value;
  24485. return this;
  24486. }
  24487. }
  24488. class AnimationLoader extends Loader {
  24489. constructor( manager ) {
  24490. super( manager );
  24491. }
  24492. load( url, onLoad, onProgress, onError ) {
  24493. const scope = this;
  24494. const loader = new FileLoader( this.manager );
  24495. loader.setPath( this.path );
  24496. loader.setRequestHeader( this.requestHeader );
  24497. loader.setWithCredentials( this.withCredentials );
  24498. loader.load( url, function ( text ) {
  24499. try {
  24500. onLoad( scope.parse( JSON.parse( text ) ) );
  24501. } catch ( e ) {
  24502. if ( onError ) {
  24503. onError( e );
  24504. } else {
  24505. console.error( e );
  24506. }
  24507. scope.manager.itemError( url );
  24508. }
  24509. }, onProgress, onError );
  24510. }
  24511. parse( json ) {
  24512. const animations = [];
  24513. for ( let i = 0; i < json.length; i ++ ) {
  24514. const clip = AnimationClip.parse( json[ i ] );
  24515. animations.push( clip );
  24516. }
  24517. return animations;
  24518. }
  24519. }
  24520. /**
  24521. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24522. *
  24523. * Sub classes have to implement the parse() method which will be used in load().
  24524. */
  24525. class CompressedTextureLoader extends Loader {
  24526. constructor( manager ) {
  24527. super( manager );
  24528. }
  24529. load( url, onLoad, onProgress, onError ) {
  24530. const scope = this;
  24531. const images = [];
  24532. const texture = new CompressedTexture();
  24533. const loader = new FileLoader( this.manager );
  24534. loader.setPath( this.path );
  24535. loader.setResponseType( 'arraybuffer' );
  24536. loader.setRequestHeader( this.requestHeader );
  24537. loader.setWithCredentials( scope.withCredentials );
  24538. let loaded = 0;
  24539. function loadTexture( i ) {
  24540. loader.load( url[ i ], function ( buffer ) {
  24541. const texDatas = scope.parse( buffer, true );
  24542. images[ i ] = {
  24543. width: texDatas.width,
  24544. height: texDatas.height,
  24545. format: texDatas.format,
  24546. mipmaps: texDatas.mipmaps
  24547. };
  24548. loaded += 1;
  24549. if ( loaded === 6 ) {
  24550. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24551. texture.image = images;
  24552. texture.format = texDatas.format;
  24553. texture.needsUpdate = true;
  24554. if ( onLoad ) onLoad( texture );
  24555. }
  24556. }, onProgress, onError );
  24557. }
  24558. if ( Array.isArray( url ) ) {
  24559. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24560. loadTexture( i );
  24561. }
  24562. } else {
  24563. // compressed cubemap texture stored in a single DDS file
  24564. loader.load( url, function ( buffer ) {
  24565. const texDatas = scope.parse( buffer, true );
  24566. if ( texDatas.isCubemap ) {
  24567. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24568. for ( let f = 0; f < faces; f ++ ) {
  24569. images[ f ] = { mipmaps: [] };
  24570. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24571. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24572. images[ f ].format = texDatas.format;
  24573. images[ f ].width = texDatas.width;
  24574. images[ f ].height = texDatas.height;
  24575. }
  24576. }
  24577. texture.image = images;
  24578. } else {
  24579. texture.image.width = texDatas.width;
  24580. texture.image.height = texDatas.height;
  24581. texture.mipmaps = texDatas.mipmaps;
  24582. }
  24583. if ( texDatas.mipmapCount === 1 ) {
  24584. texture.minFilter = LinearFilter;
  24585. }
  24586. texture.format = texDatas.format;
  24587. texture.needsUpdate = true;
  24588. if ( onLoad ) onLoad( texture );
  24589. }, onProgress, onError );
  24590. }
  24591. return texture;
  24592. }
  24593. }
  24594. class ImageLoader extends Loader {
  24595. constructor( manager ) {
  24596. super( manager );
  24597. }
  24598. load( url, onLoad, onProgress, onError ) {
  24599. if ( this.path !== undefined ) url = this.path + url;
  24600. url = this.manager.resolveURL( url );
  24601. const scope = this;
  24602. const cached = Cache.get( url );
  24603. if ( cached !== undefined ) {
  24604. scope.manager.itemStart( url );
  24605. setTimeout( function () {
  24606. if ( onLoad ) onLoad( cached );
  24607. scope.manager.itemEnd( url );
  24608. }, 0 );
  24609. return cached;
  24610. }
  24611. const image = createElementNS( 'img' );
  24612. function onImageLoad() {
  24613. removeEventListeners();
  24614. Cache.add( url, this );
  24615. if ( onLoad ) onLoad( this );
  24616. scope.manager.itemEnd( url );
  24617. }
  24618. function onImageError( event ) {
  24619. removeEventListeners();
  24620. if ( onError ) onError( event );
  24621. scope.manager.itemError( url );
  24622. scope.manager.itemEnd( url );
  24623. }
  24624. function removeEventListeners() {
  24625. image.removeEventListener( 'load', onImageLoad, false );
  24626. image.removeEventListener( 'error', onImageError, false );
  24627. }
  24628. image.addEventListener( 'load', onImageLoad, false );
  24629. image.addEventListener( 'error', onImageError, false );
  24630. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24631. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24632. }
  24633. scope.manager.itemStart( url );
  24634. image.src = url;
  24635. return image;
  24636. }
  24637. }
  24638. class CubeTextureLoader extends Loader {
  24639. constructor( manager ) {
  24640. super( manager );
  24641. }
  24642. load( urls, onLoad, onProgress, onError ) {
  24643. const texture = new CubeTexture();
  24644. const loader = new ImageLoader( this.manager );
  24645. loader.setCrossOrigin( this.crossOrigin );
  24646. loader.setPath( this.path );
  24647. let loaded = 0;
  24648. function loadTexture( i ) {
  24649. loader.load( urls[ i ], function ( image ) {
  24650. texture.images[ i ] = image;
  24651. loaded ++;
  24652. if ( loaded === 6 ) {
  24653. texture.needsUpdate = true;
  24654. if ( onLoad ) onLoad( texture );
  24655. }
  24656. }, undefined, onError );
  24657. }
  24658. for ( let i = 0; i < urls.length; ++ i ) {
  24659. loadTexture( i );
  24660. }
  24661. return texture;
  24662. }
  24663. }
  24664. /**
  24665. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24666. *
  24667. * Sub classes have to implement the parse() method which will be used in load().
  24668. */
  24669. class DataTextureLoader extends Loader {
  24670. constructor( manager ) {
  24671. super( manager );
  24672. }
  24673. load( url, onLoad, onProgress, onError ) {
  24674. const scope = this;
  24675. const texture = new DataTexture();
  24676. const loader = new FileLoader( this.manager );
  24677. loader.setResponseType( 'arraybuffer' );
  24678. loader.setRequestHeader( this.requestHeader );
  24679. loader.setPath( this.path );
  24680. loader.setWithCredentials( scope.withCredentials );
  24681. loader.load( url, function ( buffer ) {
  24682. const texData = scope.parse( buffer );
  24683. if ( ! texData ) return;
  24684. if ( texData.image !== undefined ) {
  24685. texture.image = texData.image;
  24686. } else if ( texData.data !== undefined ) {
  24687. texture.image.width = texData.width;
  24688. texture.image.height = texData.height;
  24689. texture.image.data = texData.data;
  24690. }
  24691. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24692. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24693. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24694. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24695. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24696. if ( texData.encoding !== undefined ) {
  24697. texture.encoding = texData.encoding;
  24698. }
  24699. if ( texData.flipY !== undefined ) {
  24700. texture.flipY = texData.flipY;
  24701. }
  24702. if ( texData.format !== undefined ) {
  24703. texture.format = texData.format;
  24704. }
  24705. if ( texData.type !== undefined ) {
  24706. texture.type = texData.type;
  24707. }
  24708. if ( texData.mipmaps !== undefined ) {
  24709. texture.mipmaps = texData.mipmaps;
  24710. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24711. }
  24712. if ( texData.mipmapCount === 1 ) {
  24713. texture.minFilter = LinearFilter;
  24714. }
  24715. if ( texData.generateMipmaps !== undefined ) {
  24716. texture.generateMipmaps = texData.generateMipmaps;
  24717. }
  24718. texture.needsUpdate = true;
  24719. if ( onLoad ) onLoad( texture, texData );
  24720. }, onProgress, onError );
  24721. return texture;
  24722. }
  24723. }
  24724. class TextureLoader extends Loader {
  24725. constructor( manager ) {
  24726. super( manager );
  24727. }
  24728. load( url, onLoad, onProgress, onError ) {
  24729. const texture = new Texture();
  24730. const loader = new ImageLoader( this.manager );
  24731. loader.setCrossOrigin( this.crossOrigin );
  24732. loader.setPath( this.path );
  24733. loader.load( url, function ( image ) {
  24734. texture.image = image;
  24735. texture.needsUpdate = true;
  24736. if ( onLoad !== undefined ) {
  24737. onLoad( texture );
  24738. }
  24739. }, onProgress, onError );
  24740. return texture;
  24741. }
  24742. }
  24743. class Light extends Object3D {
  24744. constructor( color, intensity = 1 ) {
  24745. super();
  24746. this.isLight = true;
  24747. this.type = 'Light';
  24748. this.color = new Color( color );
  24749. this.intensity = intensity;
  24750. }
  24751. dispose() {
  24752. // Empty here in base class; some subclasses override.
  24753. }
  24754. copy( source, recursive ) {
  24755. super.copy( source, recursive );
  24756. this.color.copy( source.color );
  24757. this.intensity = source.intensity;
  24758. return this;
  24759. }
  24760. toJSON( meta ) {
  24761. const data = super.toJSON( meta );
  24762. data.object.color = this.color.getHex();
  24763. data.object.intensity = this.intensity;
  24764. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24765. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24766. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24767. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24768. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24769. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24770. return data;
  24771. }
  24772. }
  24773. class HemisphereLight extends Light {
  24774. constructor( skyColor, groundColor, intensity ) {
  24775. super( skyColor, intensity );
  24776. this.isHemisphereLight = true;
  24777. this.type = 'HemisphereLight';
  24778. this.position.copy( Object3D.DEFAULT_UP );
  24779. this.updateMatrix();
  24780. this.groundColor = new Color( groundColor );
  24781. }
  24782. copy( source, recursive ) {
  24783. super.copy( source, recursive );
  24784. this.groundColor.copy( source.groundColor );
  24785. return this;
  24786. }
  24787. }
  24788. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24789. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24790. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24791. class LightShadow {
  24792. constructor( camera ) {
  24793. this.camera = camera;
  24794. this.bias = 0;
  24795. this.normalBias = 0;
  24796. this.radius = 1;
  24797. this.blurSamples = 8;
  24798. this.mapSize = new Vector2( 512, 512 );
  24799. this.map = null;
  24800. this.mapPass = null;
  24801. this.matrix = new Matrix4();
  24802. this.autoUpdate = true;
  24803. this.needsUpdate = false;
  24804. this._frustum = new Frustum();
  24805. this._frameExtents = new Vector2( 1, 1 );
  24806. this._viewportCount = 1;
  24807. this._viewports = [
  24808. new Vector4( 0, 0, 1, 1 )
  24809. ];
  24810. }
  24811. getViewportCount() {
  24812. return this._viewportCount;
  24813. }
  24814. getFrustum() {
  24815. return this._frustum;
  24816. }
  24817. updateMatrices( light ) {
  24818. const shadowCamera = this.camera;
  24819. const shadowMatrix = this.matrix;
  24820. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24821. shadowCamera.position.copy( _lightPositionWorld$1 );
  24822. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24823. shadowCamera.lookAt( _lookTarget$1 );
  24824. shadowCamera.updateMatrixWorld();
  24825. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24826. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24827. shadowMatrix.set(
  24828. 0.5, 0.0, 0.0, 0.5,
  24829. 0.0, 0.5, 0.0, 0.5,
  24830. 0.0, 0.0, 0.5, 0.5,
  24831. 0.0, 0.0, 0.0, 1.0
  24832. );
  24833. shadowMatrix.multiply( _projScreenMatrix$1 );
  24834. }
  24835. getViewport( viewportIndex ) {
  24836. return this._viewports[ viewportIndex ];
  24837. }
  24838. getFrameExtents() {
  24839. return this._frameExtents;
  24840. }
  24841. dispose() {
  24842. if ( this.map ) {
  24843. this.map.dispose();
  24844. }
  24845. if ( this.mapPass ) {
  24846. this.mapPass.dispose();
  24847. }
  24848. }
  24849. copy( source ) {
  24850. this.camera = source.camera.clone();
  24851. this.bias = source.bias;
  24852. this.radius = source.radius;
  24853. this.mapSize.copy( source.mapSize );
  24854. return this;
  24855. }
  24856. clone() {
  24857. return new this.constructor().copy( this );
  24858. }
  24859. toJSON() {
  24860. const object = {};
  24861. if ( this.bias !== 0 ) object.bias = this.bias;
  24862. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24863. if ( this.radius !== 1 ) object.radius = this.radius;
  24864. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24865. object.camera = this.camera.toJSON( false ).object;
  24866. delete object.camera.matrix;
  24867. return object;
  24868. }
  24869. }
  24870. class SpotLightShadow extends LightShadow {
  24871. constructor() {
  24872. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24873. this.isSpotLightShadow = true;
  24874. this.focus = 1;
  24875. }
  24876. updateMatrices( light ) {
  24877. const camera = this.camera;
  24878. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24879. const aspect = this.mapSize.width / this.mapSize.height;
  24880. const far = light.distance || camera.far;
  24881. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24882. camera.fov = fov;
  24883. camera.aspect = aspect;
  24884. camera.far = far;
  24885. camera.updateProjectionMatrix();
  24886. }
  24887. super.updateMatrices( light );
  24888. }
  24889. copy( source ) {
  24890. super.copy( source );
  24891. this.focus = source.focus;
  24892. return this;
  24893. }
  24894. }
  24895. class SpotLight extends Light {
  24896. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  24897. super( color, intensity );
  24898. this.isSpotLight = true;
  24899. this.type = 'SpotLight';
  24900. this.position.copy( Object3D.DEFAULT_UP );
  24901. this.updateMatrix();
  24902. this.target = new Object3D();
  24903. this.distance = distance;
  24904. this.angle = angle;
  24905. this.penumbra = penumbra;
  24906. this.decay = decay;
  24907. this.map = null;
  24908. this.shadow = new SpotLightShadow();
  24909. }
  24910. get power() {
  24911. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24912. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24913. return this.intensity * Math.PI;
  24914. }
  24915. set power( power ) {
  24916. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24917. this.intensity = power / Math.PI;
  24918. }
  24919. dispose() {
  24920. this.shadow.dispose();
  24921. }
  24922. copy( source, recursive ) {
  24923. super.copy( source, recursive );
  24924. this.distance = source.distance;
  24925. this.angle = source.angle;
  24926. this.penumbra = source.penumbra;
  24927. this.decay = source.decay;
  24928. this.target = source.target.clone();
  24929. this.shadow = source.shadow.clone();
  24930. return this;
  24931. }
  24932. }
  24933. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24934. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24935. const _lookTarget = /*@__PURE__*/ new Vector3();
  24936. class PointLightShadow extends LightShadow {
  24937. constructor() {
  24938. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24939. this.isPointLightShadow = true;
  24940. this._frameExtents = new Vector2( 4, 2 );
  24941. this._viewportCount = 6;
  24942. this._viewports = [
  24943. // These viewports map a cube-map onto a 2D texture with the
  24944. // following orientation:
  24945. //
  24946. // xzXZ
  24947. // y Y
  24948. //
  24949. // X - Positive x direction
  24950. // x - Negative x direction
  24951. // Y - Positive y direction
  24952. // y - Negative y direction
  24953. // Z - Positive z direction
  24954. // z - Negative z direction
  24955. // positive X
  24956. new Vector4( 2, 1, 1, 1 ),
  24957. // negative X
  24958. new Vector4( 0, 1, 1, 1 ),
  24959. // positive Z
  24960. new Vector4( 3, 1, 1, 1 ),
  24961. // negative Z
  24962. new Vector4( 1, 1, 1, 1 ),
  24963. // positive Y
  24964. new Vector4( 3, 0, 1, 1 ),
  24965. // negative Y
  24966. new Vector4( 1, 0, 1, 1 )
  24967. ];
  24968. this._cubeDirections = [
  24969. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24970. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24971. ];
  24972. this._cubeUps = [
  24973. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24974. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24975. ];
  24976. }
  24977. updateMatrices( light, viewportIndex = 0 ) {
  24978. const camera = this.camera;
  24979. const shadowMatrix = this.matrix;
  24980. const far = light.distance || camera.far;
  24981. if ( far !== camera.far ) {
  24982. camera.far = far;
  24983. camera.updateProjectionMatrix();
  24984. }
  24985. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24986. camera.position.copy( _lightPositionWorld );
  24987. _lookTarget.copy( camera.position );
  24988. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24989. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24990. camera.lookAt( _lookTarget );
  24991. camera.updateMatrixWorld();
  24992. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24993. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24994. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24995. }
  24996. }
  24997. class PointLight extends Light {
  24998. constructor( color, intensity, distance = 0, decay = 2 ) {
  24999. super( color, intensity );
  25000. this.isPointLight = true;
  25001. this.type = 'PointLight';
  25002. this.distance = distance;
  25003. this.decay = decay;
  25004. this.shadow = new PointLightShadow();
  25005. }
  25006. get power() {
  25007. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25008. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  25009. return this.intensity * 4 * Math.PI;
  25010. }
  25011. set power( power ) {
  25012. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25013. this.intensity = power / ( 4 * Math.PI );
  25014. }
  25015. dispose() {
  25016. this.shadow.dispose();
  25017. }
  25018. copy( source, recursive ) {
  25019. super.copy( source, recursive );
  25020. this.distance = source.distance;
  25021. this.decay = source.decay;
  25022. this.shadow = source.shadow.clone();
  25023. return this;
  25024. }
  25025. }
  25026. class DirectionalLightShadow extends LightShadow {
  25027. constructor() {
  25028. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  25029. this.isDirectionalLightShadow = true;
  25030. }
  25031. }
  25032. class DirectionalLight extends Light {
  25033. constructor( color, intensity ) {
  25034. super( color, intensity );
  25035. this.isDirectionalLight = true;
  25036. this.type = 'DirectionalLight';
  25037. this.position.copy( Object3D.DEFAULT_UP );
  25038. this.updateMatrix();
  25039. this.target = new Object3D();
  25040. this.shadow = new DirectionalLightShadow();
  25041. }
  25042. dispose() {
  25043. this.shadow.dispose();
  25044. }
  25045. copy( source ) {
  25046. super.copy( source );
  25047. this.target = source.target.clone();
  25048. this.shadow = source.shadow.clone();
  25049. return this;
  25050. }
  25051. }
  25052. class AmbientLight extends Light {
  25053. constructor( color, intensity ) {
  25054. super( color, intensity );
  25055. this.isAmbientLight = true;
  25056. this.type = 'AmbientLight';
  25057. }
  25058. }
  25059. class RectAreaLight extends Light {
  25060. constructor( color, intensity, width = 10, height = 10 ) {
  25061. super( color, intensity );
  25062. this.isRectAreaLight = true;
  25063. this.type = 'RectAreaLight';
  25064. this.width = width;
  25065. this.height = height;
  25066. }
  25067. get power() {
  25068. // compute the light's luminous power (in lumens) from its intensity (in nits)
  25069. return this.intensity * this.width * this.height * Math.PI;
  25070. }
  25071. set power( power ) {
  25072. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  25073. this.intensity = power / ( this.width * this.height * Math.PI );
  25074. }
  25075. copy( source ) {
  25076. super.copy( source );
  25077. this.width = source.width;
  25078. this.height = source.height;
  25079. return this;
  25080. }
  25081. toJSON( meta ) {
  25082. const data = super.toJSON( meta );
  25083. data.object.width = this.width;
  25084. data.object.height = this.height;
  25085. return data;
  25086. }
  25087. }
  25088. /**
  25089. * Primary reference:
  25090. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25091. *
  25092. * Secondary reference:
  25093. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25094. */
  25095. // 3-band SH defined by 9 coefficients
  25096. class SphericalHarmonics3 {
  25097. constructor() {
  25098. this.isSphericalHarmonics3 = true;
  25099. this.coefficients = [];
  25100. for ( let i = 0; i < 9; i ++ ) {
  25101. this.coefficients.push( new Vector3() );
  25102. }
  25103. }
  25104. set( coefficients ) {
  25105. for ( let i = 0; i < 9; i ++ ) {
  25106. this.coefficients[ i ].copy( coefficients[ i ] );
  25107. }
  25108. return this;
  25109. }
  25110. zero() {
  25111. for ( let i = 0; i < 9; i ++ ) {
  25112. this.coefficients[ i ].set( 0, 0, 0 );
  25113. }
  25114. return this;
  25115. }
  25116. // get the radiance in the direction of the normal
  25117. // target is a Vector3
  25118. getAt( normal, target ) {
  25119. // normal is assumed to be unit length
  25120. const x = normal.x, y = normal.y, z = normal.z;
  25121. const coeff = this.coefficients;
  25122. // band 0
  25123. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  25124. // band 1
  25125. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  25126. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  25127. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  25128. // band 2
  25129. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  25130. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  25131. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  25132. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  25133. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  25134. return target;
  25135. }
  25136. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25137. // target is a Vector3
  25138. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25139. getIrradianceAt( normal, target ) {
  25140. // normal is assumed to be unit length
  25141. const x = normal.x, y = normal.y, z = normal.z;
  25142. const coeff = this.coefficients;
  25143. // band 0
  25144. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  25145. // band 1
  25146. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  25147. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  25148. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  25149. // band 2
  25150. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  25151. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  25152. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  25153. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  25154. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  25155. return target;
  25156. }
  25157. add( sh ) {
  25158. for ( let i = 0; i < 9; i ++ ) {
  25159. this.coefficients[ i ].add( sh.coefficients[ i ] );
  25160. }
  25161. return this;
  25162. }
  25163. addScaledSH( sh, s ) {
  25164. for ( let i = 0; i < 9; i ++ ) {
  25165. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  25166. }
  25167. return this;
  25168. }
  25169. scale( s ) {
  25170. for ( let i = 0; i < 9; i ++ ) {
  25171. this.coefficients[ i ].multiplyScalar( s );
  25172. }
  25173. return this;
  25174. }
  25175. lerp( sh, alpha ) {
  25176. for ( let i = 0; i < 9; i ++ ) {
  25177. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  25178. }
  25179. return this;
  25180. }
  25181. equals( sh ) {
  25182. for ( let i = 0; i < 9; i ++ ) {
  25183. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  25184. return false;
  25185. }
  25186. }
  25187. return true;
  25188. }
  25189. copy( sh ) {
  25190. return this.set( sh.coefficients );
  25191. }
  25192. clone() {
  25193. return new this.constructor().copy( this );
  25194. }
  25195. fromArray( array, offset = 0 ) {
  25196. const coefficients = this.coefficients;
  25197. for ( let i = 0; i < 9; i ++ ) {
  25198. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  25199. }
  25200. return this;
  25201. }
  25202. toArray( array = [], offset = 0 ) {
  25203. const coefficients = this.coefficients;
  25204. for ( let i = 0; i < 9; i ++ ) {
  25205. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  25206. }
  25207. return array;
  25208. }
  25209. // evaluate the basis functions
  25210. // shBasis is an Array[ 9 ]
  25211. static getBasisAt( normal, shBasis ) {
  25212. // normal is assumed to be unit length
  25213. const x = normal.x, y = normal.y, z = normal.z;
  25214. // band 0
  25215. shBasis[ 0 ] = 0.282095;
  25216. // band 1
  25217. shBasis[ 1 ] = 0.488603 * y;
  25218. shBasis[ 2 ] = 0.488603 * z;
  25219. shBasis[ 3 ] = 0.488603 * x;
  25220. // band 2
  25221. shBasis[ 4 ] = 1.092548 * x * y;
  25222. shBasis[ 5 ] = 1.092548 * y * z;
  25223. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  25224. shBasis[ 7 ] = 1.092548 * x * z;
  25225. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  25226. }
  25227. }
  25228. class LightProbe extends Light {
  25229. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  25230. super( undefined, intensity );
  25231. this.isLightProbe = true;
  25232. this.sh = sh;
  25233. }
  25234. copy( source ) {
  25235. super.copy( source );
  25236. this.sh.copy( source.sh );
  25237. return this;
  25238. }
  25239. fromJSON( json ) {
  25240. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  25241. this.sh.fromArray( json.sh );
  25242. return this;
  25243. }
  25244. toJSON( meta ) {
  25245. const data = super.toJSON( meta );
  25246. data.object.sh = this.sh.toArray();
  25247. return data;
  25248. }
  25249. }
  25250. class MaterialLoader extends Loader {
  25251. constructor( manager ) {
  25252. super( manager );
  25253. this.textures = {};
  25254. }
  25255. load( url, onLoad, onProgress, onError ) {
  25256. const scope = this;
  25257. const loader = new FileLoader( scope.manager );
  25258. loader.setPath( scope.path );
  25259. loader.setRequestHeader( scope.requestHeader );
  25260. loader.setWithCredentials( scope.withCredentials );
  25261. loader.load( url, function ( text ) {
  25262. try {
  25263. onLoad( scope.parse( JSON.parse( text ) ) );
  25264. } catch ( e ) {
  25265. if ( onError ) {
  25266. onError( e );
  25267. } else {
  25268. console.error( e );
  25269. }
  25270. scope.manager.itemError( url );
  25271. }
  25272. }, onProgress, onError );
  25273. }
  25274. parse( json ) {
  25275. const textures = this.textures;
  25276. function getTexture( name ) {
  25277. if ( textures[ name ] === undefined ) {
  25278. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25279. }
  25280. return textures[ name ];
  25281. }
  25282. const material = MaterialLoader.createMaterialFromType( json.type );
  25283. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25284. if ( json.name !== undefined ) material.name = json.name;
  25285. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  25286. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25287. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25288. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  25289. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  25290. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  25291. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25292. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  25293. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  25294. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  25295. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25296. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  25297. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  25298. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  25299. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  25300. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  25301. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  25302. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  25303. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  25304. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  25305. if ( json.fog !== undefined ) material.fog = json.fog;
  25306. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25307. if ( json.blending !== undefined ) material.blending = json.blending;
  25308. if ( json.combine !== undefined ) material.combine = json.combine;
  25309. if ( json.side !== undefined ) material.side = json.side;
  25310. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  25311. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25312. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25313. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25314. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25315. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25316. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25317. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  25318. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  25319. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  25320. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  25321. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  25322. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  25323. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  25324. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  25325. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25326. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25327. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25328. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25329. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25330. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25331. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25332. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25333. if ( json.scale !== undefined ) material.scale = json.scale;
  25334. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25335. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25336. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25337. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25338. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  25339. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  25340. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  25341. if ( json.visible !== undefined ) material.visible = json.visible;
  25342. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  25343. if ( json.userData !== undefined ) material.userData = json.userData;
  25344. if ( json.vertexColors !== undefined ) {
  25345. if ( typeof json.vertexColors === 'number' ) {
  25346. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  25347. } else {
  25348. material.vertexColors = json.vertexColors;
  25349. }
  25350. }
  25351. // Shader Material
  25352. if ( json.uniforms !== undefined ) {
  25353. for ( const name in json.uniforms ) {
  25354. const uniform = json.uniforms[ name ];
  25355. material.uniforms[ name ] = {};
  25356. switch ( uniform.type ) {
  25357. case 't':
  25358. material.uniforms[ name ].value = getTexture( uniform.value );
  25359. break;
  25360. case 'c':
  25361. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  25362. break;
  25363. case 'v2':
  25364. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  25365. break;
  25366. case 'v3':
  25367. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  25368. break;
  25369. case 'v4':
  25370. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  25371. break;
  25372. case 'm3':
  25373. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  25374. break;
  25375. case 'm4':
  25376. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  25377. break;
  25378. default:
  25379. material.uniforms[ name ].value = uniform.value;
  25380. }
  25381. }
  25382. }
  25383. if ( json.defines !== undefined ) material.defines = json.defines;
  25384. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25385. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25386. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  25387. if ( json.extensions !== undefined ) {
  25388. for ( const key in json.extensions ) {
  25389. material.extensions[ key ] = json.extensions[ key ];
  25390. }
  25391. }
  25392. // for PointsMaterial
  25393. if ( json.size !== undefined ) material.size = json.size;
  25394. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25395. // maps
  25396. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25397. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  25398. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  25399. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25400. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25401. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25402. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25403. if ( json.normalScale !== undefined ) {
  25404. let normalScale = json.normalScale;
  25405. if ( Array.isArray( normalScale ) === false ) {
  25406. // Blender exporter used to export a scalar. See #7459
  25407. normalScale = [ normalScale, normalScale ];
  25408. }
  25409. material.normalScale = new Vector2().fromArray( normalScale );
  25410. }
  25411. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25412. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25413. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25414. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25415. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25416. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25417. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25418. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25419. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  25420. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  25421. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25422. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  25423. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25424. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  25425. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25426. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25427. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25428. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25429. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25430. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  25431. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  25432. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  25433. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  25434. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  25435. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  25436. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  25437. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  25438. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  25439. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  25440. return material;
  25441. }
  25442. setTextures( value ) {
  25443. this.textures = value;
  25444. return this;
  25445. }
  25446. static createMaterialFromType( type ) {
  25447. const materialLib = {
  25448. ShadowMaterial,
  25449. SpriteMaterial,
  25450. RawShaderMaterial,
  25451. ShaderMaterial,
  25452. PointsMaterial,
  25453. MeshPhysicalMaterial,
  25454. MeshStandardMaterial,
  25455. MeshPhongMaterial,
  25456. MeshToonMaterial,
  25457. MeshNormalMaterial,
  25458. MeshLambertMaterial,
  25459. MeshDepthMaterial,
  25460. MeshDistanceMaterial,
  25461. MeshBasicMaterial,
  25462. MeshMatcapMaterial,
  25463. LineDashedMaterial,
  25464. LineBasicMaterial,
  25465. Material
  25466. };
  25467. return new materialLib[ type ]();
  25468. }
  25469. }
  25470. class LoaderUtils {
  25471. static decodeText( array ) {
  25472. if ( typeof TextDecoder !== 'undefined' ) {
  25473. return new TextDecoder().decode( array );
  25474. }
  25475. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25476. // throws a "maximum call stack size exceeded" error for large arrays.
  25477. let s = '';
  25478. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25479. // Implicitly assumes little-endian.
  25480. s += String.fromCharCode( array[ i ] );
  25481. }
  25482. try {
  25483. // merges multi-byte utf-8 characters.
  25484. return decodeURIComponent( escape( s ) );
  25485. } catch ( e ) { // see #16358
  25486. return s;
  25487. }
  25488. }
  25489. static extractUrlBase( url ) {
  25490. const index = url.lastIndexOf( '/' );
  25491. if ( index === - 1 ) return './';
  25492. return url.slice( 0, index + 1 );
  25493. }
  25494. static resolveURL( url, path ) {
  25495. // Invalid URL
  25496. if ( typeof url !== 'string' || url === '' ) return '';
  25497. // Host Relative URL
  25498. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25499. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25500. }
  25501. // Absolute URL http://,https://,//
  25502. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25503. // Data URI
  25504. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25505. // Blob URL
  25506. if ( /^blob:.*$/i.test( url ) ) return url;
  25507. // Relative URL
  25508. return path + url;
  25509. }
  25510. }
  25511. class InstancedBufferGeometry extends BufferGeometry {
  25512. constructor() {
  25513. super();
  25514. this.isInstancedBufferGeometry = true;
  25515. this.type = 'InstancedBufferGeometry';
  25516. this.instanceCount = Infinity;
  25517. }
  25518. copy( source ) {
  25519. super.copy( source );
  25520. this.instanceCount = source.instanceCount;
  25521. return this;
  25522. }
  25523. toJSON() {
  25524. const data = super.toJSON();
  25525. data.instanceCount = this.instanceCount;
  25526. data.isInstancedBufferGeometry = true;
  25527. return data;
  25528. }
  25529. }
  25530. class BufferGeometryLoader extends Loader {
  25531. constructor( manager ) {
  25532. super( manager );
  25533. }
  25534. load( url, onLoad, onProgress, onError ) {
  25535. const scope = this;
  25536. const loader = new FileLoader( scope.manager );
  25537. loader.setPath( scope.path );
  25538. loader.setRequestHeader( scope.requestHeader );
  25539. loader.setWithCredentials( scope.withCredentials );
  25540. loader.load( url, function ( text ) {
  25541. try {
  25542. onLoad( scope.parse( JSON.parse( text ) ) );
  25543. } catch ( e ) {
  25544. if ( onError ) {
  25545. onError( e );
  25546. } else {
  25547. console.error( e );
  25548. }
  25549. scope.manager.itemError( url );
  25550. }
  25551. }, onProgress, onError );
  25552. }
  25553. parse( json ) {
  25554. const interleavedBufferMap = {};
  25555. const arrayBufferMap = {};
  25556. function getInterleavedBuffer( json, uuid ) {
  25557. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25558. const interleavedBuffers = json.interleavedBuffers;
  25559. const interleavedBuffer = interleavedBuffers[ uuid ];
  25560. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25561. const array = getTypedArray( interleavedBuffer.type, buffer );
  25562. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25563. ib.uuid = interleavedBuffer.uuid;
  25564. interleavedBufferMap[ uuid ] = ib;
  25565. return ib;
  25566. }
  25567. function getArrayBuffer( json, uuid ) {
  25568. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25569. const arrayBuffers = json.arrayBuffers;
  25570. const arrayBuffer = arrayBuffers[ uuid ];
  25571. const ab = new Uint32Array( arrayBuffer ).buffer;
  25572. arrayBufferMap[ uuid ] = ab;
  25573. return ab;
  25574. }
  25575. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25576. const index = json.data.index;
  25577. if ( index !== undefined ) {
  25578. const typedArray = getTypedArray( index.type, index.array );
  25579. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25580. }
  25581. const attributes = json.data.attributes;
  25582. for ( const key in attributes ) {
  25583. const attribute = attributes[ key ];
  25584. let bufferAttribute;
  25585. if ( attribute.isInterleavedBufferAttribute ) {
  25586. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25587. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25588. } else {
  25589. const typedArray = getTypedArray( attribute.type, attribute.array );
  25590. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25591. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25592. }
  25593. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25594. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25595. if ( attribute.updateRange !== undefined ) {
  25596. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25597. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25598. }
  25599. geometry.setAttribute( key, bufferAttribute );
  25600. }
  25601. const morphAttributes = json.data.morphAttributes;
  25602. if ( morphAttributes ) {
  25603. for ( const key in morphAttributes ) {
  25604. const attributeArray = morphAttributes[ key ];
  25605. const array = [];
  25606. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25607. const attribute = attributeArray[ i ];
  25608. let bufferAttribute;
  25609. if ( attribute.isInterleavedBufferAttribute ) {
  25610. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25611. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25612. } else {
  25613. const typedArray = getTypedArray( attribute.type, attribute.array );
  25614. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25615. }
  25616. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25617. array.push( bufferAttribute );
  25618. }
  25619. geometry.morphAttributes[ key ] = array;
  25620. }
  25621. }
  25622. const morphTargetsRelative = json.data.morphTargetsRelative;
  25623. if ( morphTargetsRelative ) {
  25624. geometry.morphTargetsRelative = true;
  25625. }
  25626. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25627. if ( groups !== undefined ) {
  25628. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25629. const group = groups[ i ];
  25630. geometry.addGroup( group.start, group.count, group.materialIndex );
  25631. }
  25632. }
  25633. const boundingSphere = json.data.boundingSphere;
  25634. if ( boundingSphere !== undefined ) {
  25635. const center = new Vector3();
  25636. if ( boundingSphere.center !== undefined ) {
  25637. center.fromArray( boundingSphere.center );
  25638. }
  25639. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25640. }
  25641. if ( json.name ) geometry.name = json.name;
  25642. if ( json.userData ) geometry.userData = json.userData;
  25643. return geometry;
  25644. }
  25645. }
  25646. class ObjectLoader extends Loader {
  25647. constructor( manager ) {
  25648. super( manager );
  25649. }
  25650. load( url, onLoad, onProgress, onError ) {
  25651. const scope = this;
  25652. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25653. this.resourcePath = this.resourcePath || path;
  25654. const loader = new FileLoader( this.manager );
  25655. loader.setPath( this.path );
  25656. loader.setRequestHeader( this.requestHeader );
  25657. loader.setWithCredentials( this.withCredentials );
  25658. loader.load( url, function ( text ) {
  25659. let json = null;
  25660. try {
  25661. json = JSON.parse( text );
  25662. } catch ( error ) {
  25663. if ( onError !== undefined ) onError( error );
  25664. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25665. return;
  25666. }
  25667. const metadata = json.metadata;
  25668. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25669. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  25670. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25671. return;
  25672. }
  25673. scope.parse( json, onLoad );
  25674. }, onProgress, onError );
  25675. }
  25676. async loadAsync( url, onProgress ) {
  25677. const scope = this;
  25678. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25679. this.resourcePath = this.resourcePath || path;
  25680. const loader = new FileLoader( this.manager );
  25681. loader.setPath( this.path );
  25682. loader.setRequestHeader( this.requestHeader );
  25683. loader.setWithCredentials( this.withCredentials );
  25684. const text = await loader.loadAsync( url, onProgress );
  25685. const json = JSON.parse( text );
  25686. const metadata = json.metadata;
  25687. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25688. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25689. }
  25690. return await scope.parseAsync( json );
  25691. }
  25692. parse( json, onLoad ) {
  25693. const animations = this.parseAnimations( json.animations );
  25694. const shapes = this.parseShapes( json.shapes );
  25695. const geometries = this.parseGeometries( json.geometries, shapes );
  25696. const images = this.parseImages( json.images, function () {
  25697. if ( onLoad !== undefined ) onLoad( object );
  25698. } );
  25699. const textures = this.parseTextures( json.textures, images );
  25700. const materials = this.parseMaterials( json.materials, textures );
  25701. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25702. const skeletons = this.parseSkeletons( json.skeletons, object );
  25703. this.bindSkeletons( object, skeletons );
  25704. //
  25705. if ( onLoad !== undefined ) {
  25706. let hasImages = false;
  25707. for ( const uuid in images ) {
  25708. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  25709. hasImages = true;
  25710. break;
  25711. }
  25712. }
  25713. if ( hasImages === false ) onLoad( object );
  25714. }
  25715. return object;
  25716. }
  25717. async parseAsync( json ) {
  25718. const animations = this.parseAnimations( json.animations );
  25719. const shapes = this.parseShapes( json.shapes );
  25720. const geometries = this.parseGeometries( json.geometries, shapes );
  25721. const images = await this.parseImagesAsync( json.images );
  25722. const textures = this.parseTextures( json.textures, images );
  25723. const materials = this.parseMaterials( json.materials, textures );
  25724. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25725. const skeletons = this.parseSkeletons( json.skeletons, object );
  25726. this.bindSkeletons( object, skeletons );
  25727. return object;
  25728. }
  25729. parseShapes( json ) {
  25730. const shapes = {};
  25731. if ( json !== undefined ) {
  25732. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25733. const shape = new Shape().fromJSON( json[ i ] );
  25734. shapes[ shape.uuid ] = shape;
  25735. }
  25736. }
  25737. return shapes;
  25738. }
  25739. parseSkeletons( json, object ) {
  25740. const skeletons = {};
  25741. const bones = {};
  25742. // generate bone lookup table
  25743. object.traverse( function ( child ) {
  25744. if ( child.isBone ) bones[ child.uuid ] = child;
  25745. } );
  25746. // create skeletons
  25747. if ( json !== undefined ) {
  25748. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25749. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25750. skeletons[ skeleton.uuid ] = skeleton;
  25751. }
  25752. }
  25753. return skeletons;
  25754. }
  25755. parseGeometries( json, shapes ) {
  25756. const geometries = {};
  25757. if ( json !== undefined ) {
  25758. const bufferGeometryLoader = new BufferGeometryLoader();
  25759. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25760. let geometry;
  25761. const data = json[ i ];
  25762. switch ( data.type ) {
  25763. case 'BufferGeometry':
  25764. case 'InstancedBufferGeometry':
  25765. geometry = bufferGeometryLoader.parse( data );
  25766. break;
  25767. default:
  25768. if ( data.type in Geometries ) {
  25769. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25770. } else {
  25771. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25772. }
  25773. }
  25774. geometry.uuid = data.uuid;
  25775. if ( data.name !== undefined ) geometry.name = data.name;
  25776. if ( data.userData !== undefined ) geometry.userData = data.userData;
  25777. geometries[ data.uuid ] = geometry;
  25778. }
  25779. }
  25780. return geometries;
  25781. }
  25782. parseMaterials( json, textures ) {
  25783. const cache = {}; // MultiMaterial
  25784. const materials = {};
  25785. if ( json !== undefined ) {
  25786. const loader = new MaterialLoader();
  25787. loader.setTextures( textures );
  25788. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25789. const data = json[ i ];
  25790. if ( cache[ data.uuid ] === undefined ) {
  25791. cache[ data.uuid ] = loader.parse( data );
  25792. }
  25793. materials[ data.uuid ] = cache[ data.uuid ];
  25794. }
  25795. }
  25796. return materials;
  25797. }
  25798. parseAnimations( json ) {
  25799. const animations = {};
  25800. if ( json !== undefined ) {
  25801. for ( let i = 0; i < json.length; i ++ ) {
  25802. const data = json[ i ];
  25803. const clip = AnimationClip.parse( data );
  25804. animations[ clip.uuid ] = clip;
  25805. }
  25806. }
  25807. return animations;
  25808. }
  25809. parseImages( json, onLoad ) {
  25810. const scope = this;
  25811. const images = {};
  25812. let loader;
  25813. function loadImage( url ) {
  25814. scope.manager.itemStart( url );
  25815. return loader.load( url, function () {
  25816. scope.manager.itemEnd( url );
  25817. }, undefined, function () {
  25818. scope.manager.itemError( url );
  25819. scope.manager.itemEnd( url );
  25820. } );
  25821. }
  25822. function deserializeImage( image ) {
  25823. if ( typeof image === 'string' ) {
  25824. const url = image;
  25825. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25826. return loadImage( path );
  25827. } else {
  25828. if ( image.data ) {
  25829. return {
  25830. data: getTypedArray( image.type, image.data ),
  25831. width: image.width,
  25832. height: image.height
  25833. };
  25834. } else {
  25835. return null;
  25836. }
  25837. }
  25838. }
  25839. if ( json !== undefined && json.length > 0 ) {
  25840. const manager = new LoadingManager( onLoad );
  25841. loader = new ImageLoader( manager );
  25842. loader.setCrossOrigin( this.crossOrigin );
  25843. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25844. const image = json[ i ];
  25845. const url = image.url;
  25846. if ( Array.isArray( url ) ) {
  25847. // load array of images e.g CubeTexture
  25848. const imageArray = [];
  25849. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25850. const currentUrl = url[ j ];
  25851. const deserializedImage = deserializeImage( currentUrl );
  25852. if ( deserializedImage !== null ) {
  25853. if ( deserializedImage instanceof HTMLImageElement ) {
  25854. imageArray.push( deserializedImage );
  25855. } else {
  25856. // special case: handle array of data textures for cube textures
  25857. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25858. }
  25859. }
  25860. }
  25861. images[ image.uuid ] = new Source( imageArray );
  25862. } else {
  25863. // load single image
  25864. const deserializedImage = deserializeImage( image.url );
  25865. images[ image.uuid ] = new Source( deserializedImage );
  25866. }
  25867. }
  25868. }
  25869. return images;
  25870. }
  25871. async parseImagesAsync( json ) {
  25872. const scope = this;
  25873. const images = {};
  25874. let loader;
  25875. async function deserializeImage( image ) {
  25876. if ( typeof image === 'string' ) {
  25877. const url = image;
  25878. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25879. return await loader.loadAsync( path );
  25880. } else {
  25881. if ( image.data ) {
  25882. return {
  25883. data: getTypedArray( image.type, image.data ),
  25884. width: image.width,
  25885. height: image.height
  25886. };
  25887. } else {
  25888. return null;
  25889. }
  25890. }
  25891. }
  25892. if ( json !== undefined && json.length > 0 ) {
  25893. loader = new ImageLoader( this.manager );
  25894. loader.setCrossOrigin( this.crossOrigin );
  25895. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25896. const image = json[ i ];
  25897. const url = image.url;
  25898. if ( Array.isArray( url ) ) {
  25899. // load array of images e.g CubeTexture
  25900. const imageArray = [];
  25901. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25902. const currentUrl = url[ j ];
  25903. const deserializedImage = await deserializeImage( currentUrl );
  25904. if ( deserializedImage !== null ) {
  25905. if ( deserializedImage instanceof HTMLImageElement ) {
  25906. imageArray.push( deserializedImage );
  25907. } else {
  25908. // special case: handle array of data textures for cube textures
  25909. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25910. }
  25911. }
  25912. }
  25913. images[ image.uuid ] = new Source( imageArray );
  25914. } else {
  25915. // load single image
  25916. const deserializedImage = await deserializeImage( image.url );
  25917. images[ image.uuid ] = new Source( deserializedImage );
  25918. }
  25919. }
  25920. }
  25921. return images;
  25922. }
  25923. parseTextures( json, images ) {
  25924. function parseConstant( value, type ) {
  25925. if ( typeof value === 'number' ) return value;
  25926. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25927. return type[ value ];
  25928. }
  25929. const textures = {};
  25930. if ( json !== undefined ) {
  25931. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25932. const data = json[ i ];
  25933. if ( data.image === undefined ) {
  25934. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25935. }
  25936. if ( images[ data.image ] === undefined ) {
  25937. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25938. }
  25939. const source = images[ data.image ];
  25940. const image = source.data;
  25941. let texture;
  25942. if ( Array.isArray( image ) ) {
  25943. texture = new CubeTexture();
  25944. if ( image.length === 6 ) texture.needsUpdate = true;
  25945. } else {
  25946. if ( image && image.data ) {
  25947. texture = new DataTexture();
  25948. } else {
  25949. texture = new Texture();
  25950. }
  25951. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25952. }
  25953. texture.source = source;
  25954. texture.uuid = data.uuid;
  25955. if ( data.name !== undefined ) texture.name = data.name;
  25956. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25957. if ( data.channel !== undefined ) texture.channel = data.channel;
  25958. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25959. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25960. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25961. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25962. if ( data.wrap !== undefined ) {
  25963. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25964. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25965. }
  25966. if ( data.format !== undefined ) texture.format = data.format;
  25967. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  25968. if ( data.type !== undefined ) texture.type = data.type;
  25969. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25970. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25971. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25972. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25973. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25974. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  25975. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25976. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25977. if ( data.userData !== undefined ) texture.userData = data.userData;
  25978. textures[ data.uuid ] = texture;
  25979. }
  25980. }
  25981. return textures;
  25982. }
  25983. parseObject( data, geometries, materials, textures, animations ) {
  25984. let object;
  25985. function getGeometry( name ) {
  25986. if ( geometries[ name ] === undefined ) {
  25987. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25988. }
  25989. return geometries[ name ];
  25990. }
  25991. function getMaterial( name ) {
  25992. if ( name === undefined ) return undefined;
  25993. if ( Array.isArray( name ) ) {
  25994. const array = [];
  25995. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25996. const uuid = name[ i ];
  25997. if ( materials[ uuid ] === undefined ) {
  25998. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25999. }
  26000. array.push( materials[ uuid ] );
  26001. }
  26002. return array;
  26003. }
  26004. if ( materials[ name ] === undefined ) {
  26005. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  26006. }
  26007. return materials[ name ];
  26008. }
  26009. function getTexture( uuid ) {
  26010. if ( textures[ uuid ] === undefined ) {
  26011. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  26012. }
  26013. return textures[ uuid ];
  26014. }
  26015. let geometry, material;
  26016. switch ( data.type ) {
  26017. case 'Scene':
  26018. object = new Scene();
  26019. if ( data.background !== undefined ) {
  26020. if ( Number.isInteger( data.background ) ) {
  26021. object.background = new Color( data.background );
  26022. } else {
  26023. object.background = getTexture( data.background );
  26024. }
  26025. }
  26026. if ( data.environment !== undefined ) {
  26027. object.environment = getTexture( data.environment );
  26028. }
  26029. if ( data.fog !== undefined ) {
  26030. if ( data.fog.type === 'Fog' ) {
  26031. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  26032. } else if ( data.fog.type === 'FogExp2' ) {
  26033. object.fog = new FogExp2( data.fog.color, data.fog.density );
  26034. }
  26035. }
  26036. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  26037. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  26038. break;
  26039. case 'PerspectiveCamera':
  26040. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  26041. if ( data.focus !== undefined ) object.focus = data.focus;
  26042. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26043. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  26044. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  26045. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26046. break;
  26047. case 'OrthographicCamera':
  26048. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  26049. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26050. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26051. break;
  26052. case 'AmbientLight':
  26053. object = new AmbientLight( data.color, data.intensity );
  26054. break;
  26055. case 'DirectionalLight':
  26056. object = new DirectionalLight( data.color, data.intensity );
  26057. break;
  26058. case 'PointLight':
  26059. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  26060. break;
  26061. case 'RectAreaLight':
  26062. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  26063. break;
  26064. case 'SpotLight':
  26065. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  26066. break;
  26067. case 'HemisphereLight':
  26068. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  26069. break;
  26070. case 'LightProbe':
  26071. object = new LightProbe().fromJSON( data );
  26072. break;
  26073. case 'SkinnedMesh':
  26074. geometry = getGeometry( data.geometry );
  26075. material = getMaterial( data.material );
  26076. object = new SkinnedMesh( geometry, material );
  26077. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  26078. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  26079. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  26080. break;
  26081. case 'Mesh':
  26082. geometry = getGeometry( data.geometry );
  26083. material = getMaterial( data.material );
  26084. object = new Mesh( geometry, material );
  26085. break;
  26086. case 'InstancedMesh':
  26087. geometry = getGeometry( data.geometry );
  26088. material = getMaterial( data.material );
  26089. const count = data.count;
  26090. const instanceMatrix = data.instanceMatrix;
  26091. const instanceColor = data.instanceColor;
  26092. object = new InstancedMesh( geometry, material, count );
  26093. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  26094. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  26095. break;
  26096. case 'LOD':
  26097. object = new LOD();
  26098. break;
  26099. case 'Line':
  26100. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  26101. break;
  26102. case 'LineLoop':
  26103. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  26104. break;
  26105. case 'LineSegments':
  26106. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  26107. break;
  26108. case 'PointCloud':
  26109. case 'Points':
  26110. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  26111. break;
  26112. case 'Sprite':
  26113. object = new Sprite( getMaterial( data.material ) );
  26114. break;
  26115. case 'Group':
  26116. object = new Group();
  26117. break;
  26118. case 'Bone':
  26119. object = new Bone();
  26120. break;
  26121. default:
  26122. object = new Object3D();
  26123. }
  26124. object.uuid = data.uuid;
  26125. if ( data.name !== undefined ) object.name = data.name;
  26126. if ( data.matrix !== undefined ) {
  26127. object.matrix.fromArray( data.matrix );
  26128. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  26129. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  26130. } else {
  26131. if ( data.position !== undefined ) object.position.fromArray( data.position );
  26132. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  26133. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  26134. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  26135. }
  26136. if ( data.up !== undefined ) object.up.fromArray( data.up );
  26137. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  26138. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  26139. if ( data.shadow ) {
  26140. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  26141. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  26142. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  26143. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  26144. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  26145. }
  26146. if ( data.visible !== undefined ) object.visible = data.visible;
  26147. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  26148. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  26149. if ( data.userData !== undefined ) object.userData = data.userData;
  26150. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  26151. if ( data.children !== undefined ) {
  26152. const children = data.children;
  26153. for ( let i = 0; i < children.length; i ++ ) {
  26154. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  26155. }
  26156. }
  26157. if ( data.animations !== undefined ) {
  26158. const objectAnimations = data.animations;
  26159. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  26160. const uuid = objectAnimations[ i ];
  26161. object.animations.push( animations[ uuid ] );
  26162. }
  26163. }
  26164. if ( data.type === 'LOD' ) {
  26165. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  26166. const levels = data.levels;
  26167. for ( let l = 0; l < levels.length; l ++ ) {
  26168. const level = levels[ l ];
  26169. const child = object.getObjectByProperty( 'uuid', level.object );
  26170. if ( child !== undefined ) {
  26171. object.addLevel( child, level.distance, level.hysteresis );
  26172. }
  26173. }
  26174. }
  26175. return object;
  26176. }
  26177. bindSkeletons( object, skeletons ) {
  26178. if ( Object.keys( skeletons ).length === 0 ) return;
  26179. object.traverse( function ( child ) {
  26180. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  26181. const skeleton = skeletons[ child.skeleton ];
  26182. if ( skeleton === undefined ) {
  26183. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  26184. } else {
  26185. child.bind( skeleton, child.bindMatrix );
  26186. }
  26187. }
  26188. } );
  26189. }
  26190. }
  26191. const TEXTURE_MAPPING = {
  26192. UVMapping: UVMapping,
  26193. CubeReflectionMapping: CubeReflectionMapping,
  26194. CubeRefractionMapping: CubeRefractionMapping,
  26195. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  26196. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  26197. CubeUVReflectionMapping: CubeUVReflectionMapping
  26198. };
  26199. const TEXTURE_WRAPPING = {
  26200. RepeatWrapping: RepeatWrapping,
  26201. ClampToEdgeWrapping: ClampToEdgeWrapping,
  26202. MirroredRepeatWrapping: MirroredRepeatWrapping
  26203. };
  26204. const TEXTURE_FILTER = {
  26205. NearestFilter: NearestFilter,
  26206. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  26207. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  26208. LinearFilter: LinearFilter,
  26209. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  26210. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  26211. };
  26212. class ImageBitmapLoader extends Loader {
  26213. constructor( manager ) {
  26214. super( manager );
  26215. this.isImageBitmapLoader = true;
  26216. if ( typeof createImageBitmap === 'undefined' ) {
  26217. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26218. }
  26219. if ( typeof fetch === 'undefined' ) {
  26220. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26221. }
  26222. this.options = { premultiplyAlpha: 'none' };
  26223. }
  26224. setOptions( options ) {
  26225. this.options = options;
  26226. return this;
  26227. }
  26228. load( url, onLoad, onProgress, onError ) {
  26229. if ( url === undefined ) url = '';
  26230. if ( this.path !== undefined ) url = this.path + url;
  26231. url = this.manager.resolveURL( url );
  26232. const scope = this;
  26233. const cached = Cache.get( url );
  26234. if ( cached !== undefined ) {
  26235. scope.manager.itemStart( url );
  26236. setTimeout( function () {
  26237. if ( onLoad ) onLoad( cached );
  26238. scope.manager.itemEnd( url );
  26239. }, 0 );
  26240. return cached;
  26241. }
  26242. const fetchOptions = {};
  26243. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  26244. fetchOptions.headers = this.requestHeader;
  26245. fetch( url, fetchOptions ).then( function ( res ) {
  26246. return res.blob();
  26247. } ).then( function ( blob ) {
  26248. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  26249. } ).then( function ( imageBitmap ) {
  26250. Cache.add( url, imageBitmap );
  26251. if ( onLoad ) onLoad( imageBitmap );
  26252. scope.manager.itemEnd( url );
  26253. } ).catch( function ( e ) {
  26254. if ( onError ) onError( e );
  26255. scope.manager.itemError( url );
  26256. scope.manager.itemEnd( url );
  26257. } );
  26258. scope.manager.itemStart( url );
  26259. }
  26260. }
  26261. let _context;
  26262. class AudioContext {
  26263. static getContext() {
  26264. if ( _context === undefined ) {
  26265. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26266. }
  26267. return _context;
  26268. }
  26269. static setContext( value ) {
  26270. _context = value;
  26271. }
  26272. }
  26273. class AudioLoader extends Loader {
  26274. constructor( manager ) {
  26275. super( manager );
  26276. }
  26277. load( url, onLoad, onProgress, onError ) {
  26278. const scope = this;
  26279. const loader = new FileLoader( this.manager );
  26280. loader.setResponseType( 'arraybuffer' );
  26281. loader.setPath( this.path );
  26282. loader.setRequestHeader( this.requestHeader );
  26283. loader.setWithCredentials( this.withCredentials );
  26284. loader.load( url, function ( buffer ) {
  26285. try {
  26286. // Create a copy of the buffer. The `decodeAudioData` method
  26287. // detaches the buffer when complete, preventing reuse.
  26288. const bufferCopy = buffer.slice( 0 );
  26289. const context = AudioContext.getContext();
  26290. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26291. onLoad( audioBuffer );
  26292. } );
  26293. } catch ( e ) {
  26294. if ( onError ) {
  26295. onError( e );
  26296. } else {
  26297. console.error( e );
  26298. }
  26299. scope.manager.itemError( url );
  26300. }
  26301. }, onProgress, onError );
  26302. }
  26303. }
  26304. class HemisphereLightProbe extends LightProbe {
  26305. constructor( skyColor, groundColor, intensity = 1 ) {
  26306. super( undefined, intensity );
  26307. this.isHemisphereLightProbe = true;
  26308. const color1 = new Color().set( skyColor );
  26309. const color2 = new Color().set( groundColor );
  26310. const sky = new Vector3( color1.r, color1.g, color1.b );
  26311. const ground = new Vector3( color2.r, color2.g, color2.b );
  26312. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26313. const c0 = Math.sqrt( Math.PI );
  26314. const c1 = c0 * Math.sqrt( 0.75 );
  26315. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26316. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26317. }
  26318. }
  26319. class AmbientLightProbe extends LightProbe {
  26320. constructor( color, intensity = 1 ) {
  26321. super( undefined, intensity );
  26322. this.isAmbientLightProbe = true;
  26323. const color1 = new Color().set( color );
  26324. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26325. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26326. }
  26327. }
  26328. const _eyeRight = /*@__PURE__*/ new Matrix4();
  26329. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  26330. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  26331. class StereoCamera {
  26332. constructor() {
  26333. this.type = 'StereoCamera';
  26334. this.aspect = 1;
  26335. this.eyeSep = 0.064;
  26336. this.cameraL = new PerspectiveCamera();
  26337. this.cameraL.layers.enable( 1 );
  26338. this.cameraL.matrixAutoUpdate = false;
  26339. this.cameraR = new PerspectiveCamera();
  26340. this.cameraR.layers.enable( 2 );
  26341. this.cameraR.matrixAutoUpdate = false;
  26342. this._cache = {
  26343. focus: null,
  26344. fov: null,
  26345. aspect: null,
  26346. near: null,
  26347. far: null,
  26348. zoom: null,
  26349. eyeSep: null
  26350. };
  26351. }
  26352. update( camera ) {
  26353. const cache = this._cache;
  26354. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26355. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26356. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26357. if ( needsUpdate ) {
  26358. cache.focus = camera.focus;
  26359. cache.fov = camera.fov;
  26360. cache.aspect = camera.aspect * this.aspect;
  26361. cache.near = camera.near;
  26362. cache.far = camera.far;
  26363. cache.zoom = camera.zoom;
  26364. cache.eyeSep = this.eyeSep;
  26365. // Off-axis stereoscopic effect based on
  26366. // http://paulbourke.net/stereographics/stereorender/
  26367. _projectionMatrix.copy( camera.projectionMatrix );
  26368. const eyeSepHalf = cache.eyeSep / 2;
  26369. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26370. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26371. let xmin, xmax;
  26372. // translate xOffset
  26373. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26374. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26375. // for left eye
  26376. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26377. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26378. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26379. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26380. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  26381. // for right eye
  26382. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26383. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26384. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26385. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26386. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  26387. }
  26388. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26389. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26390. }
  26391. }
  26392. class Clock {
  26393. constructor( autoStart = true ) {
  26394. this.autoStart = autoStart;
  26395. this.startTime = 0;
  26396. this.oldTime = 0;
  26397. this.elapsedTime = 0;
  26398. this.running = false;
  26399. }
  26400. start() {
  26401. this.startTime = now();
  26402. this.oldTime = this.startTime;
  26403. this.elapsedTime = 0;
  26404. this.running = true;
  26405. }
  26406. stop() {
  26407. this.getElapsedTime();
  26408. this.running = false;
  26409. this.autoStart = false;
  26410. }
  26411. getElapsedTime() {
  26412. this.getDelta();
  26413. return this.elapsedTime;
  26414. }
  26415. getDelta() {
  26416. let diff = 0;
  26417. if ( this.autoStart && ! this.running ) {
  26418. this.start();
  26419. return 0;
  26420. }
  26421. if ( this.running ) {
  26422. const newTime = now();
  26423. diff = ( newTime - this.oldTime ) / 1000;
  26424. this.oldTime = newTime;
  26425. this.elapsedTime += diff;
  26426. }
  26427. return diff;
  26428. }
  26429. }
  26430. function now() {
  26431. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26432. }
  26433. const _position$1 = /*@__PURE__*/ new Vector3();
  26434. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  26435. const _scale$1 = /*@__PURE__*/ new Vector3();
  26436. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26437. class AudioListener extends Object3D {
  26438. constructor() {
  26439. super();
  26440. this.type = 'AudioListener';
  26441. this.context = AudioContext.getContext();
  26442. this.gain = this.context.createGain();
  26443. this.gain.connect( this.context.destination );
  26444. this.filter = null;
  26445. this.timeDelta = 0;
  26446. // private
  26447. this._clock = new Clock();
  26448. }
  26449. getInput() {
  26450. return this.gain;
  26451. }
  26452. removeFilter() {
  26453. if ( this.filter !== null ) {
  26454. this.gain.disconnect( this.filter );
  26455. this.filter.disconnect( this.context.destination );
  26456. this.gain.connect( this.context.destination );
  26457. this.filter = null;
  26458. }
  26459. return this;
  26460. }
  26461. getFilter() {
  26462. return this.filter;
  26463. }
  26464. setFilter( value ) {
  26465. if ( this.filter !== null ) {
  26466. this.gain.disconnect( this.filter );
  26467. this.filter.disconnect( this.context.destination );
  26468. } else {
  26469. this.gain.disconnect( this.context.destination );
  26470. }
  26471. this.filter = value;
  26472. this.gain.connect( this.filter );
  26473. this.filter.connect( this.context.destination );
  26474. return this;
  26475. }
  26476. getMasterVolume() {
  26477. return this.gain.gain.value;
  26478. }
  26479. setMasterVolume( value ) {
  26480. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26481. return this;
  26482. }
  26483. updateMatrixWorld( force ) {
  26484. super.updateMatrixWorld( force );
  26485. const listener = this.context.listener;
  26486. const up = this.up;
  26487. this.timeDelta = this._clock.getDelta();
  26488. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26489. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26490. if ( listener.positionX ) {
  26491. // code path for Chrome (see #14393)
  26492. const endTime = this.context.currentTime + this.timeDelta;
  26493. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26494. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26495. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26496. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26497. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26498. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26499. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26500. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26501. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26502. } else {
  26503. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26504. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26505. }
  26506. }
  26507. }
  26508. class Audio extends Object3D {
  26509. constructor( listener ) {
  26510. super();
  26511. this.type = 'Audio';
  26512. this.listener = listener;
  26513. this.context = listener.context;
  26514. this.gain = this.context.createGain();
  26515. this.gain.connect( listener.getInput() );
  26516. this.autoplay = false;
  26517. this.buffer = null;
  26518. this.detune = 0;
  26519. this.loop = false;
  26520. this.loopStart = 0;
  26521. this.loopEnd = 0;
  26522. this.offset = 0;
  26523. this.duration = undefined;
  26524. this.playbackRate = 1;
  26525. this.isPlaying = false;
  26526. this.hasPlaybackControl = true;
  26527. this.source = null;
  26528. this.sourceType = 'empty';
  26529. this._startedAt = 0;
  26530. this._progress = 0;
  26531. this._connected = false;
  26532. this.filters = [];
  26533. }
  26534. getOutput() {
  26535. return this.gain;
  26536. }
  26537. setNodeSource( audioNode ) {
  26538. this.hasPlaybackControl = false;
  26539. this.sourceType = 'audioNode';
  26540. this.source = audioNode;
  26541. this.connect();
  26542. return this;
  26543. }
  26544. setMediaElementSource( mediaElement ) {
  26545. this.hasPlaybackControl = false;
  26546. this.sourceType = 'mediaNode';
  26547. this.source = this.context.createMediaElementSource( mediaElement );
  26548. this.connect();
  26549. return this;
  26550. }
  26551. setMediaStreamSource( mediaStream ) {
  26552. this.hasPlaybackControl = false;
  26553. this.sourceType = 'mediaStreamNode';
  26554. this.source = this.context.createMediaStreamSource( mediaStream );
  26555. this.connect();
  26556. return this;
  26557. }
  26558. setBuffer( audioBuffer ) {
  26559. this.buffer = audioBuffer;
  26560. this.sourceType = 'buffer';
  26561. if ( this.autoplay ) this.play();
  26562. return this;
  26563. }
  26564. play( delay = 0 ) {
  26565. if ( this.isPlaying === true ) {
  26566. console.warn( 'THREE.Audio: Audio is already playing.' );
  26567. return;
  26568. }
  26569. if ( this.hasPlaybackControl === false ) {
  26570. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26571. return;
  26572. }
  26573. this._startedAt = this.context.currentTime + delay;
  26574. const source = this.context.createBufferSource();
  26575. source.buffer = this.buffer;
  26576. source.loop = this.loop;
  26577. source.loopStart = this.loopStart;
  26578. source.loopEnd = this.loopEnd;
  26579. source.onended = this.onEnded.bind( this );
  26580. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26581. this.isPlaying = true;
  26582. this.source = source;
  26583. this.setDetune( this.detune );
  26584. this.setPlaybackRate( this.playbackRate );
  26585. return this.connect();
  26586. }
  26587. pause() {
  26588. if ( this.hasPlaybackControl === false ) {
  26589. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26590. return;
  26591. }
  26592. if ( this.isPlaying === true ) {
  26593. // update current progress
  26594. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26595. if ( this.loop === true ) {
  26596. // ensure _progress does not exceed duration with looped audios
  26597. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26598. }
  26599. this.source.stop();
  26600. this.source.onended = null;
  26601. this.isPlaying = false;
  26602. }
  26603. return this;
  26604. }
  26605. stop() {
  26606. if ( this.hasPlaybackControl === false ) {
  26607. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26608. return;
  26609. }
  26610. this._progress = 0;
  26611. if ( this.source !== null ) {
  26612. this.source.stop();
  26613. this.source.onended = null;
  26614. }
  26615. this.isPlaying = false;
  26616. return this;
  26617. }
  26618. connect() {
  26619. if ( this.filters.length > 0 ) {
  26620. this.source.connect( this.filters[ 0 ] );
  26621. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26622. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26623. }
  26624. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26625. } else {
  26626. this.source.connect( this.getOutput() );
  26627. }
  26628. this._connected = true;
  26629. return this;
  26630. }
  26631. disconnect() {
  26632. if ( this.filters.length > 0 ) {
  26633. this.source.disconnect( this.filters[ 0 ] );
  26634. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26635. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26636. }
  26637. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26638. } else {
  26639. this.source.disconnect( this.getOutput() );
  26640. }
  26641. this._connected = false;
  26642. return this;
  26643. }
  26644. getFilters() {
  26645. return this.filters;
  26646. }
  26647. setFilters( value ) {
  26648. if ( ! value ) value = [];
  26649. if ( this._connected === true ) {
  26650. this.disconnect();
  26651. this.filters = value.slice();
  26652. this.connect();
  26653. } else {
  26654. this.filters = value.slice();
  26655. }
  26656. return this;
  26657. }
  26658. setDetune( value ) {
  26659. this.detune = value;
  26660. if ( this.source.detune === undefined ) return; // only set detune when available
  26661. if ( this.isPlaying === true ) {
  26662. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26663. }
  26664. return this;
  26665. }
  26666. getDetune() {
  26667. return this.detune;
  26668. }
  26669. getFilter() {
  26670. return this.getFilters()[ 0 ];
  26671. }
  26672. setFilter( filter ) {
  26673. return this.setFilters( filter ? [ filter ] : [] );
  26674. }
  26675. setPlaybackRate( value ) {
  26676. if ( this.hasPlaybackControl === false ) {
  26677. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26678. return;
  26679. }
  26680. this.playbackRate = value;
  26681. if ( this.isPlaying === true ) {
  26682. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26683. }
  26684. return this;
  26685. }
  26686. getPlaybackRate() {
  26687. return this.playbackRate;
  26688. }
  26689. onEnded() {
  26690. this.isPlaying = false;
  26691. }
  26692. getLoop() {
  26693. if ( this.hasPlaybackControl === false ) {
  26694. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26695. return false;
  26696. }
  26697. return this.loop;
  26698. }
  26699. setLoop( value ) {
  26700. if ( this.hasPlaybackControl === false ) {
  26701. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26702. return;
  26703. }
  26704. this.loop = value;
  26705. if ( this.isPlaying === true ) {
  26706. this.source.loop = this.loop;
  26707. }
  26708. return this;
  26709. }
  26710. setLoopStart( value ) {
  26711. this.loopStart = value;
  26712. return this;
  26713. }
  26714. setLoopEnd( value ) {
  26715. this.loopEnd = value;
  26716. return this;
  26717. }
  26718. getVolume() {
  26719. return this.gain.gain.value;
  26720. }
  26721. setVolume( value ) {
  26722. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26723. return this;
  26724. }
  26725. }
  26726. const _position = /*@__PURE__*/ new Vector3();
  26727. const _quaternion = /*@__PURE__*/ new Quaternion();
  26728. const _scale = /*@__PURE__*/ new Vector3();
  26729. const _orientation = /*@__PURE__*/ new Vector3();
  26730. class PositionalAudio extends Audio {
  26731. constructor( listener ) {
  26732. super( listener );
  26733. this.panner = this.context.createPanner();
  26734. this.panner.panningModel = 'HRTF';
  26735. this.panner.connect( this.gain );
  26736. }
  26737. disconnect() {
  26738. super.disconnect();
  26739. this.panner.disconnect( this.gain );
  26740. }
  26741. getOutput() {
  26742. return this.panner;
  26743. }
  26744. getRefDistance() {
  26745. return this.panner.refDistance;
  26746. }
  26747. setRefDistance( value ) {
  26748. this.panner.refDistance = value;
  26749. return this;
  26750. }
  26751. getRolloffFactor() {
  26752. return this.panner.rolloffFactor;
  26753. }
  26754. setRolloffFactor( value ) {
  26755. this.panner.rolloffFactor = value;
  26756. return this;
  26757. }
  26758. getDistanceModel() {
  26759. return this.panner.distanceModel;
  26760. }
  26761. setDistanceModel( value ) {
  26762. this.panner.distanceModel = value;
  26763. return this;
  26764. }
  26765. getMaxDistance() {
  26766. return this.panner.maxDistance;
  26767. }
  26768. setMaxDistance( value ) {
  26769. this.panner.maxDistance = value;
  26770. return this;
  26771. }
  26772. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26773. this.panner.coneInnerAngle = coneInnerAngle;
  26774. this.panner.coneOuterAngle = coneOuterAngle;
  26775. this.panner.coneOuterGain = coneOuterGain;
  26776. return this;
  26777. }
  26778. updateMatrixWorld( force ) {
  26779. super.updateMatrixWorld( force );
  26780. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26781. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26782. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26783. const panner = this.panner;
  26784. if ( panner.positionX ) {
  26785. // code path for Chrome and Firefox (see #14393)
  26786. const endTime = this.context.currentTime + this.listener.timeDelta;
  26787. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26788. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26789. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26790. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26791. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26792. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26793. } else {
  26794. panner.setPosition( _position.x, _position.y, _position.z );
  26795. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26796. }
  26797. }
  26798. }
  26799. class AudioAnalyser {
  26800. constructor( audio, fftSize = 2048 ) {
  26801. this.analyser = audio.context.createAnalyser();
  26802. this.analyser.fftSize = fftSize;
  26803. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26804. audio.getOutput().connect( this.analyser );
  26805. }
  26806. getFrequencyData() {
  26807. this.analyser.getByteFrequencyData( this.data );
  26808. return this.data;
  26809. }
  26810. getAverageFrequency() {
  26811. let value = 0;
  26812. const data = this.getFrequencyData();
  26813. for ( let i = 0; i < data.length; i ++ ) {
  26814. value += data[ i ];
  26815. }
  26816. return value / data.length;
  26817. }
  26818. }
  26819. class PropertyMixer {
  26820. constructor( binding, typeName, valueSize ) {
  26821. this.binding = binding;
  26822. this.valueSize = valueSize;
  26823. let mixFunction,
  26824. mixFunctionAdditive,
  26825. setIdentity;
  26826. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26827. //
  26828. // interpolators can use .buffer as their .result
  26829. // the data then goes to 'incoming'
  26830. //
  26831. // 'accu0' and 'accu1' are used frame-interleaved for
  26832. // the cumulative result and are compared to detect
  26833. // changes
  26834. //
  26835. // 'orig' stores the original state of the property
  26836. //
  26837. // 'add' is used for additive cumulative results
  26838. //
  26839. // 'work' is optional and is only present for quaternion types. It is used
  26840. // to store intermediate quaternion multiplication results
  26841. switch ( typeName ) {
  26842. case 'quaternion':
  26843. mixFunction = this._slerp;
  26844. mixFunctionAdditive = this._slerpAdditive;
  26845. setIdentity = this._setAdditiveIdentityQuaternion;
  26846. this.buffer = new Float64Array( valueSize * 6 );
  26847. this._workIndex = 5;
  26848. break;
  26849. case 'string':
  26850. case 'bool':
  26851. mixFunction = this._select;
  26852. // Use the regular mix function and for additive on these types,
  26853. // additive is not relevant for non-numeric types
  26854. mixFunctionAdditive = this._select;
  26855. setIdentity = this._setAdditiveIdentityOther;
  26856. this.buffer = new Array( valueSize * 5 );
  26857. break;
  26858. default:
  26859. mixFunction = this._lerp;
  26860. mixFunctionAdditive = this._lerpAdditive;
  26861. setIdentity = this._setAdditiveIdentityNumeric;
  26862. this.buffer = new Float64Array( valueSize * 5 );
  26863. }
  26864. this._mixBufferRegion = mixFunction;
  26865. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26866. this._setIdentity = setIdentity;
  26867. this._origIndex = 3;
  26868. this._addIndex = 4;
  26869. this.cumulativeWeight = 0;
  26870. this.cumulativeWeightAdditive = 0;
  26871. this.useCount = 0;
  26872. this.referenceCount = 0;
  26873. }
  26874. // accumulate data in the 'incoming' region into 'accu<i>'
  26875. accumulate( accuIndex, weight ) {
  26876. // note: happily accumulating nothing when weight = 0, the caller knows
  26877. // the weight and shouldn't have made the call in the first place
  26878. const buffer = this.buffer,
  26879. stride = this.valueSize,
  26880. offset = accuIndex * stride + stride;
  26881. let currentWeight = this.cumulativeWeight;
  26882. if ( currentWeight === 0 ) {
  26883. // accuN := incoming * weight
  26884. for ( let i = 0; i !== stride; ++ i ) {
  26885. buffer[ offset + i ] = buffer[ i ];
  26886. }
  26887. currentWeight = weight;
  26888. } else {
  26889. // accuN := accuN + incoming * weight
  26890. currentWeight += weight;
  26891. const mix = weight / currentWeight;
  26892. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26893. }
  26894. this.cumulativeWeight = currentWeight;
  26895. }
  26896. // accumulate data in the 'incoming' region into 'add'
  26897. accumulateAdditive( weight ) {
  26898. const buffer = this.buffer,
  26899. stride = this.valueSize,
  26900. offset = stride * this._addIndex;
  26901. if ( this.cumulativeWeightAdditive === 0 ) {
  26902. // add = identity
  26903. this._setIdentity();
  26904. }
  26905. // add := add + incoming * weight
  26906. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26907. this.cumulativeWeightAdditive += weight;
  26908. }
  26909. // apply the state of 'accu<i>' to the binding when accus differ
  26910. apply( accuIndex ) {
  26911. const stride = this.valueSize,
  26912. buffer = this.buffer,
  26913. offset = accuIndex * stride + stride,
  26914. weight = this.cumulativeWeight,
  26915. weightAdditive = this.cumulativeWeightAdditive,
  26916. binding = this.binding;
  26917. this.cumulativeWeight = 0;
  26918. this.cumulativeWeightAdditive = 0;
  26919. if ( weight < 1 ) {
  26920. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26921. const originalValueOffset = stride * this._origIndex;
  26922. this._mixBufferRegion(
  26923. buffer, offset, originalValueOffset, 1 - weight, stride );
  26924. }
  26925. if ( weightAdditive > 0 ) {
  26926. // accuN := accuN + additive accuN
  26927. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26928. }
  26929. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26930. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26931. // value has changed -> update scene graph
  26932. binding.setValue( buffer, offset );
  26933. break;
  26934. }
  26935. }
  26936. }
  26937. // remember the state of the bound property and copy it to both accus
  26938. saveOriginalState() {
  26939. const binding = this.binding;
  26940. const buffer = this.buffer,
  26941. stride = this.valueSize,
  26942. originalValueOffset = stride * this._origIndex;
  26943. binding.getValue( buffer, originalValueOffset );
  26944. // accu[0..1] := orig -- initially detect changes against the original
  26945. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26946. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26947. }
  26948. // Add to identity for additive
  26949. this._setIdentity();
  26950. this.cumulativeWeight = 0;
  26951. this.cumulativeWeightAdditive = 0;
  26952. }
  26953. // apply the state previously taken via 'saveOriginalState' to the binding
  26954. restoreOriginalState() {
  26955. const originalValueOffset = this.valueSize * 3;
  26956. this.binding.setValue( this.buffer, originalValueOffset );
  26957. }
  26958. _setAdditiveIdentityNumeric() {
  26959. const startIndex = this._addIndex * this.valueSize;
  26960. const endIndex = startIndex + this.valueSize;
  26961. for ( let i = startIndex; i < endIndex; i ++ ) {
  26962. this.buffer[ i ] = 0;
  26963. }
  26964. }
  26965. _setAdditiveIdentityQuaternion() {
  26966. this._setAdditiveIdentityNumeric();
  26967. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26968. }
  26969. _setAdditiveIdentityOther() {
  26970. const startIndex = this._origIndex * this.valueSize;
  26971. const targetIndex = this._addIndex * this.valueSize;
  26972. for ( let i = 0; i < this.valueSize; i ++ ) {
  26973. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26974. }
  26975. }
  26976. // mix functions
  26977. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26978. if ( t >= 0.5 ) {
  26979. for ( let i = 0; i !== stride; ++ i ) {
  26980. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26981. }
  26982. }
  26983. }
  26984. _slerp( buffer, dstOffset, srcOffset, t ) {
  26985. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26986. }
  26987. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26988. const workOffset = this._workIndex * stride;
  26989. // Store result in intermediate buffer offset
  26990. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26991. // Slerp to the intermediate result
  26992. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26993. }
  26994. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26995. const s = 1 - t;
  26996. for ( let i = 0; i !== stride; ++ i ) {
  26997. const j = dstOffset + i;
  26998. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26999. }
  27000. }
  27001. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27002. for ( let i = 0; i !== stride; ++ i ) {
  27003. const j = dstOffset + i;
  27004. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  27005. }
  27006. }
  27007. }
  27008. // Characters [].:/ are reserved for track binding syntax.
  27009. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  27010. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  27011. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  27012. // only latin characters, and the unicode \p{L} is not yet supported. So
  27013. // instead, we exclude reserved characters and match everything else.
  27014. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  27015. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  27016. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  27017. // be matched to parse the rest of the track name.
  27018. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  27019. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  27020. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  27021. // Object on target node, and accessor. May not contain reserved
  27022. // characters. Accessor may contain any character except closing bracket.
  27023. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  27024. // Property and accessor. May not contain reserved characters. Accessor may
  27025. // contain any non-bracket characters.
  27026. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  27027. const _trackRe = new RegExp( ''
  27028. + '^'
  27029. + _directoryRe
  27030. + _nodeRe
  27031. + _objectRe
  27032. + _propertyRe
  27033. + '$'
  27034. );
  27035. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  27036. class Composite {
  27037. constructor( targetGroup, path, optionalParsedPath ) {
  27038. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  27039. this._targetGroup = targetGroup;
  27040. this._bindings = targetGroup.subscribe_( path, parsedPath );
  27041. }
  27042. getValue( array, offset ) {
  27043. this.bind(); // bind all binding
  27044. const firstValidIndex = this._targetGroup.nCachedObjects_,
  27045. binding = this._bindings[ firstValidIndex ];
  27046. // and only call .getValue on the first
  27047. if ( binding !== undefined ) binding.getValue( array, offset );
  27048. }
  27049. setValue( array, offset ) {
  27050. const bindings = this._bindings;
  27051. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27052. bindings[ i ].setValue( array, offset );
  27053. }
  27054. }
  27055. bind() {
  27056. const bindings = this._bindings;
  27057. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27058. bindings[ i ].bind();
  27059. }
  27060. }
  27061. unbind() {
  27062. const bindings = this._bindings;
  27063. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27064. bindings[ i ].unbind();
  27065. }
  27066. }
  27067. }
  27068. // Note: This class uses a State pattern on a per-method basis:
  27069. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  27070. // prototype version of these methods with one that represents
  27071. // the bound state. When the property is not found, the methods
  27072. // become no-ops.
  27073. class PropertyBinding {
  27074. constructor( rootNode, path, parsedPath ) {
  27075. this.path = path;
  27076. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  27077. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  27078. this.rootNode = rootNode;
  27079. // initial state of these methods that calls 'bind'
  27080. this.getValue = this._getValue_unbound;
  27081. this.setValue = this._setValue_unbound;
  27082. }
  27083. static create( root, path, parsedPath ) {
  27084. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  27085. return new PropertyBinding( root, path, parsedPath );
  27086. } else {
  27087. return new PropertyBinding.Composite( root, path, parsedPath );
  27088. }
  27089. }
  27090. /**
  27091. * Replaces spaces with underscores and removes unsupported characters from
  27092. * node names, to ensure compatibility with parseTrackName().
  27093. *
  27094. * @param {string} name Node name to be sanitized.
  27095. * @return {string}
  27096. */
  27097. static sanitizeNodeName( name ) {
  27098. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  27099. }
  27100. static parseTrackName( trackName ) {
  27101. const matches = _trackRe.exec( trackName );
  27102. if ( matches === null ) {
  27103. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  27104. }
  27105. const results = {
  27106. // directoryName: matches[ 1 ], // (tschw) currently unused
  27107. nodeName: matches[ 2 ],
  27108. objectName: matches[ 3 ],
  27109. objectIndex: matches[ 4 ],
  27110. propertyName: matches[ 5 ], // required
  27111. propertyIndex: matches[ 6 ]
  27112. };
  27113. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  27114. if ( lastDot !== undefined && lastDot !== - 1 ) {
  27115. const objectName = results.nodeName.substring( lastDot + 1 );
  27116. // Object names must be checked against an allowlist. Otherwise, there
  27117. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  27118. // 'bar' could be the objectName, or part of a nodeName (which can
  27119. // include '.' characters).
  27120. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  27121. results.nodeName = results.nodeName.substring( 0, lastDot );
  27122. results.objectName = objectName;
  27123. }
  27124. }
  27125. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  27126. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  27127. }
  27128. return results;
  27129. }
  27130. static findNode( root, nodeName ) {
  27131. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  27132. return root;
  27133. }
  27134. // search into skeleton bones.
  27135. if ( root.skeleton ) {
  27136. const bone = root.skeleton.getBoneByName( nodeName );
  27137. if ( bone !== undefined ) {
  27138. return bone;
  27139. }
  27140. }
  27141. // search into node subtree.
  27142. if ( root.children ) {
  27143. const searchNodeSubtree = function ( children ) {
  27144. for ( let i = 0; i < children.length; i ++ ) {
  27145. const childNode = children[ i ];
  27146. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  27147. return childNode;
  27148. }
  27149. const result = searchNodeSubtree( childNode.children );
  27150. if ( result ) return result;
  27151. }
  27152. return null;
  27153. };
  27154. const subTreeNode = searchNodeSubtree( root.children );
  27155. if ( subTreeNode ) {
  27156. return subTreeNode;
  27157. }
  27158. }
  27159. return null;
  27160. }
  27161. // these are used to "bind" a nonexistent property
  27162. _getValue_unavailable() {}
  27163. _setValue_unavailable() {}
  27164. // Getters
  27165. _getValue_direct( buffer, offset ) {
  27166. buffer[ offset ] = this.targetObject[ this.propertyName ];
  27167. }
  27168. _getValue_array( buffer, offset ) {
  27169. const source = this.resolvedProperty;
  27170. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  27171. buffer[ offset ++ ] = source[ i ];
  27172. }
  27173. }
  27174. _getValue_arrayElement( buffer, offset ) {
  27175. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  27176. }
  27177. _getValue_toArray( buffer, offset ) {
  27178. this.resolvedProperty.toArray( buffer, offset );
  27179. }
  27180. // Direct
  27181. _setValue_direct( buffer, offset ) {
  27182. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27183. }
  27184. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  27185. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27186. this.targetObject.needsUpdate = true;
  27187. }
  27188. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27189. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27190. this.targetObject.matrixWorldNeedsUpdate = true;
  27191. }
  27192. // EntireArray
  27193. _setValue_array( buffer, offset ) {
  27194. const dest = this.resolvedProperty;
  27195. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27196. dest[ i ] = buffer[ offset ++ ];
  27197. }
  27198. }
  27199. _setValue_array_setNeedsUpdate( buffer, offset ) {
  27200. const dest = this.resolvedProperty;
  27201. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27202. dest[ i ] = buffer[ offset ++ ];
  27203. }
  27204. this.targetObject.needsUpdate = true;
  27205. }
  27206. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27207. const dest = this.resolvedProperty;
  27208. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27209. dest[ i ] = buffer[ offset ++ ];
  27210. }
  27211. this.targetObject.matrixWorldNeedsUpdate = true;
  27212. }
  27213. // ArrayElement
  27214. _setValue_arrayElement( buffer, offset ) {
  27215. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27216. }
  27217. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27218. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27219. this.targetObject.needsUpdate = true;
  27220. }
  27221. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27222. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27223. this.targetObject.matrixWorldNeedsUpdate = true;
  27224. }
  27225. // HasToFromArray
  27226. _setValue_fromArray( buffer, offset ) {
  27227. this.resolvedProperty.fromArray( buffer, offset );
  27228. }
  27229. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27230. this.resolvedProperty.fromArray( buffer, offset );
  27231. this.targetObject.needsUpdate = true;
  27232. }
  27233. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27234. this.resolvedProperty.fromArray( buffer, offset );
  27235. this.targetObject.matrixWorldNeedsUpdate = true;
  27236. }
  27237. _getValue_unbound( targetArray, offset ) {
  27238. this.bind();
  27239. this.getValue( targetArray, offset );
  27240. }
  27241. _setValue_unbound( sourceArray, offset ) {
  27242. this.bind();
  27243. this.setValue( sourceArray, offset );
  27244. }
  27245. // create getter / setter pair for a property in the scene graph
  27246. bind() {
  27247. let targetObject = this.node;
  27248. const parsedPath = this.parsedPath;
  27249. const objectName = parsedPath.objectName;
  27250. const propertyName = parsedPath.propertyName;
  27251. let propertyIndex = parsedPath.propertyIndex;
  27252. if ( ! targetObject ) {
  27253. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  27254. this.node = targetObject;
  27255. }
  27256. // set fail state so we can just 'return' on error
  27257. this.getValue = this._getValue_unavailable;
  27258. this.setValue = this._setValue_unavailable;
  27259. // ensure there is a value node
  27260. if ( ! targetObject ) {
  27261. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27262. return;
  27263. }
  27264. if ( objectName ) {
  27265. let objectIndex = parsedPath.objectIndex;
  27266. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27267. switch ( objectName ) {
  27268. case 'materials':
  27269. if ( ! targetObject.material ) {
  27270. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27271. return;
  27272. }
  27273. if ( ! targetObject.material.materials ) {
  27274. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27275. return;
  27276. }
  27277. targetObject = targetObject.material.materials;
  27278. break;
  27279. case 'bones':
  27280. if ( ! targetObject.skeleton ) {
  27281. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27282. return;
  27283. }
  27284. // potential future optimization: skip this if propertyIndex is already an integer
  27285. // and convert the integer string to a true integer.
  27286. targetObject = targetObject.skeleton.bones;
  27287. // support resolving morphTarget names into indices.
  27288. for ( let i = 0; i < targetObject.length; i ++ ) {
  27289. if ( targetObject[ i ].name === objectIndex ) {
  27290. objectIndex = i;
  27291. break;
  27292. }
  27293. }
  27294. break;
  27295. case 'map':
  27296. if ( 'map' in targetObject ) {
  27297. targetObject = targetObject.map;
  27298. break;
  27299. }
  27300. if ( ! targetObject.material ) {
  27301. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27302. return;
  27303. }
  27304. if ( ! targetObject.material.map ) {
  27305. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  27306. return;
  27307. }
  27308. targetObject = targetObject.material.map;
  27309. break;
  27310. default:
  27311. if ( targetObject[ objectName ] === undefined ) {
  27312. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27313. return;
  27314. }
  27315. targetObject = targetObject[ objectName ];
  27316. }
  27317. if ( objectIndex !== undefined ) {
  27318. if ( targetObject[ objectIndex ] === undefined ) {
  27319. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27320. return;
  27321. }
  27322. targetObject = targetObject[ objectIndex ];
  27323. }
  27324. }
  27325. // resolve property
  27326. const nodeProperty = targetObject[ propertyName ];
  27327. if ( nodeProperty === undefined ) {
  27328. const nodeName = parsedPath.nodeName;
  27329. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27330. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27331. return;
  27332. }
  27333. // determine versioning scheme
  27334. let versioning = this.Versioning.None;
  27335. this.targetObject = targetObject;
  27336. if ( targetObject.needsUpdate !== undefined ) { // material
  27337. versioning = this.Versioning.NeedsUpdate;
  27338. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27339. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27340. }
  27341. // determine how the property gets bound
  27342. let bindingType = this.BindingType.Direct;
  27343. if ( propertyIndex !== undefined ) {
  27344. // access a sub element of the property array (only primitives are supported right now)
  27345. if ( propertyName === 'morphTargetInfluences' ) {
  27346. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27347. // support resolving morphTarget names into indices.
  27348. if ( ! targetObject.geometry ) {
  27349. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27350. return;
  27351. }
  27352. if ( ! targetObject.geometry.morphAttributes ) {
  27353. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27354. return;
  27355. }
  27356. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27357. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27358. }
  27359. }
  27360. bindingType = this.BindingType.ArrayElement;
  27361. this.resolvedProperty = nodeProperty;
  27362. this.propertyIndex = propertyIndex;
  27363. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27364. // must use copy for Object3D.Euler/Quaternion
  27365. bindingType = this.BindingType.HasFromToArray;
  27366. this.resolvedProperty = nodeProperty;
  27367. } else if ( Array.isArray( nodeProperty ) ) {
  27368. bindingType = this.BindingType.EntireArray;
  27369. this.resolvedProperty = nodeProperty;
  27370. } else {
  27371. this.propertyName = propertyName;
  27372. }
  27373. // select getter / setter
  27374. this.getValue = this.GetterByBindingType[ bindingType ];
  27375. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27376. }
  27377. unbind() {
  27378. this.node = null;
  27379. // back to the prototype version of getValue / setValue
  27380. // note: avoiding to mutate the shape of 'this' via 'delete'
  27381. this.getValue = this._getValue_unbound;
  27382. this.setValue = this._setValue_unbound;
  27383. }
  27384. }
  27385. PropertyBinding.Composite = Composite;
  27386. PropertyBinding.prototype.BindingType = {
  27387. Direct: 0,
  27388. EntireArray: 1,
  27389. ArrayElement: 2,
  27390. HasFromToArray: 3
  27391. };
  27392. PropertyBinding.prototype.Versioning = {
  27393. None: 0,
  27394. NeedsUpdate: 1,
  27395. MatrixWorldNeedsUpdate: 2
  27396. };
  27397. PropertyBinding.prototype.GetterByBindingType = [
  27398. PropertyBinding.prototype._getValue_direct,
  27399. PropertyBinding.prototype._getValue_array,
  27400. PropertyBinding.prototype._getValue_arrayElement,
  27401. PropertyBinding.prototype._getValue_toArray,
  27402. ];
  27403. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  27404. [
  27405. // Direct
  27406. PropertyBinding.prototype._setValue_direct,
  27407. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  27408. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  27409. ], [
  27410. // EntireArray
  27411. PropertyBinding.prototype._setValue_array,
  27412. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  27413. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  27414. ], [
  27415. // ArrayElement
  27416. PropertyBinding.prototype._setValue_arrayElement,
  27417. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  27418. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  27419. ], [
  27420. // HasToFromArray
  27421. PropertyBinding.prototype._setValue_fromArray,
  27422. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  27423. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  27424. ]
  27425. ];
  27426. /**
  27427. *
  27428. * A group of objects that receives a shared animation state.
  27429. *
  27430. * Usage:
  27431. *
  27432. * - Add objects you would otherwise pass as 'root' to the
  27433. * constructor or the .clipAction method of AnimationMixer.
  27434. *
  27435. * - Instead pass this object as 'root'.
  27436. *
  27437. * - You can also add and remove objects later when the mixer
  27438. * is running.
  27439. *
  27440. * Note:
  27441. *
  27442. * Objects of this class appear as one object to the mixer,
  27443. * so cache control of the individual objects must be done
  27444. * on the group.
  27445. *
  27446. * Limitation:
  27447. *
  27448. * - The animated properties must be compatible among the
  27449. * all objects in the group.
  27450. *
  27451. * - A single property can either be controlled through a
  27452. * target group or directly, but not both.
  27453. */
  27454. class AnimationObjectGroup {
  27455. constructor() {
  27456. this.isAnimationObjectGroup = true;
  27457. this.uuid = generateUUID();
  27458. // cached objects followed by the active ones
  27459. this._objects = Array.prototype.slice.call( arguments );
  27460. this.nCachedObjects_ = 0; // threshold
  27461. // note: read by PropertyBinding.Composite
  27462. const indices = {};
  27463. this._indicesByUUID = indices; // for bookkeeping
  27464. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27465. indices[ arguments[ i ].uuid ] = i;
  27466. }
  27467. this._paths = []; // inside: string
  27468. this._parsedPaths = []; // inside: { we don't care, here }
  27469. this._bindings = []; // inside: Array< PropertyBinding >
  27470. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27471. const scope = this;
  27472. this.stats = {
  27473. objects: {
  27474. get total() {
  27475. return scope._objects.length;
  27476. },
  27477. get inUse() {
  27478. return this.total - scope.nCachedObjects_;
  27479. }
  27480. },
  27481. get bindingsPerObject() {
  27482. return scope._bindings.length;
  27483. }
  27484. };
  27485. }
  27486. add() {
  27487. const objects = this._objects,
  27488. indicesByUUID = this._indicesByUUID,
  27489. paths = this._paths,
  27490. parsedPaths = this._parsedPaths,
  27491. bindings = this._bindings,
  27492. nBindings = bindings.length;
  27493. let knownObject = undefined,
  27494. nObjects = objects.length,
  27495. nCachedObjects = this.nCachedObjects_;
  27496. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27497. const object = arguments[ i ],
  27498. uuid = object.uuid;
  27499. let index = indicesByUUID[ uuid ];
  27500. if ( index === undefined ) {
  27501. // unknown object -> add it to the ACTIVE region
  27502. index = nObjects ++;
  27503. indicesByUUID[ uuid ] = index;
  27504. objects.push( object );
  27505. // accounting is done, now do the same for all bindings
  27506. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27507. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27508. }
  27509. } else if ( index < nCachedObjects ) {
  27510. knownObject = objects[ index ];
  27511. // move existing object to the ACTIVE region
  27512. const firstActiveIndex = -- nCachedObjects,
  27513. lastCachedObject = objects[ firstActiveIndex ];
  27514. indicesByUUID[ lastCachedObject.uuid ] = index;
  27515. objects[ index ] = lastCachedObject;
  27516. indicesByUUID[ uuid ] = firstActiveIndex;
  27517. objects[ firstActiveIndex ] = object;
  27518. // accounting is done, now do the same for all bindings
  27519. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27520. const bindingsForPath = bindings[ j ],
  27521. lastCached = bindingsForPath[ firstActiveIndex ];
  27522. let binding = bindingsForPath[ index ];
  27523. bindingsForPath[ index ] = lastCached;
  27524. if ( binding === undefined ) {
  27525. // since we do not bother to create new bindings
  27526. // for objects that are cached, the binding may
  27527. // or may not exist
  27528. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27529. }
  27530. bindingsForPath[ firstActiveIndex ] = binding;
  27531. }
  27532. } else if ( objects[ index ] !== knownObject ) {
  27533. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27534. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27535. } // else the object is already where we want it to be
  27536. } // for arguments
  27537. this.nCachedObjects_ = nCachedObjects;
  27538. }
  27539. remove() {
  27540. const objects = this._objects,
  27541. indicesByUUID = this._indicesByUUID,
  27542. bindings = this._bindings,
  27543. nBindings = bindings.length;
  27544. let nCachedObjects = this.nCachedObjects_;
  27545. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27546. const object = arguments[ i ],
  27547. uuid = object.uuid,
  27548. index = indicesByUUID[ uuid ];
  27549. if ( index !== undefined && index >= nCachedObjects ) {
  27550. // move existing object into the CACHED region
  27551. const lastCachedIndex = nCachedObjects ++,
  27552. firstActiveObject = objects[ lastCachedIndex ];
  27553. indicesByUUID[ firstActiveObject.uuid ] = index;
  27554. objects[ index ] = firstActiveObject;
  27555. indicesByUUID[ uuid ] = lastCachedIndex;
  27556. objects[ lastCachedIndex ] = object;
  27557. // accounting is done, now do the same for all bindings
  27558. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27559. const bindingsForPath = bindings[ j ],
  27560. firstActive = bindingsForPath[ lastCachedIndex ],
  27561. binding = bindingsForPath[ index ];
  27562. bindingsForPath[ index ] = firstActive;
  27563. bindingsForPath[ lastCachedIndex ] = binding;
  27564. }
  27565. }
  27566. } // for arguments
  27567. this.nCachedObjects_ = nCachedObjects;
  27568. }
  27569. // remove & forget
  27570. uncache() {
  27571. const objects = this._objects,
  27572. indicesByUUID = this._indicesByUUID,
  27573. bindings = this._bindings,
  27574. nBindings = bindings.length;
  27575. let nCachedObjects = this.nCachedObjects_,
  27576. nObjects = objects.length;
  27577. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27578. const object = arguments[ i ],
  27579. uuid = object.uuid,
  27580. index = indicesByUUID[ uuid ];
  27581. if ( index !== undefined ) {
  27582. delete indicesByUUID[ uuid ];
  27583. if ( index < nCachedObjects ) {
  27584. // object is cached, shrink the CACHED region
  27585. const firstActiveIndex = -- nCachedObjects,
  27586. lastCachedObject = objects[ firstActiveIndex ],
  27587. lastIndex = -- nObjects,
  27588. lastObject = objects[ lastIndex ];
  27589. // last cached object takes this object's place
  27590. indicesByUUID[ lastCachedObject.uuid ] = index;
  27591. objects[ index ] = lastCachedObject;
  27592. // last object goes to the activated slot and pop
  27593. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27594. objects[ firstActiveIndex ] = lastObject;
  27595. objects.pop();
  27596. // accounting is done, now do the same for all bindings
  27597. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27598. const bindingsForPath = bindings[ j ],
  27599. lastCached = bindingsForPath[ firstActiveIndex ],
  27600. last = bindingsForPath[ lastIndex ];
  27601. bindingsForPath[ index ] = lastCached;
  27602. bindingsForPath[ firstActiveIndex ] = last;
  27603. bindingsForPath.pop();
  27604. }
  27605. } else {
  27606. // object is active, just swap with the last and pop
  27607. const lastIndex = -- nObjects,
  27608. lastObject = objects[ lastIndex ];
  27609. if ( lastIndex > 0 ) {
  27610. indicesByUUID[ lastObject.uuid ] = index;
  27611. }
  27612. objects[ index ] = lastObject;
  27613. objects.pop();
  27614. // accounting is done, now do the same for all bindings
  27615. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27616. const bindingsForPath = bindings[ j ];
  27617. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27618. bindingsForPath.pop();
  27619. }
  27620. } // cached or active
  27621. } // if object is known
  27622. } // for arguments
  27623. this.nCachedObjects_ = nCachedObjects;
  27624. }
  27625. // Internal interface used by befriended PropertyBinding.Composite:
  27626. subscribe_( path, parsedPath ) {
  27627. // returns an array of bindings for the given path that is changed
  27628. // according to the contained objects in the group
  27629. const indicesByPath = this._bindingsIndicesByPath;
  27630. let index = indicesByPath[ path ];
  27631. const bindings = this._bindings;
  27632. if ( index !== undefined ) return bindings[ index ];
  27633. const paths = this._paths,
  27634. parsedPaths = this._parsedPaths,
  27635. objects = this._objects,
  27636. nObjects = objects.length,
  27637. nCachedObjects = this.nCachedObjects_,
  27638. bindingsForPath = new Array( nObjects );
  27639. index = bindings.length;
  27640. indicesByPath[ path ] = index;
  27641. paths.push( path );
  27642. parsedPaths.push( parsedPath );
  27643. bindings.push( bindingsForPath );
  27644. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27645. const object = objects[ i ];
  27646. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27647. }
  27648. return bindingsForPath;
  27649. }
  27650. unsubscribe_( path ) {
  27651. // tells the group to forget about a property path and no longer
  27652. // update the array previously obtained with 'subscribe_'
  27653. const indicesByPath = this._bindingsIndicesByPath,
  27654. index = indicesByPath[ path ];
  27655. if ( index !== undefined ) {
  27656. const paths = this._paths,
  27657. parsedPaths = this._parsedPaths,
  27658. bindings = this._bindings,
  27659. lastBindingsIndex = bindings.length - 1,
  27660. lastBindings = bindings[ lastBindingsIndex ],
  27661. lastBindingsPath = path[ lastBindingsIndex ];
  27662. indicesByPath[ lastBindingsPath ] = index;
  27663. bindings[ index ] = lastBindings;
  27664. bindings.pop();
  27665. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27666. parsedPaths.pop();
  27667. paths[ index ] = paths[ lastBindingsIndex ];
  27668. paths.pop();
  27669. }
  27670. }
  27671. }
  27672. class AnimationAction {
  27673. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27674. this._mixer = mixer;
  27675. this._clip = clip;
  27676. this._localRoot = localRoot;
  27677. this.blendMode = blendMode;
  27678. const tracks = clip.tracks,
  27679. nTracks = tracks.length,
  27680. interpolants = new Array( nTracks );
  27681. const interpolantSettings = {
  27682. endingStart: ZeroCurvatureEnding,
  27683. endingEnd: ZeroCurvatureEnding
  27684. };
  27685. for ( let i = 0; i !== nTracks; ++ i ) {
  27686. const interpolant = tracks[ i ].createInterpolant( null );
  27687. interpolants[ i ] = interpolant;
  27688. interpolant.settings = interpolantSettings;
  27689. }
  27690. this._interpolantSettings = interpolantSettings;
  27691. this._interpolants = interpolants; // bound by the mixer
  27692. // inside: PropertyMixer (managed by the mixer)
  27693. this._propertyBindings = new Array( nTracks );
  27694. this._cacheIndex = null; // for the memory manager
  27695. this._byClipCacheIndex = null; // for the memory manager
  27696. this._timeScaleInterpolant = null;
  27697. this._weightInterpolant = null;
  27698. this.loop = LoopRepeat;
  27699. this._loopCount = - 1;
  27700. // global mixer time when the action is to be started
  27701. // it's set back to 'null' upon start of the action
  27702. this._startTime = null;
  27703. // scaled local time of the action
  27704. // gets clamped or wrapped to 0..clip.duration according to loop
  27705. this.time = 0;
  27706. this.timeScale = 1;
  27707. this._effectiveTimeScale = 1;
  27708. this.weight = 1;
  27709. this._effectiveWeight = 1;
  27710. this.repetitions = Infinity; // no. of repetitions when looping
  27711. this.paused = false; // true -> zero effective time scale
  27712. this.enabled = true; // false -> zero effective weight
  27713. this.clampWhenFinished = false;// keep feeding the last frame?
  27714. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27715. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27716. }
  27717. // State & Scheduling
  27718. play() {
  27719. this._mixer._activateAction( this );
  27720. return this;
  27721. }
  27722. stop() {
  27723. this._mixer._deactivateAction( this );
  27724. return this.reset();
  27725. }
  27726. reset() {
  27727. this.paused = false;
  27728. this.enabled = true;
  27729. this.time = 0; // restart clip
  27730. this._loopCount = - 1;// forget previous loops
  27731. this._startTime = null;// forget scheduling
  27732. return this.stopFading().stopWarping();
  27733. }
  27734. isRunning() {
  27735. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27736. this._startTime === null && this._mixer._isActiveAction( this );
  27737. }
  27738. // return true when play has been called
  27739. isScheduled() {
  27740. return this._mixer._isActiveAction( this );
  27741. }
  27742. startAt( time ) {
  27743. this._startTime = time;
  27744. return this;
  27745. }
  27746. setLoop( mode, repetitions ) {
  27747. this.loop = mode;
  27748. this.repetitions = repetitions;
  27749. return this;
  27750. }
  27751. // Weight
  27752. // set the weight stopping any scheduled fading
  27753. // although .enabled = false yields an effective weight of zero, this
  27754. // method does *not* change .enabled, because it would be confusing
  27755. setEffectiveWeight( weight ) {
  27756. this.weight = weight;
  27757. // note: same logic as when updated at runtime
  27758. this._effectiveWeight = this.enabled ? weight : 0;
  27759. return this.stopFading();
  27760. }
  27761. // return the weight considering fading and .enabled
  27762. getEffectiveWeight() {
  27763. return this._effectiveWeight;
  27764. }
  27765. fadeIn( duration ) {
  27766. return this._scheduleFading( duration, 0, 1 );
  27767. }
  27768. fadeOut( duration ) {
  27769. return this._scheduleFading( duration, 1, 0 );
  27770. }
  27771. crossFadeFrom( fadeOutAction, duration, warp ) {
  27772. fadeOutAction.fadeOut( duration );
  27773. this.fadeIn( duration );
  27774. if ( warp ) {
  27775. const fadeInDuration = this._clip.duration,
  27776. fadeOutDuration = fadeOutAction._clip.duration,
  27777. startEndRatio = fadeOutDuration / fadeInDuration,
  27778. endStartRatio = fadeInDuration / fadeOutDuration;
  27779. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27780. this.warp( endStartRatio, 1.0, duration );
  27781. }
  27782. return this;
  27783. }
  27784. crossFadeTo( fadeInAction, duration, warp ) {
  27785. return fadeInAction.crossFadeFrom( this, duration, warp );
  27786. }
  27787. stopFading() {
  27788. const weightInterpolant = this._weightInterpolant;
  27789. if ( weightInterpolant !== null ) {
  27790. this._weightInterpolant = null;
  27791. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27792. }
  27793. return this;
  27794. }
  27795. // Time Scale Control
  27796. // set the time scale stopping any scheduled warping
  27797. // although .paused = true yields an effective time scale of zero, this
  27798. // method does *not* change .paused, because it would be confusing
  27799. setEffectiveTimeScale( timeScale ) {
  27800. this.timeScale = timeScale;
  27801. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27802. return this.stopWarping();
  27803. }
  27804. // return the time scale considering warping and .paused
  27805. getEffectiveTimeScale() {
  27806. return this._effectiveTimeScale;
  27807. }
  27808. setDuration( duration ) {
  27809. this.timeScale = this._clip.duration / duration;
  27810. return this.stopWarping();
  27811. }
  27812. syncWith( action ) {
  27813. this.time = action.time;
  27814. this.timeScale = action.timeScale;
  27815. return this.stopWarping();
  27816. }
  27817. halt( duration ) {
  27818. return this.warp( this._effectiveTimeScale, 0, duration );
  27819. }
  27820. warp( startTimeScale, endTimeScale, duration ) {
  27821. const mixer = this._mixer,
  27822. now = mixer.time,
  27823. timeScale = this.timeScale;
  27824. let interpolant = this._timeScaleInterpolant;
  27825. if ( interpolant === null ) {
  27826. interpolant = mixer._lendControlInterpolant();
  27827. this._timeScaleInterpolant = interpolant;
  27828. }
  27829. const times = interpolant.parameterPositions,
  27830. values = interpolant.sampleValues;
  27831. times[ 0 ] = now;
  27832. times[ 1 ] = now + duration;
  27833. values[ 0 ] = startTimeScale / timeScale;
  27834. values[ 1 ] = endTimeScale / timeScale;
  27835. return this;
  27836. }
  27837. stopWarping() {
  27838. const timeScaleInterpolant = this._timeScaleInterpolant;
  27839. if ( timeScaleInterpolant !== null ) {
  27840. this._timeScaleInterpolant = null;
  27841. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27842. }
  27843. return this;
  27844. }
  27845. // Object Accessors
  27846. getMixer() {
  27847. return this._mixer;
  27848. }
  27849. getClip() {
  27850. return this._clip;
  27851. }
  27852. getRoot() {
  27853. return this._localRoot || this._mixer._root;
  27854. }
  27855. // Interna
  27856. _update( time, deltaTime, timeDirection, accuIndex ) {
  27857. // called by the mixer
  27858. if ( ! this.enabled ) {
  27859. // call ._updateWeight() to update ._effectiveWeight
  27860. this._updateWeight( time );
  27861. return;
  27862. }
  27863. const startTime = this._startTime;
  27864. if ( startTime !== null ) {
  27865. // check for scheduled start of action
  27866. const timeRunning = ( time - startTime ) * timeDirection;
  27867. if ( timeRunning < 0 || timeDirection === 0 ) {
  27868. deltaTime = 0;
  27869. } else {
  27870. this._startTime = null; // unschedule
  27871. deltaTime = timeDirection * timeRunning;
  27872. }
  27873. }
  27874. // apply time scale and advance time
  27875. deltaTime *= this._updateTimeScale( time );
  27876. const clipTime = this._updateTime( deltaTime );
  27877. // note: _updateTime may disable the action resulting in
  27878. // an effective weight of 0
  27879. const weight = this._updateWeight( time );
  27880. if ( weight > 0 ) {
  27881. const interpolants = this._interpolants;
  27882. const propertyMixers = this._propertyBindings;
  27883. switch ( this.blendMode ) {
  27884. case AdditiveAnimationBlendMode:
  27885. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27886. interpolants[ j ].evaluate( clipTime );
  27887. propertyMixers[ j ].accumulateAdditive( weight );
  27888. }
  27889. break;
  27890. case NormalAnimationBlendMode:
  27891. default:
  27892. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27893. interpolants[ j ].evaluate( clipTime );
  27894. propertyMixers[ j ].accumulate( accuIndex, weight );
  27895. }
  27896. }
  27897. }
  27898. }
  27899. _updateWeight( time ) {
  27900. let weight = 0;
  27901. if ( this.enabled ) {
  27902. weight = this.weight;
  27903. const interpolant = this._weightInterpolant;
  27904. if ( interpolant !== null ) {
  27905. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27906. weight *= interpolantValue;
  27907. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27908. this.stopFading();
  27909. if ( interpolantValue === 0 ) {
  27910. // faded out, disable
  27911. this.enabled = false;
  27912. }
  27913. }
  27914. }
  27915. }
  27916. this._effectiveWeight = weight;
  27917. return weight;
  27918. }
  27919. _updateTimeScale( time ) {
  27920. let timeScale = 0;
  27921. if ( ! this.paused ) {
  27922. timeScale = this.timeScale;
  27923. const interpolant = this._timeScaleInterpolant;
  27924. if ( interpolant !== null ) {
  27925. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27926. timeScale *= interpolantValue;
  27927. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27928. this.stopWarping();
  27929. if ( timeScale === 0 ) {
  27930. // motion has halted, pause
  27931. this.paused = true;
  27932. } else {
  27933. // warp done - apply final time scale
  27934. this.timeScale = timeScale;
  27935. }
  27936. }
  27937. }
  27938. }
  27939. this._effectiveTimeScale = timeScale;
  27940. return timeScale;
  27941. }
  27942. _updateTime( deltaTime ) {
  27943. const duration = this._clip.duration;
  27944. const loop = this.loop;
  27945. let time = this.time + deltaTime;
  27946. let loopCount = this._loopCount;
  27947. const pingPong = ( loop === LoopPingPong );
  27948. if ( deltaTime === 0 ) {
  27949. if ( loopCount === - 1 ) return time;
  27950. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27951. }
  27952. if ( loop === LoopOnce ) {
  27953. if ( loopCount === - 1 ) {
  27954. // just started
  27955. this._loopCount = 0;
  27956. this._setEndings( true, true, false );
  27957. }
  27958. handle_stop: {
  27959. if ( time >= duration ) {
  27960. time = duration;
  27961. } else if ( time < 0 ) {
  27962. time = 0;
  27963. } else {
  27964. this.time = time;
  27965. break handle_stop;
  27966. }
  27967. if ( this.clampWhenFinished ) this.paused = true;
  27968. else this.enabled = false;
  27969. this.time = time;
  27970. this._mixer.dispatchEvent( {
  27971. type: 'finished', action: this,
  27972. direction: deltaTime < 0 ? - 1 : 1
  27973. } );
  27974. }
  27975. } else { // repetitive Repeat or PingPong
  27976. if ( loopCount === - 1 ) {
  27977. // just started
  27978. if ( deltaTime >= 0 ) {
  27979. loopCount = 0;
  27980. this._setEndings( true, this.repetitions === 0, pingPong );
  27981. } else {
  27982. // when looping in reverse direction, the initial
  27983. // transition through zero counts as a repetition,
  27984. // so leave loopCount at -1
  27985. this._setEndings( this.repetitions === 0, true, pingPong );
  27986. }
  27987. }
  27988. if ( time >= duration || time < 0 ) {
  27989. // wrap around
  27990. const loopDelta = Math.floor( time / duration ); // signed
  27991. time -= duration * loopDelta;
  27992. loopCount += Math.abs( loopDelta );
  27993. const pending = this.repetitions - loopCount;
  27994. if ( pending <= 0 ) {
  27995. // have to stop (switch state, clamp time, fire event)
  27996. if ( this.clampWhenFinished ) this.paused = true;
  27997. else this.enabled = false;
  27998. time = deltaTime > 0 ? duration : 0;
  27999. this.time = time;
  28000. this._mixer.dispatchEvent( {
  28001. type: 'finished', action: this,
  28002. direction: deltaTime > 0 ? 1 : - 1
  28003. } );
  28004. } else {
  28005. // keep running
  28006. if ( pending === 1 ) {
  28007. // entering the last round
  28008. const atStart = deltaTime < 0;
  28009. this._setEndings( atStart, ! atStart, pingPong );
  28010. } else {
  28011. this._setEndings( false, false, pingPong );
  28012. }
  28013. this._loopCount = loopCount;
  28014. this.time = time;
  28015. this._mixer.dispatchEvent( {
  28016. type: 'loop', action: this, loopDelta: loopDelta
  28017. } );
  28018. }
  28019. } else {
  28020. this.time = time;
  28021. }
  28022. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  28023. // invert time for the "pong round"
  28024. return duration - time;
  28025. }
  28026. }
  28027. return time;
  28028. }
  28029. _setEndings( atStart, atEnd, pingPong ) {
  28030. const settings = this._interpolantSettings;
  28031. if ( pingPong ) {
  28032. settings.endingStart = ZeroSlopeEnding;
  28033. settings.endingEnd = ZeroSlopeEnding;
  28034. } else {
  28035. // assuming for LoopOnce atStart == atEnd == true
  28036. if ( atStart ) {
  28037. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28038. } else {
  28039. settings.endingStart = WrapAroundEnding;
  28040. }
  28041. if ( atEnd ) {
  28042. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28043. } else {
  28044. settings.endingEnd = WrapAroundEnding;
  28045. }
  28046. }
  28047. }
  28048. _scheduleFading( duration, weightNow, weightThen ) {
  28049. const mixer = this._mixer, now = mixer.time;
  28050. let interpolant = this._weightInterpolant;
  28051. if ( interpolant === null ) {
  28052. interpolant = mixer._lendControlInterpolant();
  28053. this._weightInterpolant = interpolant;
  28054. }
  28055. const times = interpolant.parameterPositions,
  28056. values = interpolant.sampleValues;
  28057. times[ 0 ] = now;
  28058. values[ 0 ] = weightNow;
  28059. times[ 1 ] = now + duration;
  28060. values[ 1 ] = weightThen;
  28061. return this;
  28062. }
  28063. }
  28064. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  28065. class AnimationMixer extends EventDispatcher {
  28066. constructor( root ) {
  28067. super();
  28068. this._root = root;
  28069. this._initMemoryManager();
  28070. this._accuIndex = 0;
  28071. this.time = 0;
  28072. this.timeScale = 1.0;
  28073. }
  28074. _bindAction( action, prototypeAction ) {
  28075. const root = action._localRoot || this._root,
  28076. tracks = action._clip.tracks,
  28077. nTracks = tracks.length,
  28078. bindings = action._propertyBindings,
  28079. interpolants = action._interpolants,
  28080. rootUuid = root.uuid,
  28081. bindingsByRoot = this._bindingsByRootAndName;
  28082. let bindingsByName = bindingsByRoot[ rootUuid ];
  28083. if ( bindingsByName === undefined ) {
  28084. bindingsByName = {};
  28085. bindingsByRoot[ rootUuid ] = bindingsByName;
  28086. }
  28087. for ( let i = 0; i !== nTracks; ++ i ) {
  28088. const track = tracks[ i ],
  28089. trackName = track.name;
  28090. let binding = bindingsByName[ trackName ];
  28091. if ( binding !== undefined ) {
  28092. ++ binding.referenceCount;
  28093. bindings[ i ] = binding;
  28094. } else {
  28095. binding = bindings[ i ];
  28096. if ( binding !== undefined ) {
  28097. // existing binding, make sure the cache knows
  28098. if ( binding._cacheIndex === null ) {
  28099. ++ binding.referenceCount;
  28100. this._addInactiveBinding( binding, rootUuid, trackName );
  28101. }
  28102. continue;
  28103. }
  28104. const path = prototypeAction && prototypeAction.
  28105. _propertyBindings[ i ].binding.parsedPath;
  28106. binding = new PropertyMixer(
  28107. PropertyBinding.create( root, trackName, path ),
  28108. track.ValueTypeName, track.getValueSize() );
  28109. ++ binding.referenceCount;
  28110. this._addInactiveBinding( binding, rootUuid, trackName );
  28111. bindings[ i ] = binding;
  28112. }
  28113. interpolants[ i ].resultBuffer = binding.buffer;
  28114. }
  28115. }
  28116. _activateAction( action ) {
  28117. if ( ! this._isActiveAction( action ) ) {
  28118. if ( action._cacheIndex === null ) {
  28119. // this action has been forgotten by the cache, but the user
  28120. // appears to be still using it -> rebind
  28121. const rootUuid = ( action._localRoot || this._root ).uuid,
  28122. clipUuid = action._clip.uuid,
  28123. actionsForClip = this._actionsByClip[ clipUuid ];
  28124. this._bindAction( action,
  28125. actionsForClip && actionsForClip.knownActions[ 0 ] );
  28126. this._addInactiveAction( action, clipUuid, rootUuid );
  28127. }
  28128. const bindings = action._propertyBindings;
  28129. // increment reference counts / sort out state
  28130. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28131. const binding = bindings[ i ];
  28132. if ( binding.useCount ++ === 0 ) {
  28133. this._lendBinding( binding );
  28134. binding.saveOriginalState();
  28135. }
  28136. }
  28137. this._lendAction( action );
  28138. }
  28139. }
  28140. _deactivateAction( action ) {
  28141. if ( this._isActiveAction( action ) ) {
  28142. const bindings = action._propertyBindings;
  28143. // decrement reference counts / sort out state
  28144. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28145. const binding = bindings[ i ];
  28146. if ( -- binding.useCount === 0 ) {
  28147. binding.restoreOriginalState();
  28148. this._takeBackBinding( binding );
  28149. }
  28150. }
  28151. this._takeBackAction( action );
  28152. }
  28153. }
  28154. // Memory manager
  28155. _initMemoryManager() {
  28156. this._actions = []; // 'nActiveActions' followed by inactive ones
  28157. this._nActiveActions = 0;
  28158. this._actionsByClip = {};
  28159. // inside:
  28160. // {
  28161. // knownActions: Array< AnimationAction > - used as prototypes
  28162. // actionByRoot: AnimationAction - lookup
  28163. // }
  28164. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  28165. this._nActiveBindings = 0;
  28166. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  28167. this._controlInterpolants = []; // same game as above
  28168. this._nActiveControlInterpolants = 0;
  28169. const scope = this;
  28170. this.stats = {
  28171. actions: {
  28172. get total() {
  28173. return scope._actions.length;
  28174. },
  28175. get inUse() {
  28176. return scope._nActiveActions;
  28177. }
  28178. },
  28179. bindings: {
  28180. get total() {
  28181. return scope._bindings.length;
  28182. },
  28183. get inUse() {
  28184. return scope._nActiveBindings;
  28185. }
  28186. },
  28187. controlInterpolants: {
  28188. get total() {
  28189. return scope._controlInterpolants.length;
  28190. },
  28191. get inUse() {
  28192. return scope._nActiveControlInterpolants;
  28193. }
  28194. }
  28195. };
  28196. }
  28197. // Memory management for AnimationAction objects
  28198. _isActiveAction( action ) {
  28199. const index = action._cacheIndex;
  28200. return index !== null && index < this._nActiveActions;
  28201. }
  28202. _addInactiveAction( action, clipUuid, rootUuid ) {
  28203. const actions = this._actions,
  28204. actionsByClip = this._actionsByClip;
  28205. let actionsForClip = actionsByClip[ clipUuid ];
  28206. if ( actionsForClip === undefined ) {
  28207. actionsForClip = {
  28208. knownActions: [ action ],
  28209. actionByRoot: {}
  28210. };
  28211. action._byClipCacheIndex = 0;
  28212. actionsByClip[ clipUuid ] = actionsForClip;
  28213. } else {
  28214. const knownActions = actionsForClip.knownActions;
  28215. action._byClipCacheIndex = knownActions.length;
  28216. knownActions.push( action );
  28217. }
  28218. action._cacheIndex = actions.length;
  28219. actions.push( action );
  28220. actionsForClip.actionByRoot[ rootUuid ] = action;
  28221. }
  28222. _removeInactiveAction( action ) {
  28223. const actions = this._actions,
  28224. lastInactiveAction = actions[ actions.length - 1 ],
  28225. cacheIndex = action._cacheIndex;
  28226. lastInactiveAction._cacheIndex = cacheIndex;
  28227. actions[ cacheIndex ] = lastInactiveAction;
  28228. actions.pop();
  28229. action._cacheIndex = null;
  28230. const clipUuid = action._clip.uuid,
  28231. actionsByClip = this._actionsByClip,
  28232. actionsForClip = actionsByClip[ clipUuid ],
  28233. knownActionsForClip = actionsForClip.knownActions,
  28234. lastKnownAction =
  28235. knownActionsForClip[ knownActionsForClip.length - 1 ],
  28236. byClipCacheIndex = action._byClipCacheIndex;
  28237. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  28238. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  28239. knownActionsForClip.pop();
  28240. action._byClipCacheIndex = null;
  28241. const actionByRoot = actionsForClip.actionByRoot,
  28242. rootUuid = ( action._localRoot || this._root ).uuid;
  28243. delete actionByRoot[ rootUuid ];
  28244. if ( knownActionsForClip.length === 0 ) {
  28245. delete actionsByClip[ clipUuid ];
  28246. }
  28247. this._removeInactiveBindingsForAction( action );
  28248. }
  28249. _removeInactiveBindingsForAction( action ) {
  28250. const bindings = action._propertyBindings;
  28251. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28252. const binding = bindings[ i ];
  28253. if ( -- binding.referenceCount === 0 ) {
  28254. this._removeInactiveBinding( binding );
  28255. }
  28256. }
  28257. }
  28258. _lendAction( action ) {
  28259. // [ active actions | inactive actions ]
  28260. // [ active actions >| inactive actions ]
  28261. // s a
  28262. // <-swap->
  28263. // a s
  28264. const actions = this._actions,
  28265. prevIndex = action._cacheIndex,
  28266. lastActiveIndex = this._nActiveActions ++,
  28267. firstInactiveAction = actions[ lastActiveIndex ];
  28268. action._cacheIndex = lastActiveIndex;
  28269. actions[ lastActiveIndex ] = action;
  28270. firstInactiveAction._cacheIndex = prevIndex;
  28271. actions[ prevIndex ] = firstInactiveAction;
  28272. }
  28273. _takeBackAction( action ) {
  28274. // [ active actions | inactive actions ]
  28275. // [ active actions |< inactive actions ]
  28276. // a s
  28277. // <-swap->
  28278. // s a
  28279. const actions = this._actions,
  28280. prevIndex = action._cacheIndex,
  28281. firstInactiveIndex = -- this._nActiveActions,
  28282. lastActiveAction = actions[ firstInactiveIndex ];
  28283. action._cacheIndex = firstInactiveIndex;
  28284. actions[ firstInactiveIndex ] = action;
  28285. lastActiveAction._cacheIndex = prevIndex;
  28286. actions[ prevIndex ] = lastActiveAction;
  28287. }
  28288. // Memory management for PropertyMixer objects
  28289. _addInactiveBinding( binding, rootUuid, trackName ) {
  28290. const bindingsByRoot = this._bindingsByRootAndName,
  28291. bindings = this._bindings;
  28292. let bindingByName = bindingsByRoot[ rootUuid ];
  28293. if ( bindingByName === undefined ) {
  28294. bindingByName = {};
  28295. bindingsByRoot[ rootUuid ] = bindingByName;
  28296. }
  28297. bindingByName[ trackName ] = binding;
  28298. binding._cacheIndex = bindings.length;
  28299. bindings.push( binding );
  28300. }
  28301. _removeInactiveBinding( binding ) {
  28302. const bindings = this._bindings,
  28303. propBinding = binding.binding,
  28304. rootUuid = propBinding.rootNode.uuid,
  28305. trackName = propBinding.path,
  28306. bindingsByRoot = this._bindingsByRootAndName,
  28307. bindingByName = bindingsByRoot[ rootUuid ],
  28308. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28309. cacheIndex = binding._cacheIndex;
  28310. lastInactiveBinding._cacheIndex = cacheIndex;
  28311. bindings[ cacheIndex ] = lastInactiveBinding;
  28312. bindings.pop();
  28313. delete bindingByName[ trackName ];
  28314. if ( Object.keys( bindingByName ).length === 0 ) {
  28315. delete bindingsByRoot[ rootUuid ];
  28316. }
  28317. }
  28318. _lendBinding( binding ) {
  28319. const bindings = this._bindings,
  28320. prevIndex = binding._cacheIndex,
  28321. lastActiveIndex = this._nActiveBindings ++,
  28322. firstInactiveBinding = bindings[ lastActiveIndex ];
  28323. binding._cacheIndex = lastActiveIndex;
  28324. bindings[ lastActiveIndex ] = binding;
  28325. firstInactiveBinding._cacheIndex = prevIndex;
  28326. bindings[ prevIndex ] = firstInactiveBinding;
  28327. }
  28328. _takeBackBinding( binding ) {
  28329. const bindings = this._bindings,
  28330. prevIndex = binding._cacheIndex,
  28331. firstInactiveIndex = -- this._nActiveBindings,
  28332. lastActiveBinding = bindings[ firstInactiveIndex ];
  28333. binding._cacheIndex = firstInactiveIndex;
  28334. bindings[ firstInactiveIndex ] = binding;
  28335. lastActiveBinding._cacheIndex = prevIndex;
  28336. bindings[ prevIndex ] = lastActiveBinding;
  28337. }
  28338. // Memory management of Interpolants for weight and time scale
  28339. _lendControlInterpolant() {
  28340. const interpolants = this._controlInterpolants,
  28341. lastActiveIndex = this._nActiveControlInterpolants ++;
  28342. let interpolant = interpolants[ lastActiveIndex ];
  28343. if ( interpolant === undefined ) {
  28344. interpolant = new LinearInterpolant(
  28345. new Float32Array( 2 ), new Float32Array( 2 ),
  28346. 1, _controlInterpolantsResultBuffer );
  28347. interpolant.__cacheIndex = lastActiveIndex;
  28348. interpolants[ lastActiveIndex ] = interpolant;
  28349. }
  28350. return interpolant;
  28351. }
  28352. _takeBackControlInterpolant( interpolant ) {
  28353. const interpolants = this._controlInterpolants,
  28354. prevIndex = interpolant.__cacheIndex,
  28355. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28356. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28357. interpolant.__cacheIndex = firstInactiveIndex;
  28358. interpolants[ firstInactiveIndex ] = interpolant;
  28359. lastActiveInterpolant.__cacheIndex = prevIndex;
  28360. interpolants[ prevIndex ] = lastActiveInterpolant;
  28361. }
  28362. // return an action for a clip optionally using a custom root target
  28363. // object (this method allocates a lot of dynamic memory in case a
  28364. // previously unknown clip/root combination is specified)
  28365. clipAction( clip, optionalRoot, blendMode ) {
  28366. const root = optionalRoot || this._root,
  28367. rootUuid = root.uuid;
  28368. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28369. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28370. const actionsForClip = this._actionsByClip[ clipUuid ];
  28371. let prototypeAction = null;
  28372. if ( blendMode === undefined ) {
  28373. if ( clipObject !== null ) {
  28374. blendMode = clipObject.blendMode;
  28375. } else {
  28376. blendMode = NormalAnimationBlendMode;
  28377. }
  28378. }
  28379. if ( actionsForClip !== undefined ) {
  28380. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28381. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28382. return existingAction;
  28383. }
  28384. // we know the clip, so we don't have to parse all
  28385. // the bindings again but can just copy
  28386. prototypeAction = actionsForClip.knownActions[ 0 ];
  28387. // also, take the clip from the prototype action
  28388. if ( clipObject === null )
  28389. clipObject = prototypeAction._clip;
  28390. }
  28391. // clip must be known when specified via string
  28392. if ( clipObject === null ) return null;
  28393. // allocate all resources required to run it
  28394. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28395. this._bindAction( newAction, prototypeAction );
  28396. // and make the action known to the memory manager
  28397. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28398. return newAction;
  28399. }
  28400. // get an existing action
  28401. existingAction( clip, optionalRoot ) {
  28402. const root = optionalRoot || this._root,
  28403. rootUuid = root.uuid,
  28404. clipObject = typeof clip === 'string' ?
  28405. AnimationClip.findByName( root, clip ) : clip,
  28406. clipUuid = clipObject ? clipObject.uuid : clip,
  28407. actionsForClip = this._actionsByClip[ clipUuid ];
  28408. if ( actionsForClip !== undefined ) {
  28409. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28410. }
  28411. return null;
  28412. }
  28413. // deactivates all previously scheduled actions
  28414. stopAllAction() {
  28415. const actions = this._actions,
  28416. nActions = this._nActiveActions;
  28417. for ( let i = nActions - 1; i >= 0; -- i ) {
  28418. actions[ i ].stop();
  28419. }
  28420. return this;
  28421. }
  28422. // advance the time and update apply the animation
  28423. update( deltaTime ) {
  28424. deltaTime *= this.timeScale;
  28425. const actions = this._actions,
  28426. nActions = this._nActiveActions,
  28427. time = this.time += deltaTime,
  28428. timeDirection = Math.sign( deltaTime ),
  28429. accuIndex = this._accuIndex ^= 1;
  28430. // run active actions
  28431. for ( let i = 0; i !== nActions; ++ i ) {
  28432. const action = actions[ i ];
  28433. action._update( time, deltaTime, timeDirection, accuIndex );
  28434. }
  28435. // update scene graph
  28436. const bindings = this._bindings,
  28437. nBindings = this._nActiveBindings;
  28438. for ( let i = 0; i !== nBindings; ++ i ) {
  28439. bindings[ i ].apply( accuIndex );
  28440. }
  28441. return this;
  28442. }
  28443. // Allows you to seek to a specific time in an animation.
  28444. setTime( timeInSeconds ) {
  28445. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28446. for ( let i = 0; i < this._actions.length; i ++ ) {
  28447. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28448. }
  28449. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28450. }
  28451. // return this mixer's root target object
  28452. getRoot() {
  28453. return this._root;
  28454. }
  28455. // free all resources specific to a particular clip
  28456. uncacheClip( clip ) {
  28457. const actions = this._actions,
  28458. clipUuid = clip.uuid,
  28459. actionsByClip = this._actionsByClip,
  28460. actionsForClip = actionsByClip[ clipUuid ];
  28461. if ( actionsForClip !== undefined ) {
  28462. // note: just calling _removeInactiveAction would mess up the
  28463. // iteration state and also require updating the state we can
  28464. // just throw away
  28465. const actionsToRemove = actionsForClip.knownActions;
  28466. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28467. const action = actionsToRemove[ i ];
  28468. this._deactivateAction( action );
  28469. const cacheIndex = action._cacheIndex,
  28470. lastInactiveAction = actions[ actions.length - 1 ];
  28471. action._cacheIndex = null;
  28472. action._byClipCacheIndex = null;
  28473. lastInactiveAction._cacheIndex = cacheIndex;
  28474. actions[ cacheIndex ] = lastInactiveAction;
  28475. actions.pop();
  28476. this._removeInactiveBindingsForAction( action );
  28477. }
  28478. delete actionsByClip[ clipUuid ];
  28479. }
  28480. }
  28481. // free all resources specific to a particular root target object
  28482. uncacheRoot( root ) {
  28483. const rootUuid = root.uuid,
  28484. actionsByClip = this._actionsByClip;
  28485. for ( const clipUuid in actionsByClip ) {
  28486. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28487. action = actionByRoot[ rootUuid ];
  28488. if ( action !== undefined ) {
  28489. this._deactivateAction( action );
  28490. this._removeInactiveAction( action );
  28491. }
  28492. }
  28493. const bindingsByRoot = this._bindingsByRootAndName,
  28494. bindingByName = bindingsByRoot[ rootUuid ];
  28495. if ( bindingByName !== undefined ) {
  28496. for ( const trackName in bindingByName ) {
  28497. const binding = bindingByName[ trackName ];
  28498. binding.restoreOriginalState();
  28499. this._removeInactiveBinding( binding );
  28500. }
  28501. }
  28502. }
  28503. // remove a targeted clip from the cache
  28504. uncacheAction( clip, optionalRoot ) {
  28505. const action = this.existingAction( clip, optionalRoot );
  28506. if ( action !== null ) {
  28507. this._deactivateAction( action );
  28508. this._removeInactiveAction( action );
  28509. }
  28510. }
  28511. }
  28512. class Uniform {
  28513. constructor( value ) {
  28514. this.value = value;
  28515. }
  28516. clone() {
  28517. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28518. }
  28519. }
  28520. let id = 0;
  28521. class UniformsGroup extends EventDispatcher {
  28522. constructor() {
  28523. super();
  28524. this.isUniformsGroup = true;
  28525. Object.defineProperty( this, 'id', { value: id ++ } );
  28526. this.name = '';
  28527. this.usage = StaticDrawUsage;
  28528. this.uniforms = [];
  28529. }
  28530. add( uniform ) {
  28531. this.uniforms.push( uniform );
  28532. return this;
  28533. }
  28534. remove( uniform ) {
  28535. const index = this.uniforms.indexOf( uniform );
  28536. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28537. return this;
  28538. }
  28539. setName( name ) {
  28540. this.name = name;
  28541. return this;
  28542. }
  28543. setUsage( value ) {
  28544. this.usage = value;
  28545. return this;
  28546. }
  28547. dispose() {
  28548. this.dispatchEvent( { type: 'dispose' } );
  28549. return this;
  28550. }
  28551. copy( source ) {
  28552. this.name = source.name;
  28553. this.usage = source.usage;
  28554. const uniformsSource = source.uniforms;
  28555. this.uniforms.length = 0;
  28556. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28557. this.uniforms.push( uniformsSource[ i ].clone() );
  28558. }
  28559. return this;
  28560. }
  28561. clone() {
  28562. return new this.constructor().copy( this );
  28563. }
  28564. }
  28565. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28566. constructor( array, stride, meshPerAttribute = 1 ) {
  28567. super( array, stride );
  28568. this.isInstancedInterleavedBuffer = true;
  28569. this.meshPerAttribute = meshPerAttribute;
  28570. }
  28571. copy( source ) {
  28572. super.copy( source );
  28573. this.meshPerAttribute = source.meshPerAttribute;
  28574. return this;
  28575. }
  28576. clone( data ) {
  28577. const ib = super.clone( data );
  28578. ib.meshPerAttribute = this.meshPerAttribute;
  28579. return ib;
  28580. }
  28581. toJSON( data ) {
  28582. const json = super.toJSON( data );
  28583. json.isInstancedInterleavedBuffer = true;
  28584. json.meshPerAttribute = this.meshPerAttribute;
  28585. return json;
  28586. }
  28587. }
  28588. class GLBufferAttribute {
  28589. constructor( buffer, type, itemSize, elementSize, count ) {
  28590. this.isGLBufferAttribute = true;
  28591. this.name = '';
  28592. this.buffer = buffer;
  28593. this.type = type;
  28594. this.itemSize = itemSize;
  28595. this.elementSize = elementSize;
  28596. this.count = count;
  28597. this.version = 0;
  28598. }
  28599. set needsUpdate( value ) {
  28600. if ( value === true ) this.version ++;
  28601. }
  28602. setBuffer( buffer ) {
  28603. this.buffer = buffer;
  28604. return this;
  28605. }
  28606. setType( type, elementSize ) {
  28607. this.type = type;
  28608. this.elementSize = elementSize;
  28609. return this;
  28610. }
  28611. setItemSize( itemSize ) {
  28612. this.itemSize = itemSize;
  28613. return this;
  28614. }
  28615. setCount( count ) {
  28616. this.count = count;
  28617. return this;
  28618. }
  28619. }
  28620. class Raycaster {
  28621. constructor( origin, direction, near = 0, far = Infinity ) {
  28622. this.ray = new Ray( origin, direction );
  28623. // direction is assumed to be normalized (for accurate distance calculations)
  28624. this.near = near;
  28625. this.far = far;
  28626. this.camera = null;
  28627. this.layers = new Layers();
  28628. this.params = {
  28629. Mesh: {},
  28630. Line: { threshold: 1 },
  28631. LOD: {},
  28632. Points: { threshold: 1 },
  28633. Sprite: {}
  28634. };
  28635. }
  28636. set( origin, direction ) {
  28637. // direction is assumed to be normalized (for accurate distance calculations)
  28638. this.ray.set( origin, direction );
  28639. }
  28640. setFromCamera( coords, camera ) {
  28641. if ( camera.isPerspectiveCamera ) {
  28642. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28643. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28644. this.camera = camera;
  28645. } else if ( camera.isOrthographicCamera ) {
  28646. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28647. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28648. this.camera = camera;
  28649. } else {
  28650. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28651. }
  28652. }
  28653. intersectObject( object, recursive = true, intersects = [] ) {
  28654. intersectObject( object, this, intersects, recursive );
  28655. intersects.sort( ascSort );
  28656. return intersects;
  28657. }
  28658. intersectObjects( objects, recursive = true, intersects = [] ) {
  28659. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28660. intersectObject( objects[ i ], this, intersects, recursive );
  28661. }
  28662. intersects.sort( ascSort );
  28663. return intersects;
  28664. }
  28665. }
  28666. function ascSort( a, b ) {
  28667. return a.distance - b.distance;
  28668. }
  28669. function intersectObject( object, raycaster, intersects, recursive ) {
  28670. if ( object.layers.test( raycaster.layers ) ) {
  28671. object.raycast( raycaster, intersects );
  28672. }
  28673. if ( recursive === true ) {
  28674. const children = object.children;
  28675. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28676. intersectObject( children[ i ], raycaster, intersects, true );
  28677. }
  28678. }
  28679. }
  28680. /**
  28681. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28682. *
  28683. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28684. * The azimuthal angle (theta) is measured from the positive z-axis.
  28685. */
  28686. class Spherical {
  28687. constructor( radius = 1, phi = 0, theta = 0 ) {
  28688. this.radius = radius;
  28689. this.phi = phi; // polar angle
  28690. this.theta = theta; // azimuthal angle
  28691. return this;
  28692. }
  28693. set( radius, phi, theta ) {
  28694. this.radius = radius;
  28695. this.phi = phi;
  28696. this.theta = theta;
  28697. return this;
  28698. }
  28699. copy( other ) {
  28700. this.radius = other.radius;
  28701. this.phi = other.phi;
  28702. this.theta = other.theta;
  28703. return this;
  28704. }
  28705. // restrict phi to be between EPS and PI-EPS
  28706. makeSafe() {
  28707. const EPS = 0.000001;
  28708. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28709. return this;
  28710. }
  28711. setFromVector3( v ) {
  28712. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28713. }
  28714. setFromCartesianCoords( x, y, z ) {
  28715. this.radius = Math.sqrt( x * x + y * y + z * z );
  28716. if ( this.radius === 0 ) {
  28717. this.theta = 0;
  28718. this.phi = 0;
  28719. } else {
  28720. this.theta = Math.atan2( x, z );
  28721. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28722. }
  28723. return this;
  28724. }
  28725. clone() {
  28726. return new this.constructor().copy( this );
  28727. }
  28728. }
  28729. /**
  28730. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28731. */
  28732. class Cylindrical {
  28733. constructor( radius = 1, theta = 0, y = 0 ) {
  28734. this.radius = radius; // distance from the origin to a point in the x-z plane
  28735. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28736. this.y = y; // height above the x-z plane
  28737. return this;
  28738. }
  28739. set( radius, theta, y ) {
  28740. this.radius = radius;
  28741. this.theta = theta;
  28742. this.y = y;
  28743. return this;
  28744. }
  28745. copy( other ) {
  28746. this.radius = other.radius;
  28747. this.theta = other.theta;
  28748. this.y = other.y;
  28749. return this;
  28750. }
  28751. setFromVector3( v ) {
  28752. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28753. }
  28754. setFromCartesianCoords( x, y, z ) {
  28755. this.radius = Math.sqrt( x * x + z * z );
  28756. this.theta = Math.atan2( x, z );
  28757. this.y = y;
  28758. return this;
  28759. }
  28760. clone() {
  28761. return new this.constructor().copy( this );
  28762. }
  28763. }
  28764. const _vector$4 = /*@__PURE__*/ new Vector2();
  28765. class Box2 {
  28766. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28767. this.isBox2 = true;
  28768. this.min = min;
  28769. this.max = max;
  28770. }
  28771. set( min, max ) {
  28772. this.min.copy( min );
  28773. this.max.copy( max );
  28774. return this;
  28775. }
  28776. setFromPoints( points ) {
  28777. this.makeEmpty();
  28778. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28779. this.expandByPoint( points[ i ] );
  28780. }
  28781. return this;
  28782. }
  28783. setFromCenterAndSize( center, size ) {
  28784. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28785. this.min.copy( center ).sub( halfSize );
  28786. this.max.copy( center ).add( halfSize );
  28787. return this;
  28788. }
  28789. clone() {
  28790. return new this.constructor().copy( this );
  28791. }
  28792. copy( box ) {
  28793. this.min.copy( box.min );
  28794. this.max.copy( box.max );
  28795. return this;
  28796. }
  28797. makeEmpty() {
  28798. this.min.x = this.min.y = + Infinity;
  28799. this.max.x = this.max.y = - Infinity;
  28800. return this;
  28801. }
  28802. isEmpty() {
  28803. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28804. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28805. }
  28806. getCenter( target ) {
  28807. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28808. }
  28809. getSize( target ) {
  28810. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28811. }
  28812. expandByPoint( point ) {
  28813. this.min.min( point );
  28814. this.max.max( point );
  28815. return this;
  28816. }
  28817. expandByVector( vector ) {
  28818. this.min.sub( vector );
  28819. this.max.add( vector );
  28820. return this;
  28821. }
  28822. expandByScalar( scalar ) {
  28823. this.min.addScalar( - scalar );
  28824. this.max.addScalar( scalar );
  28825. return this;
  28826. }
  28827. containsPoint( point ) {
  28828. return point.x < this.min.x || point.x > this.max.x ||
  28829. point.y < this.min.y || point.y > this.max.y ? false : true;
  28830. }
  28831. containsBox( box ) {
  28832. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28833. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28834. }
  28835. getParameter( point, target ) {
  28836. // This can potentially have a divide by zero if the box
  28837. // has a size dimension of 0.
  28838. return target.set(
  28839. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28840. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28841. );
  28842. }
  28843. intersectsBox( box ) {
  28844. // using 4 splitting planes to rule out intersections
  28845. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28846. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28847. }
  28848. clampPoint( point, target ) {
  28849. return target.copy( point ).clamp( this.min, this.max );
  28850. }
  28851. distanceToPoint( point ) {
  28852. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  28853. }
  28854. intersect( box ) {
  28855. this.min.max( box.min );
  28856. this.max.min( box.max );
  28857. if ( this.isEmpty() ) this.makeEmpty();
  28858. return this;
  28859. }
  28860. union( box ) {
  28861. this.min.min( box.min );
  28862. this.max.max( box.max );
  28863. return this;
  28864. }
  28865. translate( offset ) {
  28866. this.min.add( offset );
  28867. this.max.add( offset );
  28868. return this;
  28869. }
  28870. equals( box ) {
  28871. return box.min.equals( this.min ) && box.max.equals( this.max );
  28872. }
  28873. }
  28874. const _startP = /*@__PURE__*/ new Vector3();
  28875. const _startEnd = /*@__PURE__*/ new Vector3();
  28876. class Line3 {
  28877. constructor( start = new Vector3(), end = new Vector3() ) {
  28878. this.start = start;
  28879. this.end = end;
  28880. }
  28881. set( start, end ) {
  28882. this.start.copy( start );
  28883. this.end.copy( end );
  28884. return this;
  28885. }
  28886. copy( line ) {
  28887. this.start.copy( line.start );
  28888. this.end.copy( line.end );
  28889. return this;
  28890. }
  28891. getCenter( target ) {
  28892. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28893. }
  28894. delta( target ) {
  28895. return target.subVectors( this.end, this.start );
  28896. }
  28897. distanceSq() {
  28898. return this.start.distanceToSquared( this.end );
  28899. }
  28900. distance() {
  28901. return this.start.distanceTo( this.end );
  28902. }
  28903. at( t, target ) {
  28904. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28905. }
  28906. closestPointToPointParameter( point, clampToLine ) {
  28907. _startP.subVectors( point, this.start );
  28908. _startEnd.subVectors( this.end, this.start );
  28909. const startEnd2 = _startEnd.dot( _startEnd );
  28910. const startEnd_startP = _startEnd.dot( _startP );
  28911. let t = startEnd_startP / startEnd2;
  28912. if ( clampToLine ) {
  28913. t = clamp( t, 0, 1 );
  28914. }
  28915. return t;
  28916. }
  28917. closestPointToPoint( point, clampToLine, target ) {
  28918. const t = this.closestPointToPointParameter( point, clampToLine );
  28919. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28920. }
  28921. applyMatrix4( matrix ) {
  28922. this.start.applyMatrix4( matrix );
  28923. this.end.applyMatrix4( matrix );
  28924. return this;
  28925. }
  28926. equals( line ) {
  28927. return line.start.equals( this.start ) && line.end.equals( this.end );
  28928. }
  28929. clone() {
  28930. return new this.constructor().copy( this );
  28931. }
  28932. }
  28933. const _vector$3 = /*@__PURE__*/ new Vector3();
  28934. class SpotLightHelper extends Object3D {
  28935. constructor( light, color ) {
  28936. super();
  28937. this.light = light;
  28938. this.matrix = light.matrixWorld;
  28939. this.matrixAutoUpdate = false;
  28940. this.color = color;
  28941. this.type = 'SpotLightHelper';
  28942. const geometry = new BufferGeometry();
  28943. const positions = [
  28944. 0, 0, 0, 0, 0, 1,
  28945. 0, 0, 0, 1, 0, 1,
  28946. 0, 0, 0, - 1, 0, 1,
  28947. 0, 0, 0, 0, 1, 1,
  28948. 0, 0, 0, 0, - 1, 1
  28949. ];
  28950. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28951. const p1 = ( i / l ) * Math.PI * 2;
  28952. const p2 = ( j / l ) * Math.PI * 2;
  28953. positions.push(
  28954. Math.cos( p1 ), Math.sin( p1 ), 1,
  28955. Math.cos( p2 ), Math.sin( p2 ), 1
  28956. );
  28957. }
  28958. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28959. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28960. this.cone = new LineSegments( geometry, material );
  28961. this.add( this.cone );
  28962. this.update();
  28963. }
  28964. dispose() {
  28965. this.cone.geometry.dispose();
  28966. this.cone.material.dispose();
  28967. }
  28968. update() {
  28969. this.light.updateWorldMatrix( true, false );
  28970. this.light.target.updateWorldMatrix( true, false );
  28971. const coneLength = this.light.distance ? this.light.distance : 1000;
  28972. const coneWidth = coneLength * Math.tan( this.light.angle );
  28973. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28974. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28975. this.cone.lookAt( _vector$3 );
  28976. if ( this.color !== undefined ) {
  28977. this.cone.material.color.set( this.color );
  28978. } else {
  28979. this.cone.material.color.copy( this.light.color );
  28980. }
  28981. }
  28982. }
  28983. const _vector$2 = /*@__PURE__*/ new Vector3();
  28984. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28985. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28986. class SkeletonHelper extends LineSegments {
  28987. constructor( object ) {
  28988. const bones = getBoneList( object );
  28989. const geometry = new BufferGeometry();
  28990. const vertices = [];
  28991. const colors = [];
  28992. const color1 = new Color( 0, 0, 1 );
  28993. const color2 = new Color( 0, 1, 0 );
  28994. for ( let i = 0; i < bones.length; i ++ ) {
  28995. const bone = bones[ i ];
  28996. if ( bone.parent && bone.parent.isBone ) {
  28997. vertices.push( 0, 0, 0 );
  28998. vertices.push( 0, 0, 0 );
  28999. colors.push( color1.r, color1.g, color1.b );
  29000. colors.push( color2.r, color2.g, color2.b );
  29001. }
  29002. }
  29003. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29004. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29005. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  29006. super( geometry, material );
  29007. this.isSkeletonHelper = true;
  29008. this.type = 'SkeletonHelper';
  29009. this.root = object;
  29010. this.bones = bones;
  29011. this.matrix = object.matrixWorld;
  29012. this.matrixAutoUpdate = false;
  29013. }
  29014. updateMatrixWorld( force ) {
  29015. const bones = this.bones;
  29016. const geometry = this.geometry;
  29017. const position = geometry.getAttribute( 'position' );
  29018. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  29019. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  29020. const bone = bones[ i ];
  29021. if ( bone.parent && bone.parent.isBone ) {
  29022. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  29023. _vector$2.setFromMatrixPosition( _boneMatrix );
  29024. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  29025. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  29026. _vector$2.setFromMatrixPosition( _boneMatrix );
  29027. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  29028. j += 2;
  29029. }
  29030. }
  29031. geometry.getAttribute( 'position' ).needsUpdate = true;
  29032. super.updateMatrixWorld( force );
  29033. }
  29034. dispose() {
  29035. this.geometry.dispose();
  29036. this.material.dispose();
  29037. }
  29038. }
  29039. function getBoneList( object ) {
  29040. const boneList = [];
  29041. if ( object.isBone === true ) {
  29042. boneList.push( object );
  29043. }
  29044. for ( let i = 0; i < object.children.length; i ++ ) {
  29045. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  29046. }
  29047. return boneList;
  29048. }
  29049. class PointLightHelper extends Mesh {
  29050. constructor( light, sphereSize, color ) {
  29051. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  29052. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29053. super( geometry, material );
  29054. this.light = light;
  29055. this.color = color;
  29056. this.type = 'PointLightHelper';
  29057. this.matrix = this.light.matrixWorld;
  29058. this.matrixAutoUpdate = false;
  29059. this.update();
  29060. /*
  29061. // TODO: delete this comment?
  29062. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  29063. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  29064. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  29065. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  29066. const d = light.distance;
  29067. if ( d === 0.0 ) {
  29068. this.lightDistance.visible = false;
  29069. } else {
  29070. this.lightDistance.scale.set( d, d, d );
  29071. }
  29072. this.add( this.lightDistance );
  29073. */
  29074. }
  29075. dispose() {
  29076. this.geometry.dispose();
  29077. this.material.dispose();
  29078. }
  29079. update() {
  29080. this.light.updateWorldMatrix( true, false );
  29081. if ( this.color !== undefined ) {
  29082. this.material.color.set( this.color );
  29083. } else {
  29084. this.material.color.copy( this.light.color );
  29085. }
  29086. /*
  29087. const d = this.light.distance;
  29088. if ( d === 0.0 ) {
  29089. this.lightDistance.visible = false;
  29090. } else {
  29091. this.lightDistance.visible = true;
  29092. this.lightDistance.scale.set( d, d, d );
  29093. }
  29094. */
  29095. }
  29096. }
  29097. const _vector$1 = /*@__PURE__*/ new Vector3();
  29098. const _color1 = /*@__PURE__*/ new Color();
  29099. const _color2 = /*@__PURE__*/ new Color();
  29100. class HemisphereLightHelper extends Object3D {
  29101. constructor( light, size, color ) {
  29102. super();
  29103. this.light = light;
  29104. this.matrix = light.matrixWorld;
  29105. this.matrixAutoUpdate = false;
  29106. this.color = color;
  29107. this.type = 'HemisphereLightHelper';
  29108. const geometry = new OctahedronGeometry( size );
  29109. geometry.rotateY( Math.PI * 0.5 );
  29110. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29111. if ( this.color === undefined ) this.material.vertexColors = true;
  29112. const position = geometry.getAttribute( 'position' );
  29113. const colors = new Float32Array( position.count * 3 );
  29114. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  29115. this.add( new Mesh( geometry, this.material ) );
  29116. this.update();
  29117. }
  29118. dispose() {
  29119. this.children[ 0 ].geometry.dispose();
  29120. this.children[ 0 ].material.dispose();
  29121. }
  29122. update() {
  29123. const mesh = this.children[ 0 ];
  29124. if ( this.color !== undefined ) {
  29125. this.material.color.set( this.color );
  29126. } else {
  29127. const colors = mesh.geometry.getAttribute( 'color' );
  29128. _color1.copy( this.light.color );
  29129. _color2.copy( this.light.groundColor );
  29130. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  29131. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  29132. colors.setXYZ( i, color.r, color.g, color.b );
  29133. }
  29134. colors.needsUpdate = true;
  29135. }
  29136. this.light.updateWorldMatrix( true, false );
  29137. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  29138. }
  29139. }
  29140. class GridHelper extends LineSegments {
  29141. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  29142. color1 = new Color( color1 );
  29143. color2 = new Color( color2 );
  29144. const center = divisions / 2;
  29145. const step = size / divisions;
  29146. const halfSize = size / 2;
  29147. const vertices = [], colors = [];
  29148. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  29149. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  29150. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  29151. const color = i === center ? color1 : color2;
  29152. color.toArray( colors, j ); j += 3;
  29153. color.toArray( colors, j ); j += 3;
  29154. color.toArray( colors, j ); j += 3;
  29155. color.toArray( colors, j ); j += 3;
  29156. }
  29157. const geometry = new BufferGeometry();
  29158. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29159. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29160. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29161. super( geometry, material );
  29162. this.type = 'GridHelper';
  29163. }
  29164. dispose() {
  29165. this.geometry.dispose();
  29166. this.material.dispose();
  29167. }
  29168. }
  29169. class PolarGridHelper extends LineSegments {
  29170. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  29171. color1 = new Color( color1 );
  29172. color2 = new Color( color2 );
  29173. const vertices = [];
  29174. const colors = [];
  29175. // create the sectors
  29176. if ( sectors > 1 ) {
  29177. for ( let i = 0; i < sectors; i ++ ) {
  29178. const v = ( i / sectors ) * ( Math.PI * 2 );
  29179. const x = Math.sin( v ) * radius;
  29180. const z = Math.cos( v ) * radius;
  29181. vertices.push( 0, 0, 0 );
  29182. vertices.push( x, 0, z );
  29183. const color = ( i & 1 ) ? color1 : color2;
  29184. colors.push( color.r, color.g, color.b );
  29185. colors.push( color.r, color.g, color.b );
  29186. }
  29187. }
  29188. // create the rings
  29189. for ( let i = 0; i < rings; i ++ ) {
  29190. const color = ( i & 1 ) ? color1 : color2;
  29191. const r = radius - ( radius / rings * i );
  29192. for ( let j = 0; j < divisions; j ++ ) {
  29193. // first vertex
  29194. let v = ( j / divisions ) * ( Math.PI * 2 );
  29195. let x = Math.sin( v ) * r;
  29196. let z = Math.cos( v ) * r;
  29197. vertices.push( x, 0, z );
  29198. colors.push( color.r, color.g, color.b );
  29199. // second vertex
  29200. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  29201. x = Math.sin( v ) * r;
  29202. z = Math.cos( v ) * r;
  29203. vertices.push( x, 0, z );
  29204. colors.push( color.r, color.g, color.b );
  29205. }
  29206. }
  29207. const geometry = new BufferGeometry();
  29208. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29209. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29210. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29211. super( geometry, material );
  29212. this.type = 'PolarGridHelper';
  29213. }
  29214. dispose() {
  29215. this.geometry.dispose();
  29216. this.material.dispose();
  29217. }
  29218. }
  29219. const _v1 = /*@__PURE__*/ new Vector3();
  29220. const _v2 = /*@__PURE__*/ new Vector3();
  29221. const _v3 = /*@__PURE__*/ new Vector3();
  29222. class DirectionalLightHelper extends Object3D {
  29223. constructor( light, size, color ) {
  29224. super();
  29225. this.light = light;
  29226. this.matrix = light.matrixWorld;
  29227. this.matrixAutoUpdate = false;
  29228. this.color = color;
  29229. this.type = 'DirectionalLightHelper';
  29230. if ( size === undefined ) size = 1;
  29231. let geometry = new BufferGeometry();
  29232. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29233. - size, size, 0,
  29234. size, size, 0,
  29235. size, - size, 0,
  29236. - size, - size, 0,
  29237. - size, size, 0
  29238. ], 3 ) );
  29239. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29240. this.lightPlane = new Line( geometry, material );
  29241. this.add( this.lightPlane );
  29242. geometry = new BufferGeometry();
  29243. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29244. this.targetLine = new Line( geometry, material );
  29245. this.add( this.targetLine );
  29246. this.update();
  29247. }
  29248. dispose() {
  29249. this.lightPlane.geometry.dispose();
  29250. this.lightPlane.material.dispose();
  29251. this.targetLine.geometry.dispose();
  29252. this.targetLine.material.dispose();
  29253. }
  29254. update() {
  29255. this.light.updateWorldMatrix( true, false );
  29256. this.light.target.updateWorldMatrix( true, false );
  29257. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29258. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29259. _v3.subVectors( _v2, _v1 );
  29260. this.lightPlane.lookAt( _v2 );
  29261. if ( this.color !== undefined ) {
  29262. this.lightPlane.material.color.set( this.color );
  29263. this.targetLine.material.color.set( this.color );
  29264. } else {
  29265. this.lightPlane.material.color.copy( this.light.color );
  29266. this.targetLine.material.color.copy( this.light.color );
  29267. }
  29268. this.targetLine.lookAt( _v2 );
  29269. this.targetLine.scale.z = _v3.length();
  29270. }
  29271. }
  29272. const _vector = /*@__PURE__*/ new Vector3();
  29273. const _camera = /*@__PURE__*/ new Camera();
  29274. /**
  29275. * - shows frustum, line of sight and up of the camera
  29276. * - suitable for fast updates
  29277. * - based on frustum visualization in lightgl.js shadowmap example
  29278. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  29279. */
  29280. class CameraHelper extends LineSegments {
  29281. constructor( camera ) {
  29282. const geometry = new BufferGeometry();
  29283. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29284. const vertices = [];
  29285. const colors = [];
  29286. const pointMap = {};
  29287. // near
  29288. addLine( 'n1', 'n2' );
  29289. addLine( 'n2', 'n4' );
  29290. addLine( 'n4', 'n3' );
  29291. addLine( 'n3', 'n1' );
  29292. // far
  29293. addLine( 'f1', 'f2' );
  29294. addLine( 'f2', 'f4' );
  29295. addLine( 'f4', 'f3' );
  29296. addLine( 'f3', 'f1' );
  29297. // sides
  29298. addLine( 'n1', 'f1' );
  29299. addLine( 'n2', 'f2' );
  29300. addLine( 'n3', 'f3' );
  29301. addLine( 'n4', 'f4' );
  29302. // cone
  29303. addLine( 'p', 'n1' );
  29304. addLine( 'p', 'n2' );
  29305. addLine( 'p', 'n3' );
  29306. addLine( 'p', 'n4' );
  29307. // up
  29308. addLine( 'u1', 'u2' );
  29309. addLine( 'u2', 'u3' );
  29310. addLine( 'u3', 'u1' );
  29311. // target
  29312. addLine( 'c', 't' );
  29313. addLine( 'p', 'c' );
  29314. // cross
  29315. addLine( 'cn1', 'cn2' );
  29316. addLine( 'cn3', 'cn4' );
  29317. addLine( 'cf1', 'cf2' );
  29318. addLine( 'cf3', 'cf4' );
  29319. function addLine( a, b ) {
  29320. addPoint( a );
  29321. addPoint( b );
  29322. }
  29323. function addPoint( id ) {
  29324. vertices.push( 0, 0, 0 );
  29325. colors.push( 0, 0, 0 );
  29326. if ( pointMap[ id ] === undefined ) {
  29327. pointMap[ id ] = [];
  29328. }
  29329. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29330. }
  29331. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29332. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29333. super( geometry, material );
  29334. this.type = 'CameraHelper';
  29335. this.camera = camera;
  29336. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29337. this.matrix = camera.matrixWorld;
  29338. this.matrixAutoUpdate = false;
  29339. this.pointMap = pointMap;
  29340. this.update();
  29341. // colors
  29342. const colorFrustum = new Color( 0xffaa00 );
  29343. const colorCone = new Color( 0xff0000 );
  29344. const colorUp = new Color( 0x00aaff );
  29345. const colorTarget = new Color( 0xffffff );
  29346. const colorCross = new Color( 0x333333 );
  29347. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  29348. }
  29349. setColors( frustum, cone, up, target, cross ) {
  29350. const geometry = this.geometry;
  29351. const colorAttribute = geometry.getAttribute( 'color' );
  29352. // near
  29353. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  29354. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  29355. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  29356. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  29357. // far
  29358. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  29359. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  29360. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  29361. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  29362. // sides
  29363. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  29364. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  29365. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  29366. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  29367. // cone
  29368. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  29369. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  29370. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  29371. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  29372. // up
  29373. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  29374. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  29375. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  29376. // target
  29377. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  29378. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  29379. // cross
  29380. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  29381. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  29382. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  29383. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  29384. colorAttribute.needsUpdate = true;
  29385. }
  29386. update() {
  29387. const geometry = this.geometry;
  29388. const pointMap = this.pointMap;
  29389. const w = 1, h = 1;
  29390. // we need just camera projection matrix inverse
  29391. // world matrix must be identity
  29392. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29393. // center / target
  29394. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29395. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29396. // near
  29397. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29398. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29399. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29400. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29401. // far
  29402. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29403. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29404. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29405. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29406. // up
  29407. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29408. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29409. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29410. // cross
  29411. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29412. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29413. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29414. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29415. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29416. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29417. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29418. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29419. geometry.getAttribute( 'position' ).needsUpdate = true;
  29420. }
  29421. dispose() {
  29422. this.geometry.dispose();
  29423. this.material.dispose();
  29424. }
  29425. }
  29426. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29427. _vector.set( x, y, z ).unproject( camera );
  29428. const points = pointMap[ point ];
  29429. if ( points !== undefined ) {
  29430. const position = geometry.getAttribute( 'position' );
  29431. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29432. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29433. }
  29434. }
  29435. }
  29436. const _box = /*@__PURE__*/ new Box3();
  29437. class BoxHelper extends LineSegments {
  29438. constructor( object, color = 0xffff00 ) {
  29439. 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 ] );
  29440. const positions = new Float32Array( 8 * 3 );
  29441. const geometry = new BufferGeometry();
  29442. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29443. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29444. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29445. this.object = object;
  29446. this.type = 'BoxHelper';
  29447. this.matrixAutoUpdate = false;
  29448. this.update();
  29449. }
  29450. update( object ) {
  29451. if ( object !== undefined ) {
  29452. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29453. }
  29454. if ( this.object !== undefined ) {
  29455. _box.setFromObject( this.object );
  29456. }
  29457. if ( _box.isEmpty() ) return;
  29458. const min = _box.min;
  29459. const max = _box.max;
  29460. /*
  29461. 5____4
  29462. 1/___0/|
  29463. | 6__|_7
  29464. 2/___3/
  29465. 0: max.x, max.y, max.z
  29466. 1: min.x, max.y, max.z
  29467. 2: min.x, min.y, max.z
  29468. 3: max.x, min.y, max.z
  29469. 4: max.x, max.y, min.z
  29470. 5: min.x, max.y, min.z
  29471. 6: min.x, min.y, min.z
  29472. 7: max.x, min.y, min.z
  29473. */
  29474. const position = this.geometry.attributes.position;
  29475. const array = position.array;
  29476. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29477. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29478. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29479. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29480. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29481. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29482. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29483. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29484. position.needsUpdate = true;
  29485. this.geometry.computeBoundingSphere();
  29486. }
  29487. setFromObject( object ) {
  29488. this.object = object;
  29489. this.update();
  29490. return this;
  29491. }
  29492. copy( source, recursive ) {
  29493. super.copy( source, recursive );
  29494. this.object = source.object;
  29495. return this;
  29496. }
  29497. dispose() {
  29498. this.geometry.dispose();
  29499. this.material.dispose();
  29500. }
  29501. }
  29502. class Box3Helper extends LineSegments {
  29503. constructor( box, color = 0xffff00 ) {
  29504. 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 ] );
  29505. 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 ];
  29506. const geometry = new BufferGeometry();
  29507. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29508. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29509. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29510. this.box = box;
  29511. this.type = 'Box3Helper';
  29512. this.geometry.computeBoundingSphere();
  29513. }
  29514. updateMatrixWorld( force ) {
  29515. const box = this.box;
  29516. if ( box.isEmpty() ) return;
  29517. box.getCenter( this.position );
  29518. box.getSize( this.scale );
  29519. this.scale.multiplyScalar( 0.5 );
  29520. super.updateMatrixWorld( force );
  29521. }
  29522. dispose() {
  29523. this.geometry.dispose();
  29524. this.material.dispose();
  29525. }
  29526. }
  29527. class PlaneHelper extends Line {
  29528. constructor( plane, size = 1, hex = 0xffff00 ) {
  29529. const color = hex;
  29530. 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 ];
  29531. const geometry = new BufferGeometry();
  29532. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29533. geometry.computeBoundingSphere();
  29534. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29535. this.type = 'PlaneHelper';
  29536. this.plane = plane;
  29537. this.size = size;
  29538. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29539. const geometry2 = new BufferGeometry();
  29540. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29541. geometry2.computeBoundingSphere();
  29542. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29543. }
  29544. updateMatrixWorld( force ) {
  29545. this.position.set( 0, 0, 0 );
  29546. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29547. this.lookAt( this.plane.normal );
  29548. this.translateZ( - this.plane.constant );
  29549. super.updateMatrixWorld( force );
  29550. }
  29551. dispose() {
  29552. this.geometry.dispose();
  29553. this.material.dispose();
  29554. this.children[ 0 ].geometry.dispose();
  29555. this.children[ 0 ].material.dispose();
  29556. }
  29557. }
  29558. const _axis = /*@__PURE__*/ new Vector3();
  29559. let _lineGeometry, _coneGeometry;
  29560. class ArrowHelper extends Object3D {
  29561. // dir is assumed to be normalized
  29562. 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 ) {
  29563. super();
  29564. this.type = 'ArrowHelper';
  29565. if ( _lineGeometry === undefined ) {
  29566. _lineGeometry = new BufferGeometry();
  29567. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29568. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29569. _coneGeometry.translate( 0, - 0.5, 0 );
  29570. }
  29571. this.position.copy( origin );
  29572. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29573. this.line.matrixAutoUpdate = false;
  29574. this.add( this.line );
  29575. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29576. this.cone.matrixAutoUpdate = false;
  29577. this.add( this.cone );
  29578. this.setDirection( dir );
  29579. this.setLength( length, headLength, headWidth );
  29580. }
  29581. setDirection( dir ) {
  29582. // dir is assumed to be normalized
  29583. if ( dir.y > 0.99999 ) {
  29584. this.quaternion.set( 0, 0, 0, 1 );
  29585. } else if ( dir.y < - 0.99999 ) {
  29586. this.quaternion.set( 1, 0, 0, 0 );
  29587. } else {
  29588. _axis.set( dir.z, 0, - dir.x ).normalize();
  29589. const radians = Math.acos( dir.y );
  29590. this.quaternion.setFromAxisAngle( _axis, radians );
  29591. }
  29592. }
  29593. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29594. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29595. this.line.updateMatrix();
  29596. this.cone.scale.set( headWidth, headLength, headWidth );
  29597. this.cone.position.y = length;
  29598. this.cone.updateMatrix();
  29599. }
  29600. setColor( color ) {
  29601. this.line.material.color.set( color );
  29602. this.cone.material.color.set( color );
  29603. }
  29604. copy( source ) {
  29605. super.copy( source, false );
  29606. this.line.copy( source.line );
  29607. this.cone.copy( source.cone );
  29608. return this;
  29609. }
  29610. dispose() {
  29611. this.line.geometry.dispose();
  29612. this.line.material.dispose();
  29613. this.cone.geometry.dispose();
  29614. this.cone.material.dispose();
  29615. }
  29616. }
  29617. class AxesHelper extends LineSegments {
  29618. constructor( size = 1 ) {
  29619. const vertices = [
  29620. 0, 0, 0, size, 0, 0,
  29621. 0, 0, 0, 0, size, 0,
  29622. 0, 0, 0, 0, 0, size
  29623. ];
  29624. const colors = [
  29625. 1, 0, 0, 1, 0.6, 0,
  29626. 0, 1, 0, 0.6, 1, 0,
  29627. 0, 0, 1, 0, 0.6, 1
  29628. ];
  29629. const geometry = new BufferGeometry();
  29630. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29631. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29632. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29633. super( geometry, material );
  29634. this.type = 'AxesHelper';
  29635. }
  29636. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29637. const color = new Color();
  29638. const array = this.geometry.attributes.color.array;
  29639. color.set( xAxisColor );
  29640. color.toArray( array, 0 );
  29641. color.toArray( array, 3 );
  29642. color.set( yAxisColor );
  29643. color.toArray( array, 6 );
  29644. color.toArray( array, 9 );
  29645. color.set( zAxisColor );
  29646. color.toArray( array, 12 );
  29647. color.toArray( array, 15 );
  29648. this.geometry.attributes.color.needsUpdate = true;
  29649. return this;
  29650. }
  29651. dispose() {
  29652. this.geometry.dispose();
  29653. this.material.dispose();
  29654. }
  29655. }
  29656. class ShapePath {
  29657. constructor() {
  29658. this.type = 'ShapePath';
  29659. this.color = new Color();
  29660. this.subPaths = [];
  29661. this.currentPath = null;
  29662. }
  29663. moveTo( x, y ) {
  29664. this.currentPath = new Path();
  29665. this.subPaths.push( this.currentPath );
  29666. this.currentPath.moveTo( x, y );
  29667. return this;
  29668. }
  29669. lineTo( x, y ) {
  29670. this.currentPath.lineTo( x, y );
  29671. return this;
  29672. }
  29673. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29674. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29675. return this;
  29676. }
  29677. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29678. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29679. return this;
  29680. }
  29681. splineThru( pts ) {
  29682. this.currentPath.splineThru( pts );
  29683. return this;
  29684. }
  29685. toShapes( isCCW ) {
  29686. function toShapesNoHoles( inSubpaths ) {
  29687. const shapes = [];
  29688. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29689. const tmpPath = inSubpaths[ i ];
  29690. const tmpShape = new Shape();
  29691. tmpShape.curves = tmpPath.curves;
  29692. shapes.push( tmpShape );
  29693. }
  29694. return shapes;
  29695. }
  29696. function isPointInsidePolygon( inPt, inPolygon ) {
  29697. const polyLen = inPolygon.length;
  29698. // inPt on polygon contour => immediate success or
  29699. // toggling of inside/outside at every single! intersection point of an edge
  29700. // with the horizontal line through inPt, left of inPt
  29701. // not counting lowerY endpoints of edges and whole edges on that line
  29702. let inside = false;
  29703. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29704. let edgeLowPt = inPolygon[ p ];
  29705. let edgeHighPt = inPolygon[ q ];
  29706. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29707. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29708. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29709. // not parallel
  29710. if ( edgeDy < 0 ) {
  29711. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29712. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29713. }
  29714. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29715. if ( inPt.y === edgeLowPt.y ) {
  29716. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29717. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29718. } else {
  29719. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29720. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29721. if ( perpEdge < 0 ) continue;
  29722. inside = ! inside; // true intersection left of inPt
  29723. }
  29724. } else {
  29725. // parallel or collinear
  29726. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29727. // edge lies on the same horizontal line as inPt
  29728. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29729. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29730. // continue;
  29731. }
  29732. }
  29733. return inside;
  29734. }
  29735. const isClockWise = ShapeUtils.isClockWise;
  29736. const subPaths = this.subPaths;
  29737. if ( subPaths.length === 0 ) return [];
  29738. let solid, tmpPath, tmpShape;
  29739. const shapes = [];
  29740. if ( subPaths.length === 1 ) {
  29741. tmpPath = subPaths[ 0 ];
  29742. tmpShape = new Shape();
  29743. tmpShape.curves = tmpPath.curves;
  29744. shapes.push( tmpShape );
  29745. return shapes;
  29746. }
  29747. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29748. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29749. // console.log("Holes first", holesFirst);
  29750. const betterShapeHoles = [];
  29751. const newShapes = [];
  29752. let newShapeHoles = [];
  29753. let mainIdx = 0;
  29754. let tmpPoints;
  29755. newShapes[ mainIdx ] = undefined;
  29756. newShapeHoles[ mainIdx ] = [];
  29757. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29758. tmpPath = subPaths[ i ];
  29759. tmpPoints = tmpPath.getPoints();
  29760. solid = isClockWise( tmpPoints );
  29761. solid = isCCW ? ! solid : solid;
  29762. if ( solid ) {
  29763. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29764. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29765. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29766. if ( holesFirst ) mainIdx ++;
  29767. newShapeHoles[ mainIdx ] = [];
  29768. //console.log('cw', i);
  29769. } else {
  29770. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29771. //console.log('ccw', i);
  29772. }
  29773. }
  29774. // only Holes? -> probably all Shapes with wrong orientation
  29775. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29776. if ( newShapes.length > 1 ) {
  29777. let ambiguous = false;
  29778. let toChange = 0;
  29779. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29780. betterShapeHoles[ sIdx ] = [];
  29781. }
  29782. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29783. const sho = newShapeHoles[ sIdx ];
  29784. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29785. const ho = sho[ hIdx ];
  29786. let hole_unassigned = true;
  29787. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29788. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29789. if ( sIdx !== s2Idx ) toChange ++;
  29790. if ( hole_unassigned ) {
  29791. hole_unassigned = false;
  29792. betterShapeHoles[ s2Idx ].push( ho );
  29793. } else {
  29794. ambiguous = true;
  29795. }
  29796. }
  29797. }
  29798. if ( hole_unassigned ) {
  29799. betterShapeHoles[ sIdx ].push( ho );
  29800. }
  29801. }
  29802. }
  29803. if ( toChange > 0 && ambiguous === false ) {
  29804. newShapeHoles = betterShapeHoles;
  29805. }
  29806. }
  29807. let tmpHoles;
  29808. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29809. tmpShape = newShapes[ i ].s;
  29810. shapes.push( tmpShape );
  29811. tmpHoles = newShapeHoles[ i ];
  29812. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29813. tmpShape.holes.push( tmpHoles[ j ].h );
  29814. }
  29815. }
  29816. //console.log("shape", shapes);
  29817. return shapes;
  29818. }
  29819. }
  29820. class BoxBufferGeometry extends BoxGeometry { // @deprecated, r144
  29821. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29822. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29823. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29824. }
  29825. }
  29826. class CapsuleBufferGeometry extends CapsuleGeometry { // @deprecated, r144
  29827. constructor( radius, length, capSegments, radialSegments ) {
  29828. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29829. super( radius, length, capSegments, radialSegments );
  29830. }
  29831. }
  29832. class CircleBufferGeometry extends CircleGeometry { // @deprecated, r144
  29833. constructor( radius, segments, thetaStart, thetaLength ) {
  29834. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29835. super( radius, segments, thetaStart, thetaLength );
  29836. }
  29837. }
  29838. class ConeBufferGeometry extends ConeGeometry { // @deprecated, r144
  29839. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29840. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29841. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29842. }
  29843. }
  29844. class CylinderBufferGeometry extends CylinderGeometry { // @deprecated, r144
  29845. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29846. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29847. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29848. }
  29849. }
  29850. class DodecahedronBufferGeometry extends DodecahedronGeometry { // @deprecated, r144
  29851. constructor( radius, detail ) {
  29852. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29853. super( radius, detail );
  29854. }
  29855. }
  29856. class ExtrudeBufferGeometry extends ExtrudeGeometry { // @deprecated, r144
  29857. constructor( shapes, options ) {
  29858. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29859. super( shapes, options );
  29860. }
  29861. }
  29862. class IcosahedronBufferGeometry extends IcosahedronGeometry { // @deprecated, r144
  29863. constructor( radius, detail ) {
  29864. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29865. super( radius, detail );
  29866. }
  29867. }
  29868. class LatheBufferGeometry extends LatheGeometry { // @deprecated, r144
  29869. constructor( points, segments, phiStart, phiLength ) {
  29870. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29871. super( points, segments, phiStart, phiLength );
  29872. }
  29873. }
  29874. class OctahedronBufferGeometry extends OctahedronGeometry { // @deprecated, r144
  29875. constructor( radius, detail ) {
  29876. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29877. super( radius, detail );
  29878. }
  29879. }
  29880. class PlaneBufferGeometry extends PlaneGeometry { // @deprecated, r144
  29881. constructor( width, height, widthSegments, heightSegments ) {
  29882. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29883. super( width, height, widthSegments, heightSegments );
  29884. }
  29885. }
  29886. class PolyhedronBufferGeometry extends PolyhedronGeometry { // @deprecated, r144
  29887. constructor( vertices, indices, radius, detail ) {
  29888. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  29889. super( vertices, indices, radius, detail );
  29890. }
  29891. }
  29892. class RingBufferGeometry extends RingGeometry { // @deprecated, r144
  29893. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  29894. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  29895. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  29896. }
  29897. }
  29898. class ShapeBufferGeometry extends ShapeGeometry { // @deprecated, r144
  29899. constructor( shapes, curveSegments ) {
  29900. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  29901. super( shapes, curveSegments );
  29902. }
  29903. }
  29904. class SphereBufferGeometry extends SphereGeometry { // @deprecated, r144
  29905. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  29906. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  29907. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  29908. }
  29909. }
  29910. class TetrahedronBufferGeometry extends TetrahedronGeometry { // @deprecated, r144
  29911. constructor( radius, detail ) {
  29912. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  29913. super( radius, detail );
  29914. }
  29915. }
  29916. class TorusBufferGeometry extends TorusGeometry { // @deprecated, r144
  29917. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  29918. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  29919. super( radius, tube, radialSegments, tubularSegments, arc );
  29920. }
  29921. }
  29922. class TorusKnotBufferGeometry extends TorusKnotGeometry { // @deprecated, r144
  29923. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  29924. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  29925. super( radius, tube, tubularSegments, radialSegments, p, q );
  29926. }
  29927. }
  29928. class TubeBufferGeometry extends TubeGeometry { // @deprecated, r144
  29929. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  29930. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  29931. super( path, tubularSegments, radius, radialSegments, closed );
  29932. }
  29933. }
  29934. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29935. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29936. revision: REVISION,
  29937. } } ) );
  29938. }
  29939. if ( typeof window !== 'undefined' ) {
  29940. if ( window.__THREE__ ) {
  29941. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29942. } else {
  29943. window.__THREE__ = REVISION;
  29944. }
  29945. }
  29946. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleBufferGeometry, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderBufferGeometry, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, Float64BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheBufferGeometry, LatheGeometry, Layers, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, Path, PerspectiveCamera, Plane, PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingBufferGeometry, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, Scene, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronBufferGeometry, TetrahedronGeometry, Texture, TextureLoader, TorusBufferGeometry, TorusGeometry, TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeBufferGeometry, TubeGeometry, TwoPassDoubleSide, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoTexture, WebGL1Renderer, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, sRGBEncoding };