three.module.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '151';
  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 SRGBToLinear( c ) {
  924. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  925. }
  926. function LinearToSRGB( c ) {
  927. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  928. }
  929. /**
  930. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  931. * or clipping. Based on W3C specifications for sRGB and Display P3,
  932. * and ICC specifications for the D50 connection space. Values in/out
  933. * are _linear_ sRGB and _linear_ Display P3.
  934. *
  935. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  936. *
  937. * Reference:
  938. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  939. */
  940. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().fromArray( [
  941. 0.8224621, 0.0331941, 0.0170827,
  942. 0.1775380, 0.9668058, 0.0723974,
  943. - 0.0000001, 0.0000001, 0.9105199
  944. ] );
  945. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().fromArray( [
  946. 1.2249401, - 0.0420569, - 0.0196376,
  947. - 0.2249404, 1.0420571, - 0.0786361,
  948. 0.0000001, 0.0000000, 1.0982735
  949. ] );
  950. function DisplayP3ToLinearSRGB( color ) {
  951. // Display P3 uses the sRGB transfer functions
  952. return color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB );
  953. }
  954. function LinearSRGBToDisplayP3( color ) {
  955. // Display P3 uses the sRGB transfer functions
  956. return color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB();
  957. }
  958. // Conversions from <source> to Linear-sRGB reference space.
  959. const TO_LINEAR = {
  960. [ LinearSRGBColorSpace ]: ( color ) => color,
  961. [ SRGBColorSpace ]: ( color ) => color.convertSRGBToLinear(),
  962. [ DisplayP3ColorSpace ]: DisplayP3ToLinearSRGB,
  963. };
  964. // Conversions to <target> from Linear-sRGB reference space.
  965. const FROM_LINEAR = {
  966. [ LinearSRGBColorSpace ]: ( color ) => color,
  967. [ SRGBColorSpace ]: ( color ) => color.convertLinearToSRGB(),
  968. [ DisplayP3ColorSpace ]: LinearSRGBToDisplayP3,
  969. };
  970. const ColorManagement = {
  971. enabled: false,
  972. get legacyMode() {
  973. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  974. return ! this.enabled;
  975. },
  976. set legacyMode( legacyMode ) {
  977. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  978. this.enabled = ! legacyMode;
  979. },
  980. get workingColorSpace() {
  981. return LinearSRGBColorSpace;
  982. },
  983. set workingColorSpace( colorSpace ) {
  984. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  985. },
  986. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  987. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  988. return color;
  989. }
  990. const sourceToLinear = TO_LINEAR[ sourceColorSpace ];
  991. const targetFromLinear = FROM_LINEAR[ targetColorSpace ];
  992. if ( sourceToLinear === undefined || targetFromLinear === undefined ) {
  993. throw new Error( `Unsupported color space conversion, "${ sourceColorSpace }" to "${ targetColorSpace }".` );
  994. }
  995. return targetFromLinear( sourceToLinear( color ) );
  996. },
  997. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  998. return this.convert( color, this.workingColorSpace, targetColorSpace );
  999. },
  1000. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1001. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1002. },
  1003. };
  1004. let _canvas;
  1005. class ImageUtils {
  1006. static getDataURL( image ) {
  1007. if ( /^data:/i.test( image.src ) ) {
  1008. return image.src;
  1009. }
  1010. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1011. return image.src;
  1012. }
  1013. let canvas;
  1014. if ( image instanceof HTMLCanvasElement ) {
  1015. canvas = image;
  1016. } else {
  1017. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1018. _canvas.width = image.width;
  1019. _canvas.height = image.height;
  1020. const context = _canvas.getContext( '2d' );
  1021. if ( image instanceof ImageData ) {
  1022. context.putImageData( image, 0, 0 );
  1023. } else {
  1024. context.drawImage( image, 0, 0, image.width, image.height );
  1025. }
  1026. canvas = _canvas;
  1027. }
  1028. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1029. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1030. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1031. } else {
  1032. return canvas.toDataURL( 'image/png' );
  1033. }
  1034. }
  1035. static sRGBToLinear( image ) {
  1036. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1037. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1038. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1039. const canvas = createElementNS( 'canvas' );
  1040. canvas.width = image.width;
  1041. canvas.height = image.height;
  1042. const context = canvas.getContext( '2d' );
  1043. context.drawImage( image, 0, 0, image.width, image.height );
  1044. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1045. const data = imageData.data;
  1046. for ( let i = 0; i < data.length; i ++ ) {
  1047. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1048. }
  1049. context.putImageData( imageData, 0, 0 );
  1050. return canvas;
  1051. } else if ( image.data ) {
  1052. const data = image.data.slice( 0 );
  1053. for ( let i = 0; i < data.length; i ++ ) {
  1054. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1055. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1056. } else {
  1057. // assuming float
  1058. data[ i ] = SRGBToLinear( data[ i ] );
  1059. }
  1060. }
  1061. return {
  1062. data: data,
  1063. width: image.width,
  1064. height: image.height
  1065. };
  1066. } else {
  1067. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1068. return image;
  1069. }
  1070. }
  1071. }
  1072. class Source {
  1073. constructor( data = null ) {
  1074. this.isSource = true;
  1075. this.uuid = generateUUID();
  1076. this.data = data;
  1077. this.version = 0;
  1078. }
  1079. set needsUpdate( value ) {
  1080. if ( value === true ) this.version ++;
  1081. }
  1082. toJSON( meta ) {
  1083. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1084. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1085. return meta.images[ this.uuid ];
  1086. }
  1087. const output = {
  1088. uuid: this.uuid,
  1089. url: ''
  1090. };
  1091. const data = this.data;
  1092. if ( data !== null ) {
  1093. let url;
  1094. if ( Array.isArray( data ) ) {
  1095. // cube texture
  1096. url = [];
  1097. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1098. if ( data[ i ].isDataTexture ) {
  1099. url.push( serializeImage( data[ i ].image ) );
  1100. } else {
  1101. url.push( serializeImage( data[ i ] ) );
  1102. }
  1103. }
  1104. } else {
  1105. // texture
  1106. url = serializeImage( data );
  1107. }
  1108. output.url = url;
  1109. }
  1110. if ( ! isRootObject ) {
  1111. meta.images[ this.uuid ] = output;
  1112. }
  1113. return output;
  1114. }
  1115. }
  1116. function serializeImage( image ) {
  1117. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1118. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1119. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1120. // default images
  1121. return ImageUtils.getDataURL( image );
  1122. } else {
  1123. if ( image.data ) {
  1124. // images of DataTexture
  1125. return {
  1126. data: Array.from( image.data ),
  1127. width: image.width,
  1128. height: image.height,
  1129. type: image.data.constructor.name
  1130. };
  1131. } else {
  1132. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1133. return {};
  1134. }
  1135. }
  1136. }
  1137. let textureId = 0;
  1138. class Texture extends EventDispatcher {
  1139. 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 ) {
  1140. super();
  1141. this.isTexture = true;
  1142. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1143. this.uuid = generateUUID();
  1144. this.name = '';
  1145. this.source = new Source( image );
  1146. this.mipmaps = [];
  1147. this.mapping = mapping;
  1148. this.channel = 0;
  1149. this.wrapS = wrapS;
  1150. this.wrapT = wrapT;
  1151. this.magFilter = magFilter;
  1152. this.minFilter = minFilter;
  1153. this.anisotropy = anisotropy;
  1154. this.format = format;
  1155. this.internalFormat = null;
  1156. this.type = type;
  1157. this.offset = new Vector2( 0, 0 );
  1158. this.repeat = new Vector2( 1, 1 );
  1159. this.center = new Vector2( 0, 0 );
  1160. this.rotation = 0;
  1161. this.matrixAutoUpdate = true;
  1162. this.matrix = new Matrix3();
  1163. this.generateMipmaps = true;
  1164. this.premultiplyAlpha = false;
  1165. this.flipY = true;
  1166. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1167. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1168. //
  1169. // Also changing the encoding after already used by a Material will not automatically make the Material
  1170. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1171. this.encoding = encoding;
  1172. this.userData = {};
  1173. this.version = 0;
  1174. this.onUpdate = null;
  1175. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1176. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1177. }
  1178. get image() {
  1179. return this.source.data;
  1180. }
  1181. set image( value = null ) {
  1182. this.source.data = value;
  1183. }
  1184. updateMatrix() {
  1185. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1186. }
  1187. clone() {
  1188. return new this.constructor().copy( this );
  1189. }
  1190. copy( source ) {
  1191. this.name = source.name;
  1192. this.source = source.source;
  1193. this.mipmaps = source.mipmaps.slice( 0 );
  1194. this.mapping = source.mapping;
  1195. this.channel = source.channel;
  1196. this.wrapS = source.wrapS;
  1197. this.wrapT = source.wrapT;
  1198. this.magFilter = source.magFilter;
  1199. this.minFilter = source.minFilter;
  1200. this.anisotropy = source.anisotropy;
  1201. this.format = source.format;
  1202. this.internalFormat = source.internalFormat;
  1203. this.type = source.type;
  1204. this.offset.copy( source.offset );
  1205. this.repeat.copy( source.repeat );
  1206. this.center.copy( source.center );
  1207. this.rotation = source.rotation;
  1208. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1209. this.matrix.copy( source.matrix );
  1210. this.generateMipmaps = source.generateMipmaps;
  1211. this.premultiplyAlpha = source.premultiplyAlpha;
  1212. this.flipY = source.flipY;
  1213. this.unpackAlignment = source.unpackAlignment;
  1214. this.encoding = source.encoding;
  1215. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1216. this.needsUpdate = true;
  1217. return this;
  1218. }
  1219. toJSON( meta ) {
  1220. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1221. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1222. return meta.textures[ this.uuid ];
  1223. }
  1224. const output = {
  1225. metadata: {
  1226. version: 4.5,
  1227. type: 'Texture',
  1228. generator: 'Texture.toJSON'
  1229. },
  1230. uuid: this.uuid,
  1231. name: this.name,
  1232. image: this.source.toJSON( meta ).uuid,
  1233. mapping: this.mapping,
  1234. channel: this.channel,
  1235. repeat: [ this.repeat.x, this.repeat.y ],
  1236. offset: [ this.offset.x, this.offset.y ],
  1237. center: [ this.center.x, this.center.y ],
  1238. rotation: this.rotation,
  1239. wrap: [ this.wrapS, this.wrapT ],
  1240. format: this.format,
  1241. internalFormat: this.internalFormat,
  1242. type: this.type,
  1243. encoding: this.encoding,
  1244. minFilter: this.minFilter,
  1245. magFilter: this.magFilter,
  1246. anisotropy: this.anisotropy,
  1247. flipY: this.flipY,
  1248. generateMipmaps: this.generateMipmaps,
  1249. premultiplyAlpha: this.premultiplyAlpha,
  1250. unpackAlignment: this.unpackAlignment
  1251. };
  1252. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1253. if ( ! isRootObject ) {
  1254. meta.textures[ this.uuid ] = output;
  1255. }
  1256. return output;
  1257. }
  1258. dispose() {
  1259. this.dispatchEvent( { type: 'dispose' } );
  1260. }
  1261. transformUv( uv ) {
  1262. if ( this.mapping !== UVMapping ) return uv;
  1263. uv.applyMatrix3( this.matrix );
  1264. if ( uv.x < 0 || uv.x > 1 ) {
  1265. switch ( this.wrapS ) {
  1266. case RepeatWrapping:
  1267. uv.x = uv.x - Math.floor( uv.x );
  1268. break;
  1269. case ClampToEdgeWrapping:
  1270. uv.x = uv.x < 0 ? 0 : 1;
  1271. break;
  1272. case MirroredRepeatWrapping:
  1273. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1274. uv.x = Math.ceil( uv.x ) - uv.x;
  1275. } else {
  1276. uv.x = uv.x - Math.floor( uv.x );
  1277. }
  1278. break;
  1279. }
  1280. }
  1281. if ( uv.y < 0 || uv.y > 1 ) {
  1282. switch ( this.wrapT ) {
  1283. case RepeatWrapping:
  1284. uv.y = uv.y - Math.floor( uv.y );
  1285. break;
  1286. case ClampToEdgeWrapping:
  1287. uv.y = uv.y < 0 ? 0 : 1;
  1288. break;
  1289. case MirroredRepeatWrapping:
  1290. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1291. uv.y = Math.ceil( uv.y ) - uv.y;
  1292. } else {
  1293. uv.y = uv.y - Math.floor( uv.y );
  1294. }
  1295. break;
  1296. }
  1297. }
  1298. if ( this.flipY ) {
  1299. uv.y = 1 - uv.y;
  1300. }
  1301. return uv;
  1302. }
  1303. set needsUpdate( value ) {
  1304. if ( value === true ) {
  1305. this.version ++;
  1306. this.source.needsUpdate = true;
  1307. }
  1308. }
  1309. }
  1310. Texture.DEFAULT_IMAGE = null;
  1311. Texture.DEFAULT_MAPPING = UVMapping;
  1312. Texture.DEFAULT_ANISOTROPY = 1;
  1313. class Vector4 {
  1314. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1315. Vector4.prototype.isVector4 = true;
  1316. this.x = x;
  1317. this.y = y;
  1318. this.z = z;
  1319. this.w = w;
  1320. }
  1321. get width() {
  1322. return this.z;
  1323. }
  1324. set width( value ) {
  1325. this.z = value;
  1326. }
  1327. get height() {
  1328. return this.w;
  1329. }
  1330. set height( value ) {
  1331. this.w = value;
  1332. }
  1333. set( x, y, z, w ) {
  1334. this.x = x;
  1335. this.y = y;
  1336. this.z = z;
  1337. this.w = w;
  1338. return this;
  1339. }
  1340. setScalar( scalar ) {
  1341. this.x = scalar;
  1342. this.y = scalar;
  1343. this.z = scalar;
  1344. this.w = scalar;
  1345. return this;
  1346. }
  1347. setX( x ) {
  1348. this.x = x;
  1349. return this;
  1350. }
  1351. setY( y ) {
  1352. this.y = y;
  1353. return this;
  1354. }
  1355. setZ( z ) {
  1356. this.z = z;
  1357. return this;
  1358. }
  1359. setW( w ) {
  1360. this.w = w;
  1361. return this;
  1362. }
  1363. setComponent( index, value ) {
  1364. switch ( index ) {
  1365. case 0: this.x = value; break;
  1366. case 1: this.y = value; break;
  1367. case 2: this.z = value; break;
  1368. case 3: this.w = value; break;
  1369. default: throw new Error( 'index is out of range: ' + index );
  1370. }
  1371. return this;
  1372. }
  1373. getComponent( index ) {
  1374. switch ( index ) {
  1375. case 0: return this.x;
  1376. case 1: return this.y;
  1377. case 2: return this.z;
  1378. case 3: return this.w;
  1379. default: throw new Error( 'index is out of range: ' + index );
  1380. }
  1381. }
  1382. clone() {
  1383. return new this.constructor( this.x, this.y, this.z, this.w );
  1384. }
  1385. copy( v ) {
  1386. this.x = v.x;
  1387. this.y = v.y;
  1388. this.z = v.z;
  1389. this.w = ( v.w !== undefined ) ? v.w : 1;
  1390. return this;
  1391. }
  1392. add( v ) {
  1393. this.x += v.x;
  1394. this.y += v.y;
  1395. this.z += v.z;
  1396. this.w += v.w;
  1397. return this;
  1398. }
  1399. addScalar( s ) {
  1400. this.x += s;
  1401. this.y += s;
  1402. this.z += s;
  1403. this.w += s;
  1404. return this;
  1405. }
  1406. addVectors( a, b ) {
  1407. this.x = a.x + b.x;
  1408. this.y = a.y + b.y;
  1409. this.z = a.z + b.z;
  1410. this.w = a.w + b.w;
  1411. return this;
  1412. }
  1413. addScaledVector( v, s ) {
  1414. this.x += v.x * s;
  1415. this.y += v.y * s;
  1416. this.z += v.z * s;
  1417. this.w += v.w * s;
  1418. return this;
  1419. }
  1420. sub( v ) {
  1421. this.x -= v.x;
  1422. this.y -= v.y;
  1423. this.z -= v.z;
  1424. this.w -= v.w;
  1425. return this;
  1426. }
  1427. subScalar( s ) {
  1428. this.x -= s;
  1429. this.y -= s;
  1430. this.z -= s;
  1431. this.w -= s;
  1432. return this;
  1433. }
  1434. subVectors( a, b ) {
  1435. this.x = a.x - b.x;
  1436. this.y = a.y - b.y;
  1437. this.z = a.z - b.z;
  1438. this.w = a.w - b.w;
  1439. return this;
  1440. }
  1441. multiply( v ) {
  1442. this.x *= v.x;
  1443. this.y *= v.y;
  1444. this.z *= v.z;
  1445. this.w *= v.w;
  1446. return this;
  1447. }
  1448. multiplyScalar( scalar ) {
  1449. this.x *= scalar;
  1450. this.y *= scalar;
  1451. this.z *= scalar;
  1452. this.w *= scalar;
  1453. return this;
  1454. }
  1455. applyMatrix4( m ) {
  1456. const x = this.x, y = this.y, z = this.z, w = this.w;
  1457. const e = m.elements;
  1458. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1459. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1460. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1461. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1462. return this;
  1463. }
  1464. divideScalar( scalar ) {
  1465. return this.multiplyScalar( 1 / scalar );
  1466. }
  1467. setAxisAngleFromQuaternion( q ) {
  1468. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1469. // q is assumed to be normalized
  1470. this.w = 2 * Math.acos( q.w );
  1471. const s = Math.sqrt( 1 - q.w * q.w );
  1472. if ( s < 0.0001 ) {
  1473. this.x = 1;
  1474. this.y = 0;
  1475. this.z = 0;
  1476. } else {
  1477. this.x = q.x / s;
  1478. this.y = q.y / s;
  1479. this.z = q.z / s;
  1480. }
  1481. return this;
  1482. }
  1483. setAxisAngleFromRotationMatrix( m ) {
  1484. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1485. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1486. let angle, x, y, z; // variables for result
  1487. const epsilon = 0.01, // margin to allow for rounding errors
  1488. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1489. te = m.elements,
  1490. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1491. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1492. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1493. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1494. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1495. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1496. // singularity found
  1497. // first check for identity matrix which must have +1 for all terms
  1498. // in leading diagonal and zero in other terms
  1499. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1500. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1501. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1502. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1503. // this singularity is identity matrix so angle = 0
  1504. this.set( 1, 0, 0, 0 );
  1505. return this; // zero angle, arbitrary axis
  1506. }
  1507. // otherwise this singularity is angle = 180
  1508. angle = Math.PI;
  1509. const xx = ( m11 + 1 ) / 2;
  1510. const yy = ( m22 + 1 ) / 2;
  1511. const zz = ( m33 + 1 ) / 2;
  1512. const xy = ( m12 + m21 ) / 4;
  1513. const xz = ( m13 + m31 ) / 4;
  1514. const yz = ( m23 + m32 ) / 4;
  1515. if ( ( xx > yy ) && ( xx > zz ) ) {
  1516. // m11 is the largest diagonal term
  1517. if ( xx < epsilon ) {
  1518. x = 0;
  1519. y = 0.707106781;
  1520. z = 0.707106781;
  1521. } else {
  1522. x = Math.sqrt( xx );
  1523. y = xy / x;
  1524. z = xz / x;
  1525. }
  1526. } else if ( yy > zz ) {
  1527. // m22 is the largest diagonal term
  1528. if ( yy < epsilon ) {
  1529. x = 0.707106781;
  1530. y = 0;
  1531. z = 0.707106781;
  1532. } else {
  1533. y = Math.sqrt( yy );
  1534. x = xy / y;
  1535. z = yz / y;
  1536. }
  1537. } else {
  1538. // m33 is the largest diagonal term so base result on this
  1539. if ( zz < epsilon ) {
  1540. x = 0.707106781;
  1541. y = 0.707106781;
  1542. z = 0;
  1543. } else {
  1544. z = Math.sqrt( zz );
  1545. x = xz / z;
  1546. y = yz / z;
  1547. }
  1548. }
  1549. this.set( x, y, z, angle );
  1550. return this; // return 180 deg rotation
  1551. }
  1552. // as we have reached here there are no singularities so we can handle normally
  1553. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1554. ( m13 - m31 ) * ( m13 - m31 ) +
  1555. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1556. if ( Math.abs( s ) < 0.001 ) s = 1;
  1557. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1558. // caught by singularity test above, but I've left it in just in case
  1559. this.x = ( m32 - m23 ) / s;
  1560. this.y = ( m13 - m31 ) / s;
  1561. this.z = ( m21 - m12 ) / s;
  1562. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1563. return this;
  1564. }
  1565. min( v ) {
  1566. this.x = Math.min( this.x, v.x );
  1567. this.y = Math.min( this.y, v.y );
  1568. this.z = Math.min( this.z, v.z );
  1569. this.w = Math.min( this.w, v.w );
  1570. return this;
  1571. }
  1572. max( v ) {
  1573. this.x = Math.max( this.x, v.x );
  1574. this.y = Math.max( this.y, v.y );
  1575. this.z = Math.max( this.z, v.z );
  1576. this.w = Math.max( this.w, v.w );
  1577. return this;
  1578. }
  1579. clamp( min, max ) {
  1580. // assumes min < max, componentwise
  1581. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1582. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1583. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1584. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1585. return this;
  1586. }
  1587. clampScalar( minVal, maxVal ) {
  1588. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1589. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1590. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1591. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1592. return this;
  1593. }
  1594. clampLength( min, max ) {
  1595. const length = this.length();
  1596. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1597. }
  1598. floor() {
  1599. this.x = Math.floor( this.x );
  1600. this.y = Math.floor( this.y );
  1601. this.z = Math.floor( this.z );
  1602. this.w = Math.floor( this.w );
  1603. return this;
  1604. }
  1605. ceil() {
  1606. this.x = Math.ceil( this.x );
  1607. this.y = Math.ceil( this.y );
  1608. this.z = Math.ceil( this.z );
  1609. this.w = Math.ceil( this.w );
  1610. return this;
  1611. }
  1612. round() {
  1613. this.x = Math.round( this.x );
  1614. this.y = Math.round( this.y );
  1615. this.z = Math.round( this.z );
  1616. this.w = Math.round( this.w );
  1617. return this;
  1618. }
  1619. roundToZero() {
  1620. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1621. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1622. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1623. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1624. return this;
  1625. }
  1626. negate() {
  1627. this.x = - this.x;
  1628. this.y = - this.y;
  1629. this.z = - this.z;
  1630. this.w = - this.w;
  1631. return this;
  1632. }
  1633. dot( v ) {
  1634. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1635. }
  1636. lengthSq() {
  1637. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1638. }
  1639. length() {
  1640. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1641. }
  1642. manhattanLength() {
  1643. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1644. }
  1645. normalize() {
  1646. return this.divideScalar( this.length() || 1 );
  1647. }
  1648. setLength( length ) {
  1649. return this.normalize().multiplyScalar( length );
  1650. }
  1651. lerp( v, alpha ) {
  1652. this.x += ( v.x - this.x ) * alpha;
  1653. this.y += ( v.y - this.y ) * alpha;
  1654. this.z += ( v.z - this.z ) * alpha;
  1655. this.w += ( v.w - this.w ) * alpha;
  1656. return this;
  1657. }
  1658. lerpVectors( v1, v2, alpha ) {
  1659. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1660. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1661. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1662. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1663. return this;
  1664. }
  1665. equals( v ) {
  1666. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1667. }
  1668. fromArray( array, offset = 0 ) {
  1669. this.x = array[ offset ];
  1670. this.y = array[ offset + 1 ];
  1671. this.z = array[ offset + 2 ];
  1672. this.w = array[ offset + 3 ];
  1673. return this;
  1674. }
  1675. toArray( array = [], offset = 0 ) {
  1676. array[ offset ] = this.x;
  1677. array[ offset + 1 ] = this.y;
  1678. array[ offset + 2 ] = this.z;
  1679. array[ offset + 3 ] = this.w;
  1680. return array;
  1681. }
  1682. fromBufferAttribute( attribute, index ) {
  1683. this.x = attribute.getX( index );
  1684. this.y = attribute.getY( index );
  1685. this.z = attribute.getZ( index );
  1686. this.w = attribute.getW( index );
  1687. return this;
  1688. }
  1689. random() {
  1690. this.x = Math.random();
  1691. this.y = Math.random();
  1692. this.z = Math.random();
  1693. this.w = Math.random();
  1694. return this;
  1695. }
  1696. *[ Symbol.iterator ]() {
  1697. yield this.x;
  1698. yield this.y;
  1699. yield this.z;
  1700. yield this.w;
  1701. }
  1702. }
  1703. /*
  1704. In options, we can specify:
  1705. * Texture parameters for an auto-generated target texture
  1706. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1707. */
  1708. class WebGLRenderTarget extends EventDispatcher {
  1709. constructor( width = 1, height = 1, options = {} ) {
  1710. super();
  1711. this.isWebGLRenderTarget = true;
  1712. this.width = width;
  1713. this.height = height;
  1714. this.depth = 1;
  1715. this.scissor = new Vector4( 0, 0, width, height );
  1716. this.scissorTest = false;
  1717. this.viewport = new Vector4( 0, 0, width, height );
  1718. const image = { width: width, height: height, depth: 1 };
  1719. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1720. this.texture.isRenderTargetTexture = true;
  1721. this.texture.flipY = false;
  1722. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1723. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1724. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1725. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1726. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1727. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1728. this.samples = options.samples !== undefined ? options.samples : 0;
  1729. }
  1730. setSize( width, height, depth = 1 ) {
  1731. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1732. this.width = width;
  1733. this.height = height;
  1734. this.depth = depth;
  1735. this.texture.image.width = width;
  1736. this.texture.image.height = height;
  1737. this.texture.image.depth = depth;
  1738. this.dispose();
  1739. }
  1740. this.viewport.set( 0, 0, width, height );
  1741. this.scissor.set( 0, 0, width, height );
  1742. }
  1743. clone() {
  1744. return new this.constructor().copy( this );
  1745. }
  1746. copy( source ) {
  1747. this.width = source.width;
  1748. this.height = source.height;
  1749. this.depth = source.depth;
  1750. this.viewport.copy( source.viewport );
  1751. this.texture = source.texture.clone();
  1752. this.texture.isRenderTargetTexture = true;
  1753. // ensure image object is not shared, see #20328
  1754. const image = Object.assign( {}, source.texture.image );
  1755. this.texture.source = new Source( image );
  1756. this.depthBuffer = source.depthBuffer;
  1757. this.stencilBuffer = source.stencilBuffer;
  1758. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1759. this.samples = source.samples;
  1760. return this;
  1761. }
  1762. dispose() {
  1763. this.dispatchEvent( { type: 'dispose' } );
  1764. }
  1765. }
  1766. class DataArrayTexture extends Texture {
  1767. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1768. super( null );
  1769. this.isDataArrayTexture = true;
  1770. this.image = { data, width, height, depth };
  1771. this.magFilter = NearestFilter;
  1772. this.minFilter = NearestFilter;
  1773. this.wrapR = ClampToEdgeWrapping;
  1774. this.generateMipmaps = false;
  1775. this.flipY = false;
  1776. this.unpackAlignment = 1;
  1777. }
  1778. }
  1779. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1780. constructor( width = 1, height = 1, depth = 1 ) {
  1781. super( width, height );
  1782. this.isWebGLArrayRenderTarget = true;
  1783. this.depth = depth;
  1784. this.texture = new DataArrayTexture( null, width, height, depth );
  1785. this.texture.isRenderTargetTexture = true;
  1786. }
  1787. }
  1788. class Data3DTexture extends Texture {
  1789. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1790. // We're going to add .setXXX() methods for setting properties later.
  1791. // Users can still set in DataTexture3D directly.
  1792. //
  1793. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1794. // texture.anisotropy = 16;
  1795. //
  1796. // See #14839
  1797. super( null );
  1798. this.isData3DTexture = true;
  1799. this.image = { data, width, height, depth };
  1800. this.magFilter = NearestFilter;
  1801. this.minFilter = NearestFilter;
  1802. this.wrapR = ClampToEdgeWrapping;
  1803. this.generateMipmaps = false;
  1804. this.flipY = false;
  1805. this.unpackAlignment = 1;
  1806. }
  1807. }
  1808. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1809. constructor( width = 1, height = 1, depth = 1 ) {
  1810. super( width, height );
  1811. this.isWebGL3DRenderTarget = true;
  1812. this.depth = depth;
  1813. this.texture = new Data3DTexture( null, width, height, depth );
  1814. this.texture.isRenderTargetTexture = true;
  1815. }
  1816. }
  1817. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1818. constructor( width = 1, height = 1, count = 1, options = {} ) {
  1819. super( width, height, options );
  1820. this.isWebGLMultipleRenderTargets = true;
  1821. const texture = this.texture;
  1822. this.texture = [];
  1823. for ( let i = 0; i < count; i ++ ) {
  1824. this.texture[ i ] = texture.clone();
  1825. this.texture[ i ].isRenderTargetTexture = true;
  1826. }
  1827. }
  1828. setSize( width, height, depth = 1 ) {
  1829. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1830. this.width = width;
  1831. this.height = height;
  1832. this.depth = depth;
  1833. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1834. this.texture[ i ].image.width = width;
  1835. this.texture[ i ].image.height = height;
  1836. this.texture[ i ].image.depth = depth;
  1837. }
  1838. this.dispose();
  1839. }
  1840. this.viewport.set( 0, 0, width, height );
  1841. this.scissor.set( 0, 0, width, height );
  1842. return this;
  1843. }
  1844. copy( source ) {
  1845. this.dispose();
  1846. this.width = source.width;
  1847. this.height = source.height;
  1848. this.depth = source.depth;
  1849. this.viewport.set( 0, 0, this.width, this.height );
  1850. this.scissor.set( 0, 0, this.width, this.height );
  1851. this.depthBuffer = source.depthBuffer;
  1852. this.stencilBuffer = source.stencilBuffer;
  1853. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1854. this.texture.length = 0;
  1855. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1856. this.texture[ i ] = source.texture[ i ].clone();
  1857. this.texture[ i ].isRenderTargetTexture = true;
  1858. }
  1859. return this;
  1860. }
  1861. }
  1862. class Quaternion {
  1863. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1864. this.isQuaternion = true;
  1865. this._x = x;
  1866. this._y = y;
  1867. this._z = z;
  1868. this._w = w;
  1869. }
  1870. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1871. // fuzz-free, array-based Quaternion SLERP operation
  1872. let x0 = src0[ srcOffset0 + 0 ],
  1873. y0 = src0[ srcOffset0 + 1 ],
  1874. z0 = src0[ srcOffset0 + 2 ],
  1875. w0 = src0[ srcOffset0 + 3 ];
  1876. const x1 = src1[ srcOffset1 + 0 ],
  1877. y1 = src1[ srcOffset1 + 1 ],
  1878. z1 = src1[ srcOffset1 + 2 ],
  1879. w1 = src1[ srcOffset1 + 3 ];
  1880. if ( t === 0 ) {
  1881. dst[ dstOffset + 0 ] = x0;
  1882. dst[ dstOffset + 1 ] = y0;
  1883. dst[ dstOffset + 2 ] = z0;
  1884. dst[ dstOffset + 3 ] = w0;
  1885. return;
  1886. }
  1887. if ( t === 1 ) {
  1888. dst[ dstOffset + 0 ] = x1;
  1889. dst[ dstOffset + 1 ] = y1;
  1890. dst[ dstOffset + 2 ] = z1;
  1891. dst[ dstOffset + 3 ] = w1;
  1892. return;
  1893. }
  1894. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1895. let s = 1 - t;
  1896. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1897. dir = ( cos >= 0 ? 1 : - 1 ),
  1898. sqrSin = 1 - cos * cos;
  1899. // Skip the Slerp for tiny steps to avoid numeric problems:
  1900. if ( sqrSin > Number.EPSILON ) {
  1901. const sin = Math.sqrt( sqrSin ),
  1902. len = Math.atan2( sin, cos * dir );
  1903. s = Math.sin( s * len ) / sin;
  1904. t = Math.sin( t * len ) / sin;
  1905. }
  1906. const tDir = t * dir;
  1907. x0 = x0 * s + x1 * tDir;
  1908. y0 = y0 * s + y1 * tDir;
  1909. z0 = z0 * s + z1 * tDir;
  1910. w0 = w0 * s + w1 * tDir;
  1911. // Normalize in case we just did a lerp:
  1912. if ( s === 1 - t ) {
  1913. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1914. x0 *= f;
  1915. y0 *= f;
  1916. z0 *= f;
  1917. w0 *= f;
  1918. }
  1919. }
  1920. dst[ dstOffset ] = x0;
  1921. dst[ dstOffset + 1 ] = y0;
  1922. dst[ dstOffset + 2 ] = z0;
  1923. dst[ dstOffset + 3 ] = w0;
  1924. }
  1925. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1926. const x0 = src0[ srcOffset0 ];
  1927. const y0 = src0[ srcOffset0 + 1 ];
  1928. const z0 = src0[ srcOffset0 + 2 ];
  1929. const w0 = src0[ srcOffset0 + 3 ];
  1930. const x1 = src1[ srcOffset1 ];
  1931. const y1 = src1[ srcOffset1 + 1 ];
  1932. const z1 = src1[ srcOffset1 + 2 ];
  1933. const w1 = src1[ srcOffset1 + 3 ];
  1934. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1935. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1936. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1937. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1938. return dst;
  1939. }
  1940. get x() {
  1941. return this._x;
  1942. }
  1943. set x( value ) {
  1944. this._x = value;
  1945. this._onChangeCallback();
  1946. }
  1947. get y() {
  1948. return this._y;
  1949. }
  1950. set y( value ) {
  1951. this._y = value;
  1952. this._onChangeCallback();
  1953. }
  1954. get z() {
  1955. return this._z;
  1956. }
  1957. set z( value ) {
  1958. this._z = value;
  1959. this._onChangeCallback();
  1960. }
  1961. get w() {
  1962. return this._w;
  1963. }
  1964. set w( value ) {
  1965. this._w = value;
  1966. this._onChangeCallback();
  1967. }
  1968. set( x, y, z, w ) {
  1969. this._x = x;
  1970. this._y = y;
  1971. this._z = z;
  1972. this._w = w;
  1973. this._onChangeCallback();
  1974. return this;
  1975. }
  1976. clone() {
  1977. return new this.constructor( this._x, this._y, this._z, this._w );
  1978. }
  1979. copy( quaternion ) {
  1980. this._x = quaternion.x;
  1981. this._y = quaternion.y;
  1982. this._z = quaternion.z;
  1983. this._w = quaternion.w;
  1984. this._onChangeCallback();
  1985. return this;
  1986. }
  1987. setFromEuler( euler, update ) {
  1988. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1989. // http://www.mathworks.com/matlabcentral/fileexchange/
  1990. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1991. // content/SpinCalc.m
  1992. const cos = Math.cos;
  1993. const sin = Math.sin;
  1994. const c1 = cos( x / 2 );
  1995. const c2 = cos( y / 2 );
  1996. const c3 = cos( z / 2 );
  1997. const s1 = sin( x / 2 );
  1998. const s2 = sin( y / 2 );
  1999. const s3 = sin( z / 2 );
  2000. switch ( order ) {
  2001. case 'XYZ':
  2002. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2003. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2004. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2005. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2006. break;
  2007. case 'YXZ':
  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 'ZXY':
  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 'ZYX':
  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 'YZX':
  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 'XZY':
  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. default:
  2038. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2039. }
  2040. if ( update !== false ) this._onChangeCallback();
  2041. return this;
  2042. }
  2043. setFromAxisAngle( axis, angle ) {
  2044. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2045. // assumes axis is normalized
  2046. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2047. this._x = axis.x * s;
  2048. this._y = axis.y * s;
  2049. this._z = axis.z * s;
  2050. this._w = Math.cos( halfAngle );
  2051. this._onChangeCallback();
  2052. return this;
  2053. }
  2054. setFromRotationMatrix( m ) {
  2055. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2056. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2057. const te = m.elements,
  2058. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2059. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2060. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2061. trace = m11 + m22 + m33;
  2062. if ( trace > 0 ) {
  2063. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2064. this._w = 0.25 / s;
  2065. this._x = ( m32 - m23 ) * s;
  2066. this._y = ( m13 - m31 ) * s;
  2067. this._z = ( m21 - m12 ) * s;
  2068. } else if ( m11 > m22 && m11 > m33 ) {
  2069. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2070. this._w = ( m32 - m23 ) / s;
  2071. this._x = 0.25 * s;
  2072. this._y = ( m12 + m21 ) / s;
  2073. this._z = ( m13 + m31 ) / s;
  2074. } else if ( m22 > m33 ) {
  2075. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2076. this._w = ( m13 - m31 ) / s;
  2077. this._x = ( m12 + m21 ) / s;
  2078. this._y = 0.25 * s;
  2079. this._z = ( m23 + m32 ) / s;
  2080. } else {
  2081. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2082. this._w = ( m21 - m12 ) / s;
  2083. this._x = ( m13 + m31 ) / s;
  2084. this._y = ( m23 + m32 ) / s;
  2085. this._z = 0.25 * s;
  2086. }
  2087. this._onChangeCallback();
  2088. return this;
  2089. }
  2090. setFromUnitVectors( vFrom, vTo ) {
  2091. // assumes direction vectors vFrom and vTo are normalized
  2092. let r = vFrom.dot( vTo ) + 1;
  2093. if ( r < Number.EPSILON ) {
  2094. // vFrom and vTo point in opposite directions
  2095. r = 0;
  2096. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2097. this._x = - vFrom.y;
  2098. this._y = vFrom.x;
  2099. this._z = 0;
  2100. this._w = r;
  2101. } else {
  2102. this._x = 0;
  2103. this._y = - vFrom.z;
  2104. this._z = vFrom.y;
  2105. this._w = r;
  2106. }
  2107. } else {
  2108. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2109. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2110. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2111. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2112. this._w = r;
  2113. }
  2114. return this.normalize();
  2115. }
  2116. angleTo( q ) {
  2117. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2118. }
  2119. rotateTowards( q, step ) {
  2120. const angle = this.angleTo( q );
  2121. if ( angle === 0 ) return this;
  2122. const t = Math.min( 1, step / angle );
  2123. this.slerp( q, t );
  2124. return this;
  2125. }
  2126. identity() {
  2127. return this.set( 0, 0, 0, 1 );
  2128. }
  2129. invert() {
  2130. // quaternion is assumed to have unit length
  2131. return this.conjugate();
  2132. }
  2133. conjugate() {
  2134. this._x *= - 1;
  2135. this._y *= - 1;
  2136. this._z *= - 1;
  2137. this._onChangeCallback();
  2138. return this;
  2139. }
  2140. dot( v ) {
  2141. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2142. }
  2143. lengthSq() {
  2144. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2145. }
  2146. length() {
  2147. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2148. }
  2149. normalize() {
  2150. let l = this.length();
  2151. if ( l === 0 ) {
  2152. this._x = 0;
  2153. this._y = 0;
  2154. this._z = 0;
  2155. this._w = 1;
  2156. } else {
  2157. l = 1 / l;
  2158. this._x = this._x * l;
  2159. this._y = this._y * l;
  2160. this._z = this._z * l;
  2161. this._w = this._w * l;
  2162. }
  2163. this._onChangeCallback();
  2164. return this;
  2165. }
  2166. multiply( q ) {
  2167. return this.multiplyQuaternions( this, q );
  2168. }
  2169. premultiply( q ) {
  2170. return this.multiplyQuaternions( q, this );
  2171. }
  2172. multiplyQuaternions( a, b ) {
  2173. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2174. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2175. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2176. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2177. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2178. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2179. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2180. this._onChangeCallback();
  2181. return this;
  2182. }
  2183. slerp( qb, t ) {
  2184. if ( t === 0 ) return this;
  2185. if ( t === 1 ) return this.copy( qb );
  2186. const x = this._x, y = this._y, z = this._z, w = this._w;
  2187. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2188. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2189. if ( cosHalfTheta < 0 ) {
  2190. this._w = - qb._w;
  2191. this._x = - qb._x;
  2192. this._y = - qb._y;
  2193. this._z = - qb._z;
  2194. cosHalfTheta = - cosHalfTheta;
  2195. } else {
  2196. this.copy( qb );
  2197. }
  2198. if ( cosHalfTheta >= 1.0 ) {
  2199. this._w = w;
  2200. this._x = x;
  2201. this._y = y;
  2202. this._z = z;
  2203. return this;
  2204. }
  2205. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2206. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2207. const s = 1 - t;
  2208. this._w = s * w + t * this._w;
  2209. this._x = s * x + t * this._x;
  2210. this._y = s * y + t * this._y;
  2211. this._z = s * z + t * this._z;
  2212. this.normalize();
  2213. this._onChangeCallback();
  2214. return this;
  2215. }
  2216. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2217. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2218. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2219. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2220. this._w = ( w * ratioA + this._w * ratioB );
  2221. this._x = ( x * ratioA + this._x * ratioB );
  2222. this._y = ( y * ratioA + this._y * ratioB );
  2223. this._z = ( z * ratioA + this._z * ratioB );
  2224. this._onChangeCallback();
  2225. return this;
  2226. }
  2227. slerpQuaternions( qa, qb, t ) {
  2228. return this.copy( qa ).slerp( qb, t );
  2229. }
  2230. random() {
  2231. // Derived from http://planning.cs.uiuc.edu/node198.html
  2232. // Note, this source uses w, x, y, z ordering,
  2233. // so we swap the order below.
  2234. const u1 = Math.random();
  2235. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2236. const sqrtu1 = Math.sqrt( u1 );
  2237. const u2 = 2 * Math.PI * Math.random();
  2238. const u3 = 2 * Math.PI * Math.random();
  2239. return this.set(
  2240. sqrt1u1 * Math.cos( u2 ),
  2241. sqrtu1 * Math.sin( u3 ),
  2242. sqrtu1 * Math.cos( u3 ),
  2243. sqrt1u1 * Math.sin( u2 ),
  2244. );
  2245. }
  2246. equals( quaternion ) {
  2247. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2248. }
  2249. fromArray( array, offset = 0 ) {
  2250. this._x = array[ offset ];
  2251. this._y = array[ offset + 1 ];
  2252. this._z = array[ offset + 2 ];
  2253. this._w = array[ offset + 3 ];
  2254. this._onChangeCallback();
  2255. return this;
  2256. }
  2257. toArray( array = [], offset = 0 ) {
  2258. array[ offset ] = this._x;
  2259. array[ offset + 1 ] = this._y;
  2260. array[ offset + 2 ] = this._z;
  2261. array[ offset + 3 ] = this._w;
  2262. return array;
  2263. }
  2264. fromBufferAttribute( attribute, index ) {
  2265. this._x = attribute.getX( index );
  2266. this._y = attribute.getY( index );
  2267. this._z = attribute.getZ( index );
  2268. this._w = attribute.getW( index );
  2269. return this;
  2270. }
  2271. toJSON() {
  2272. return this.toArray();
  2273. }
  2274. _onChange( callback ) {
  2275. this._onChangeCallback = callback;
  2276. return this;
  2277. }
  2278. _onChangeCallback() {}
  2279. *[ Symbol.iterator ]() {
  2280. yield this._x;
  2281. yield this._y;
  2282. yield this._z;
  2283. yield this._w;
  2284. }
  2285. }
  2286. class Vector3 {
  2287. constructor( x = 0, y = 0, z = 0 ) {
  2288. Vector3.prototype.isVector3 = true;
  2289. this.x = x;
  2290. this.y = y;
  2291. this.z = z;
  2292. }
  2293. set( x, y, z ) {
  2294. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2295. this.x = x;
  2296. this.y = y;
  2297. this.z = z;
  2298. return this;
  2299. }
  2300. setScalar( scalar ) {
  2301. this.x = scalar;
  2302. this.y = scalar;
  2303. this.z = scalar;
  2304. return this;
  2305. }
  2306. setX( x ) {
  2307. this.x = x;
  2308. return this;
  2309. }
  2310. setY( y ) {
  2311. this.y = y;
  2312. return this;
  2313. }
  2314. setZ( z ) {
  2315. this.z = z;
  2316. return this;
  2317. }
  2318. setComponent( index, value ) {
  2319. switch ( index ) {
  2320. case 0: this.x = value; break;
  2321. case 1: this.y = value; break;
  2322. case 2: this.z = value; break;
  2323. default: throw new Error( 'index is out of range: ' + index );
  2324. }
  2325. return this;
  2326. }
  2327. getComponent( index ) {
  2328. switch ( index ) {
  2329. case 0: return this.x;
  2330. case 1: return this.y;
  2331. case 2: return this.z;
  2332. default: throw new Error( 'index is out of range: ' + index );
  2333. }
  2334. }
  2335. clone() {
  2336. return new this.constructor( this.x, this.y, this.z );
  2337. }
  2338. copy( v ) {
  2339. this.x = v.x;
  2340. this.y = v.y;
  2341. this.z = v.z;
  2342. return this;
  2343. }
  2344. add( v ) {
  2345. this.x += v.x;
  2346. this.y += v.y;
  2347. this.z += v.z;
  2348. return this;
  2349. }
  2350. addScalar( s ) {
  2351. this.x += s;
  2352. this.y += s;
  2353. this.z += s;
  2354. return this;
  2355. }
  2356. addVectors( a, b ) {
  2357. this.x = a.x + b.x;
  2358. this.y = a.y + b.y;
  2359. this.z = a.z + b.z;
  2360. return this;
  2361. }
  2362. addScaledVector( v, s ) {
  2363. this.x += v.x * s;
  2364. this.y += v.y * s;
  2365. this.z += v.z * s;
  2366. return this;
  2367. }
  2368. sub( v ) {
  2369. this.x -= v.x;
  2370. this.y -= v.y;
  2371. this.z -= v.z;
  2372. return this;
  2373. }
  2374. subScalar( s ) {
  2375. this.x -= s;
  2376. this.y -= s;
  2377. this.z -= s;
  2378. return this;
  2379. }
  2380. subVectors( a, b ) {
  2381. this.x = a.x - b.x;
  2382. this.y = a.y - b.y;
  2383. this.z = a.z - b.z;
  2384. return this;
  2385. }
  2386. multiply( v ) {
  2387. this.x *= v.x;
  2388. this.y *= v.y;
  2389. this.z *= v.z;
  2390. return this;
  2391. }
  2392. multiplyScalar( scalar ) {
  2393. this.x *= scalar;
  2394. this.y *= scalar;
  2395. this.z *= scalar;
  2396. return this;
  2397. }
  2398. multiplyVectors( a, b ) {
  2399. this.x = a.x * b.x;
  2400. this.y = a.y * b.y;
  2401. this.z = a.z * b.z;
  2402. return this;
  2403. }
  2404. applyEuler( euler ) {
  2405. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2406. }
  2407. applyAxisAngle( axis, angle ) {
  2408. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2409. }
  2410. applyMatrix3( m ) {
  2411. const x = this.x, y = this.y, z = this.z;
  2412. const e = m.elements;
  2413. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2414. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2415. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2416. return this;
  2417. }
  2418. applyNormalMatrix( m ) {
  2419. return this.applyMatrix3( m ).normalize();
  2420. }
  2421. applyMatrix4( m ) {
  2422. const x = this.x, y = this.y, z = this.z;
  2423. const e = m.elements;
  2424. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2425. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2426. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2427. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2428. return this;
  2429. }
  2430. applyQuaternion( q ) {
  2431. const x = this.x, y = this.y, z = this.z;
  2432. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2433. // calculate quat * vector
  2434. const ix = qw * x + qy * z - qz * y;
  2435. const iy = qw * y + qz * x - qx * z;
  2436. const iz = qw * z + qx * y - qy * x;
  2437. const iw = - qx * x - qy * y - qz * z;
  2438. // calculate result * inverse quat
  2439. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2440. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2441. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2442. return this;
  2443. }
  2444. project( camera ) {
  2445. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2446. }
  2447. unproject( camera ) {
  2448. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2449. }
  2450. transformDirection( m ) {
  2451. // input: THREE.Matrix4 affine matrix
  2452. // vector interpreted as a direction
  2453. const x = this.x, y = this.y, z = this.z;
  2454. const e = m.elements;
  2455. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2456. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2457. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2458. return this.normalize();
  2459. }
  2460. divide( v ) {
  2461. this.x /= v.x;
  2462. this.y /= v.y;
  2463. this.z /= v.z;
  2464. return this;
  2465. }
  2466. divideScalar( scalar ) {
  2467. return this.multiplyScalar( 1 / scalar );
  2468. }
  2469. min( v ) {
  2470. this.x = Math.min( this.x, v.x );
  2471. this.y = Math.min( this.y, v.y );
  2472. this.z = Math.min( this.z, v.z );
  2473. return this;
  2474. }
  2475. max( v ) {
  2476. this.x = Math.max( this.x, v.x );
  2477. this.y = Math.max( this.y, v.y );
  2478. this.z = Math.max( this.z, v.z );
  2479. return this;
  2480. }
  2481. clamp( min, max ) {
  2482. // assumes min < max, componentwise
  2483. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2484. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2485. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2486. return this;
  2487. }
  2488. clampScalar( minVal, maxVal ) {
  2489. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2490. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2491. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2492. return this;
  2493. }
  2494. clampLength( min, max ) {
  2495. const length = this.length();
  2496. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2497. }
  2498. floor() {
  2499. this.x = Math.floor( this.x );
  2500. this.y = Math.floor( this.y );
  2501. this.z = Math.floor( this.z );
  2502. return this;
  2503. }
  2504. ceil() {
  2505. this.x = Math.ceil( this.x );
  2506. this.y = Math.ceil( this.y );
  2507. this.z = Math.ceil( this.z );
  2508. return this;
  2509. }
  2510. round() {
  2511. this.x = Math.round( this.x );
  2512. this.y = Math.round( this.y );
  2513. this.z = Math.round( this.z );
  2514. return this;
  2515. }
  2516. roundToZero() {
  2517. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2518. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2519. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2520. return this;
  2521. }
  2522. negate() {
  2523. this.x = - this.x;
  2524. this.y = - this.y;
  2525. this.z = - this.z;
  2526. return this;
  2527. }
  2528. dot( v ) {
  2529. return this.x * v.x + this.y * v.y + this.z * v.z;
  2530. }
  2531. // TODO lengthSquared?
  2532. lengthSq() {
  2533. return this.x * this.x + this.y * this.y + this.z * this.z;
  2534. }
  2535. length() {
  2536. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2537. }
  2538. manhattanLength() {
  2539. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2540. }
  2541. normalize() {
  2542. return this.divideScalar( this.length() || 1 );
  2543. }
  2544. setLength( length ) {
  2545. return this.normalize().multiplyScalar( length );
  2546. }
  2547. lerp( v, alpha ) {
  2548. this.x += ( v.x - this.x ) * alpha;
  2549. this.y += ( v.y - this.y ) * alpha;
  2550. this.z += ( v.z - this.z ) * alpha;
  2551. return this;
  2552. }
  2553. lerpVectors( v1, v2, alpha ) {
  2554. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2555. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2556. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2557. return this;
  2558. }
  2559. cross( v ) {
  2560. return this.crossVectors( this, v );
  2561. }
  2562. crossVectors( a, b ) {
  2563. const ax = a.x, ay = a.y, az = a.z;
  2564. const bx = b.x, by = b.y, bz = b.z;
  2565. this.x = ay * bz - az * by;
  2566. this.y = az * bx - ax * bz;
  2567. this.z = ax * by - ay * bx;
  2568. return this;
  2569. }
  2570. projectOnVector( v ) {
  2571. const denominator = v.lengthSq();
  2572. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2573. const scalar = v.dot( this ) / denominator;
  2574. return this.copy( v ).multiplyScalar( scalar );
  2575. }
  2576. projectOnPlane( planeNormal ) {
  2577. _vector$b.copy( this ).projectOnVector( planeNormal );
  2578. return this.sub( _vector$b );
  2579. }
  2580. reflect( normal ) {
  2581. // reflect incident vector off plane orthogonal to normal
  2582. // normal is assumed to have unit length
  2583. return this.sub( _vector$b.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2584. }
  2585. angleTo( v ) {
  2586. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2587. if ( denominator === 0 ) return Math.PI / 2;
  2588. const theta = this.dot( v ) / denominator;
  2589. // clamp, to handle numerical problems
  2590. return Math.acos( clamp( theta, - 1, 1 ) );
  2591. }
  2592. distanceTo( v ) {
  2593. return Math.sqrt( this.distanceToSquared( v ) );
  2594. }
  2595. distanceToSquared( v ) {
  2596. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2597. return dx * dx + dy * dy + dz * dz;
  2598. }
  2599. manhattanDistanceTo( v ) {
  2600. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2601. }
  2602. setFromSpherical( s ) {
  2603. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2604. }
  2605. setFromSphericalCoords( radius, phi, theta ) {
  2606. const sinPhiRadius = Math.sin( phi ) * radius;
  2607. this.x = sinPhiRadius * Math.sin( theta );
  2608. this.y = Math.cos( phi ) * radius;
  2609. this.z = sinPhiRadius * Math.cos( theta );
  2610. return this;
  2611. }
  2612. setFromCylindrical( c ) {
  2613. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2614. }
  2615. setFromCylindricalCoords( radius, theta, y ) {
  2616. this.x = radius * Math.sin( theta );
  2617. this.y = y;
  2618. this.z = radius * Math.cos( theta );
  2619. return this;
  2620. }
  2621. setFromMatrixPosition( m ) {
  2622. const e = m.elements;
  2623. this.x = e[ 12 ];
  2624. this.y = e[ 13 ];
  2625. this.z = e[ 14 ];
  2626. return this;
  2627. }
  2628. setFromMatrixScale( m ) {
  2629. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2630. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2631. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2632. this.x = sx;
  2633. this.y = sy;
  2634. this.z = sz;
  2635. return this;
  2636. }
  2637. setFromMatrixColumn( m, index ) {
  2638. return this.fromArray( m.elements, index * 4 );
  2639. }
  2640. setFromMatrix3Column( m, index ) {
  2641. return this.fromArray( m.elements, index * 3 );
  2642. }
  2643. setFromEuler( e ) {
  2644. this.x = e._x;
  2645. this.y = e._y;
  2646. this.z = e._z;
  2647. return this;
  2648. }
  2649. setFromColor( c ) {
  2650. this.x = c.r;
  2651. this.y = c.g;
  2652. this.z = c.b;
  2653. return this;
  2654. }
  2655. equals( v ) {
  2656. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2657. }
  2658. fromArray( array, offset = 0 ) {
  2659. this.x = array[ offset ];
  2660. this.y = array[ offset + 1 ];
  2661. this.z = array[ offset + 2 ];
  2662. return this;
  2663. }
  2664. toArray( array = [], offset = 0 ) {
  2665. array[ offset ] = this.x;
  2666. array[ offset + 1 ] = this.y;
  2667. array[ offset + 2 ] = this.z;
  2668. return array;
  2669. }
  2670. fromBufferAttribute( attribute, index ) {
  2671. this.x = attribute.getX( index );
  2672. this.y = attribute.getY( index );
  2673. this.z = attribute.getZ( index );
  2674. return this;
  2675. }
  2676. random() {
  2677. this.x = Math.random();
  2678. this.y = Math.random();
  2679. this.z = Math.random();
  2680. return this;
  2681. }
  2682. randomDirection() {
  2683. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2684. const u = ( Math.random() - 0.5 ) * 2;
  2685. const t = Math.random() * Math.PI * 2;
  2686. const f = Math.sqrt( 1 - u ** 2 );
  2687. this.x = f * Math.cos( t );
  2688. this.y = f * Math.sin( t );
  2689. this.z = u;
  2690. return this;
  2691. }
  2692. *[ Symbol.iterator ]() {
  2693. yield this.x;
  2694. yield this.y;
  2695. yield this.z;
  2696. }
  2697. }
  2698. const _vector$b = /*@__PURE__*/ new Vector3();
  2699. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2700. class Box3 {
  2701. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2702. this.isBox3 = true;
  2703. this.min = min;
  2704. this.max = max;
  2705. }
  2706. set( min, max ) {
  2707. this.min.copy( min );
  2708. this.max.copy( max );
  2709. return this;
  2710. }
  2711. setFromArray( array ) {
  2712. this.makeEmpty();
  2713. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2714. this.expandByPoint( _vector$a.fromArray( array, i ) );
  2715. }
  2716. return this;
  2717. }
  2718. setFromBufferAttribute( attribute ) {
  2719. this.makeEmpty();
  2720. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2721. this.expandByPoint( _vector$a.fromBufferAttribute( attribute, i ) );
  2722. }
  2723. return this;
  2724. }
  2725. setFromPoints( points ) {
  2726. this.makeEmpty();
  2727. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2728. this.expandByPoint( points[ i ] );
  2729. }
  2730. return this;
  2731. }
  2732. setFromCenterAndSize( center, size ) {
  2733. const halfSize = _vector$a.copy( size ).multiplyScalar( 0.5 );
  2734. this.min.copy( center ).sub( halfSize );
  2735. this.max.copy( center ).add( halfSize );
  2736. return this;
  2737. }
  2738. setFromObject( object, precise = false ) {
  2739. this.makeEmpty();
  2740. return this.expandByObject( object, precise );
  2741. }
  2742. clone() {
  2743. return new this.constructor().copy( this );
  2744. }
  2745. copy( box ) {
  2746. this.min.copy( box.min );
  2747. this.max.copy( box.max );
  2748. return this;
  2749. }
  2750. makeEmpty() {
  2751. this.min.x = this.min.y = this.min.z = + Infinity;
  2752. this.max.x = this.max.y = this.max.z = - Infinity;
  2753. return this;
  2754. }
  2755. isEmpty() {
  2756. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2757. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2758. }
  2759. getCenter( target ) {
  2760. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2761. }
  2762. getSize( target ) {
  2763. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2764. }
  2765. expandByPoint( point ) {
  2766. this.min.min( point );
  2767. this.max.max( point );
  2768. return this;
  2769. }
  2770. expandByVector( vector ) {
  2771. this.min.sub( vector );
  2772. this.max.add( vector );
  2773. return this;
  2774. }
  2775. expandByScalar( scalar ) {
  2776. this.min.addScalar( - scalar );
  2777. this.max.addScalar( scalar );
  2778. return this;
  2779. }
  2780. expandByObject( object, precise = false ) {
  2781. // Computes the world-axis-aligned bounding box of an object (including its children),
  2782. // accounting for both the object's, and children's, world transforms
  2783. object.updateWorldMatrix( false, false );
  2784. if ( object.boundingBox !== undefined ) {
  2785. if ( object.boundingBox === null ) {
  2786. object.computeBoundingBox();
  2787. }
  2788. _box$3.copy( object.boundingBox );
  2789. _box$3.applyMatrix4( object.matrixWorld );
  2790. this.union( _box$3 );
  2791. } else {
  2792. const geometry = object.geometry;
  2793. if ( geometry !== undefined ) {
  2794. if ( precise && geometry.attributes !== undefined && geometry.attributes.position !== undefined ) {
  2795. const position = geometry.attributes.position;
  2796. for ( let i = 0, l = position.count; i < l; i ++ ) {
  2797. _vector$a.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  2798. this.expandByPoint( _vector$a );
  2799. }
  2800. } else {
  2801. if ( geometry.boundingBox === null ) {
  2802. geometry.computeBoundingBox();
  2803. }
  2804. _box$3.copy( geometry.boundingBox );
  2805. _box$3.applyMatrix4( object.matrixWorld );
  2806. this.union( _box$3 );
  2807. }
  2808. }
  2809. }
  2810. const children = object.children;
  2811. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2812. this.expandByObject( children[ i ], precise );
  2813. }
  2814. return this;
  2815. }
  2816. containsPoint( point ) {
  2817. return point.x < this.min.x || point.x > this.max.x ||
  2818. point.y < this.min.y || point.y > this.max.y ||
  2819. point.z < this.min.z || point.z > this.max.z ? false : true;
  2820. }
  2821. containsBox( box ) {
  2822. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2823. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2824. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2825. }
  2826. getParameter( point, target ) {
  2827. // This can potentially have a divide by zero if the box
  2828. // has a size dimension of 0.
  2829. return target.set(
  2830. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2831. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2832. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2833. );
  2834. }
  2835. intersectsBox( box ) {
  2836. // using 6 splitting planes to rule out intersections.
  2837. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2838. box.max.y < this.min.y || box.min.y > this.max.y ||
  2839. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2840. }
  2841. intersectsSphere( sphere ) {
  2842. // Find the point on the AABB closest to the sphere center.
  2843. this.clampPoint( sphere.center, _vector$a );
  2844. // If that point is inside the sphere, the AABB and sphere intersect.
  2845. return _vector$a.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2846. }
  2847. intersectsPlane( plane ) {
  2848. // We compute the minimum and maximum dot product values. If those values
  2849. // are on the same side (back or front) of the plane, then there is no intersection.
  2850. let min, max;
  2851. if ( plane.normal.x > 0 ) {
  2852. min = plane.normal.x * this.min.x;
  2853. max = plane.normal.x * this.max.x;
  2854. } else {
  2855. min = plane.normal.x * this.max.x;
  2856. max = plane.normal.x * this.min.x;
  2857. }
  2858. if ( plane.normal.y > 0 ) {
  2859. min += plane.normal.y * this.min.y;
  2860. max += plane.normal.y * this.max.y;
  2861. } else {
  2862. min += plane.normal.y * this.max.y;
  2863. max += plane.normal.y * this.min.y;
  2864. }
  2865. if ( plane.normal.z > 0 ) {
  2866. min += plane.normal.z * this.min.z;
  2867. max += plane.normal.z * this.max.z;
  2868. } else {
  2869. min += plane.normal.z * this.max.z;
  2870. max += plane.normal.z * this.min.z;
  2871. }
  2872. return ( min <= - plane.constant && max >= - plane.constant );
  2873. }
  2874. intersectsTriangle( triangle ) {
  2875. if ( this.isEmpty() ) {
  2876. return false;
  2877. }
  2878. // compute box center and extents
  2879. this.getCenter( _center );
  2880. _extents.subVectors( this.max, _center );
  2881. // translate triangle to aabb origin
  2882. _v0$2.subVectors( triangle.a, _center );
  2883. _v1$7.subVectors( triangle.b, _center );
  2884. _v2$4.subVectors( triangle.c, _center );
  2885. // compute edge vectors for triangle
  2886. _f0.subVectors( _v1$7, _v0$2 );
  2887. _f1.subVectors( _v2$4, _v1$7 );
  2888. _f2.subVectors( _v0$2, _v2$4 );
  2889. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2890. // 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
  2891. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2892. let axes = [
  2893. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2894. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2895. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2896. ];
  2897. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2898. return false;
  2899. }
  2900. // test 3 face normals from the aabb
  2901. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2902. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2903. return false;
  2904. }
  2905. // finally testing the face normal of the triangle
  2906. // use already existing triangle edge vectors here
  2907. _triangleNormal.crossVectors( _f0, _f1 );
  2908. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2909. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2910. }
  2911. clampPoint( point, target ) {
  2912. return target.copy( point ).clamp( this.min, this.max );
  2913. }
  2914. distanceToPoint( point ) {
  2915. return this.clampPoint( point, _vector$a ).distanceTo( point );
  2916. }
  2917. getBoundingSphere( target ) {
  2918. if ( this.isEmpty() ) {
  2919. target.makeEmpty();
  2920. } else {
  2921. this.getCenter( target.center );
  2922. target.radius = this.getSize( _vector$a ).length() * 0.5;
  2923. }
  2924. return target;
  2925. }
  2926. intersect( box ) {
  2927. this.min.max( box.min );
  2928. this.max.min( box.max );
  2929. // 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.
  2930. if ( this.isEmpty() ) this.makeEmpty();
  2931. return this;
  2932. }
  2933. union( box ) {
  2934. this.min.min( box.min );
  2935. this.max.max( box.max );
  2936. return this;
  2937. }
  2938. applyMatrix4( matrix ) {
  2939. // transform of empty box is an empty box.
  2940. if ( this.isEmpty() ) return this;
  2941. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2942. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2943. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2944. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2945. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2946. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2947. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2948. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2949. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2950. this.setFromPoints( _points );
  2951. return this;
  2952. }
  2953. translate( offset ) {
  2954. this.min.add( offset );
  2955. this.max.add( offset );
  2956. return this;
  2957. }
  2958. equals( box ) {
  2959. return box.min.equals( this.min ) && box.max.equals( this.max );
  2960. }
  2961. }
  2962. const _points = [
  2963. /*@__PURE__*/ new Vector3(),
  2964. /*@__PURE__*/ new Vector3(),
  2965. /*@__PURE__*/ new Vector3(),
  2966. /*@__PURE__*/ new Vector3(),
  2967. /*@__PURE__*/ new Vector3(),
  2968. /*@__PURE__*/ new Vector3(),
  2969. /*@__PURE__*/ new Vector3(),
  2970. /*@__PURE__*/ new Vector3()
  2971. ];
  2972. const _vector$a = /*@__PURE__*/ new Vector3();
  2973. const _box$3 = /*@__PURE__*/ new Box3();
  2974. // triangle centered vertices
  2975. const _v0$2 = /*@__PURE__*/ new Vector3();
  2976. const _v1$7 = /*@__PURE__*/ new Vector3();
  2977. const _v2$4 = /*@__PURE__*/ new Vector3();
  2978. // triangle edge vectors
  2979. const _f0 = /*@__PURE__*/ new Vector3();
  2980. const _f1 = /*@__PURE__*/ new Vector3();
  2981. const _f2 = /*@__PURE__*/ new Vector3();
  2982. const _center = /*@__PURE__*/ new Vector3();
  2983. const _extents = /*@__PURE__*/ new Vector3();
  2984. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2985. const _testAxis = /*@__PURE__*/ new Vector3();
  2986. function satForAxes( axes, v0, v1, v2, extents ) {
  2987. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2988. _testAxis.fromArray( axes, i );
  2989. // project the aabb onto the separating axis
  2990. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2991. // project all 3 vertices of the triangle onto the separating axis
  2992. const p0 = v0.dot( _testAxis );
  2993. const p1 = v1.dot( _testAxis );
  2994. const p2 = v2.dot( _testAxis );
  2995. // actual test, basically see if either of the most extreme of the triangle points intersects r
  2996. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  2997. // points of the projected triangle are outside the projected half-length of the aabb
  2998. // the axis is separating and we can exit
  2999. return false;
  3000. }
  3001. }
  3002. return true;
  3003. }
  3004. const _box$2 = /*@__PURE__*/ new Box3();
  3005. const _v1$6 = /*@__PURE__*/ new Vector3();
  3006. const _v2$3 = /*@__PURE__*/ new Vector3();
  3007. class Sphere {
  3008. constructor( center = new Vector3(), radius = - 1 ) {
  3009. this.center = center;
  3010. this.radius = radius;
  3011. }
  3012. set( center, radius ) {
  3013. this.center.copy( center );
  3014. this.radius = radius;
  3015. return this;
  3016. }
  3017. setFromPoints( points, optionalCenter ) {
  3018. const center = this.center;
  3019. if ( optionalCenter !== undefined ) {
  3020. center.copy( optionalCenter );
  3021. } else {
  3022. _box$2.setFromPoints( points ).getCenter( center );
  3023. }
  3024. let maxRadiusSq = 0;
  3025. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3026. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3027. }
  3028. this.radius = Math.sqrt( maxRadiusSq );
  3029. return this;
  3030. }
  3031. copy( sphere ) {
  3032. this.center.copy( sphere.center );
  3033. this.radius = sphere.radius;
  3034. return this;
  3035. }
  3036. isEmpty() {
  3037. return ( this.radius < 0 );
  3038. }
  3039. makeEmpty() {
  3040. this.center.set( 0, 0, 0 );
  3041. this.radius = - 1;
  3042. return this;
  3043. }
  3044. containsPoint( point ) {
  3045. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3046. }
  3047. distanceToPoint( point ) {
  3048. return ( point.distanceTo( this.center ) - this.radius );
  3049. }
  3050. intersectsSphere( sphere ) {
  3051. const radiusSum = this.radius + sphere.radius;
  3052. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3053. }
  3054. intersectsBox( box ) {
  3055. return box.intersectsSphere( this );
  3056. }
  3057. intersectsPlane( plane ) {
  3058. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3059. }
  3060. clampPoint( point, target ) {
  3061. const deltaLengthSq = this.center.distanceToSquared( point );
  3062. target.copy( point );
  3063. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3064. target.sub( this.center ).normalize();
  3065. target.multiplyScalar( this.radius ).add( this.center );
  3066. }
  3067. return target;
  3068. }
  3069. getBoundingBox( target ) {
  3070. if ( this.isEmpty() ) {
  3071. // Empty sphere produces empty bounding box
  3072. target.makeEmpty();
  3073. return target;
  3074. }
  3075. target.set( this.center, this.center );
  3076. target.expandByScalar( this.radius );
  3077. return target;
  3078. }
  3079. applyMatrix4( matrix ) {
  3080. this.center.applyMatrix4( matrix );
  3081. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3082. return this;
  3083. }
  3084. translate( offset ) {
  3085. this.center.add( offset );
  3086. return this;
  3087. }
  3088. expandByPoint( point ) {
  3089. if ( this.isEmpty() ) {
  3090. this.center.copy( point );
  3091. this.radius = 0;
  3092. return this;
  3093. }
  3094. _v1$6.subVectors( point, this.center );
  3095. const lengthSq = _v1$6.lengthSq();
  3096. if ( lengthSq > ( this.radius * this.radius ) ) {
  3097. // calculate the minimal sphere
  3098. const length = Math.sqrt( lengthSq );
  3099. const delta = ( length - this.radius ) * 0.5;
  3100. this.center.addScaledVector( _v1$6, delta / length );
  3101. this.radius += delta;
  3102. }
  3103. return this;
  3104. }
  3105. union( sphere ) {
  3106. if ( sphere.isEmpty() ) {
  3107. return this;
  3108. }
  3109. if ( this.isEmpty() ) {
  3110. this.copy( sphere );
  3111. return this;
  3112. }
  3113. if ( this.center.equals( sphere.center ) === true ) {
  3114. this.radius = Math.max( this.radius, sphere.radius );
  3115. } else {
  3116. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3117. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3118. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3119. }
  3120. return this;
  3121. }
  3122. equals( sphere ) {
  3123. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3124. }
  3125. clone() {
  3126. return new this.constructor().copy( this );
  3127. }
  3128. }
  3129. const _vector$9 = /*@__PURE__*/ new Vector3();
  3130. const _segCenter = /*@__PURE__*/ new Vector3();
  3131. const _segDir = /*@__PURE__*/ new Vector3();
  3132. const _diff = /*@__PURE__*/ new Vector3();
  3133. const _edge1 = /*@__PURE__*/ new Vector3();
  3134. const _edge2 = /*@__PURE__*/ new Vector3();
  3135. const _normal$1 = /*@__PURE__*/ new Vector3();
  3136. class Ray {
  3137. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3138. this.origin = origin;
  3139. this.direction = direction;
  3140. }
  3141. set( origin, direction ) {
  3142. this.origin.copy( origin );
  3143. this.direction.copy( direction );
  3144. return this;
  3145. }
  3146. copy( ray ) {
  3147. this.origin.copy( ray.origin );
  3148. this.direction.copy( ray.direction );
  3149. return this;
  3150. }
  3151. at( t, target ) {
  3152. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3153. }
  3154. lookAt( v ) {
  3155. this.direction.copy( v ).sub( this.origin ).normalize();
  3156. return this;
  3157. }
  3158. recast( t ) {
  3159. this.origin.copy( this.at( t, _vector$9 ) );
  3160. return this;
  3161. }
  3162. closestPointToPoint( point, target ) {
  3163. target.subVectors( point, this.origin );
  3164. const directionDistance = target.dot( this.direction );
  3165. if ( directionDistance < 0 ) {
  3166. return target.copy( this.origin );
  3167. }
  3168. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3169. }
  3170. distanceToPoint( point ) {
  3171. return Math.sqrt( this.distanceSqToPoint( point ) );
  3172. }
  3173. distanceSqToPoint( point ) {
  3174. const directionDistance = _vector$9.subVectors( point, this.origin ).dot( this.direction );
  3175. // point behind the ray
  3176. if ( directionDistance < 0 ) {
  3177. return this.origin.distanceToSquared( point );
  3178. }
  3179. _vector$9.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3180. return _vector$9.distanceToSquared( point );
  3181. }
  3182. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3183. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3184. // It returns the min distance between the ray and the segment
  3185. // defined by v0 and v1
  3186. // It can also set two optional targets :
  3187. // - The closest point on the ray
  3188. // - The closest point on the segment
  3189. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3190. _segDir.copy( v1 ).sub( v0 ).normalize();
  3191. _diff.copy( this.origin ).sub( _segCenter );
  3192. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3193. const a01 = - this.direction.dot( _segDir );
  3194. const b0 = _diff.dot( this.direction );
  3195. const b1 = - _diff.dot( _segDir );
  3196. const c = _diff.lengthSq();
  3197. const det = Math.abs( 1 - a01 * a01 );
  3198. let s0, s1, sqrDist, extDet;
  3199. if ( det > 0 ) {
  3200. // The ray and segment are not parallel.
  3201. s0 = a01 * b1 - b0;
  3202. s1 = a01 * b0 - b1;
  3203. extDet = segExtent * det;
  3204. if ( s0 >= 0 ) {
  3205. if ( s1 >= - extDet ) {
  3206. if ( s1 <= extDet ) {
  3207. // region 0
  3208. // Minimum at interior points of ray and segment.
  3209. const invDet = 1 / det;
  3210. s0 *= invDet;
  3211. s1 *= invDet;
  3212. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3213. } else {
  3214. // region 1
  3215. s1 = segExtent;
  3216. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3217. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3218. }
  3219. } else {
  3220. // region 5
  3221. s1 = - segExtent;
  3222. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3223. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3224. }
  3225. } else {
  3226. if ( s1 <= - extDet ) {
  3227. // region 4
  3228. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3229. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3230. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3231. } else if ( s1 <= extDet ) {
  3232. // region 3
  3233. s0 = 0;
  3234. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3235. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3236. } else {
  3237. // region 2
  3238. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3239. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3240. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3241. }
  3242. }
  3243. } else {
  3244. // Ray and segment are parallel.
  3245. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3246. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3247. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3248. }
  3249. if ( optionalPointOnRay ) {
  3250. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3251. }
  3252. if ( optionalPointOnSegment ) {
  3253. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3254. }
  3255. return sqrDist;
  3256. }
  3257. intersectSphere( sphere, target ) {
  3258. _vector$9.subVectors( sphere.center, this.origin );
  3259. const tca = _vector$9.dot( this.direction );
  3260. const d2 = _vector$9.dot( _vector$9 ) - tca * tca;
  3261. const radius2 = sphere.radius * sphere.radius;
  3262. if ( d2 > radius2 ) return null;
  3263. const thc = Math.sqrt( radius2 - d2 );
  3264. // t0 = first intersect point - entrance on front of sphere
  3265. const t0 = tca - thc;
  3266. // t1 = second intersect point - exit point on back of sphere
  3267. const t1 = tca + thc;
  3268. // test to see if t1 is behind the ray - if so, return null
  3269. if ( t1 < 0 ) return null;
  3270. // test to see if t0 is behind the ray:
  3271. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3272. // in order to always return an intersect point that is in front of the ray.
  3273. if ( t0 < 0 ) return this.at( t1, target );
  3274. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3275. return this.at( t0, target );
  3276. }
  3277. intersectsSphere( sphere ) {
  3278. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3279. }
  3280. distanceToPlane( plane ) {
  3281. const denominator = plane.normal.dot( this.direction );
  3282. if ( denominator === 0 ) {
  3283. // line is coplanar, return origin
  3284. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3285. return 0;
  3286. }
  3287. // Null is preferable to undefined since undefined means.... it is undefined
  3288. return null;
  3289. }
  3290. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3291. // Return if the ray never intersects the plane
  3292. return t >= 0 ? t : null;
  3293. }
  3294. intersectPlane( plane, target ) {
  3295. const t = this.distanceToPlane( plane );
  3296. if ( t === null ) {
  3297. return null;
  3298. }
  3299. return this.at( t, target );
  3300. }
  3301. intersectsPlane( plane ) {
  3302. // check if the ray lies on the plane first
  3303. const distToPoint = plane.distanceToPoint( this.origin );
  3304. if ( distToPoint === 0 ) {
  3305. return true;
  3306. }
  3307. const denominator = plane.normal.dot( this.direction );
  3308. if ( denominator * distToPoint < 0 ) {
  3309. return true;
  3310. }
  3311. // ray origin is behind the plane (and is pointing behind it)
  3312. return false;
  3313. }
  3314. intersectBox( box, target ) {
  3315. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3316. const invdirx = 1 / this.direction.x,
  3317. invdiry = 1 / this.direction.y,
  3318. invdirz = 1 / this.direction.z;
  3319. const origin = this.origin;
  3320. if ( invdirx >= 0 ) {
  3321. tmin = ( box.min.x - origin.x ) * invdirx;
  3322. tmax = ( box.max.x - origin.x ) * invdirx;
  3323. } else {
  3324. tmin = ( box.max.x - origin.x ) * invdirx;
  3325. tmax = ( box.min.x - origin.x ) * invdirx;
  3326. }
  3327. if ( invdiry >= 0 ) {
  3328. tymin = ( box.min.y - origin.y ) * invdiry;
  3329. tymax = ( box.max.y - origin.y ) * invdiry;
  3330. } else {
  3331. tymin = ( box.max.y - origin.y ) * invdiry;
  3332. tymax = ( box.min.y - origin.y ) * invdiry;
  3333. }
  3334. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3335. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3336. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3337. if ( invdirz >= 0 ) {
  3338. tzmin = ( box.min.z - origin.z ) * invdirz;
  3339. tzmax = ( box.max.z - origin.z ) * invdirz;
  3340. } else {
  3341. tzmin = ( box.max.z - origin.z ) * invdirz;
  3342. tzmax = ( box.min.z - origin.z ) * invdirz;
  3343. }
  3344. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3345. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3346. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3347. //return point closest to the ray (positive side)
  3348. if ( tmax < 0 ) return null;
  3349. return this.at( tmin >= 0 ? tmin : tmax, target );
  3350. }
  3351. intersectsBox( box ) {
  3352. return this.intersectBox( box, _vector$9 ) !== null;
  3353. }
  3354. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3355. // Compute the offset origin, edges, and normal.
  3356. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3357. _edge1.subVectors( b, a );
  3358. _edge2.subVectors( c, a );
  3359. _normal$1.crossVectors( _edge1, _edge2 );
  3360. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3361. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3362. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3363. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3364. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3365. let DdN = this.direction.dot( _normal$1 );
  3366. let sign;
  3367. if ( DdN > 0 ) {
  3368. if ( backfaceCulling ) return null;
  3369. sign = 1;
  3370. } else if ( DdN < 0 ) {
  3371. sign = - 1;
  3372. DdN = - DdN;
  3373. } else {
  3374. return null;
  3375. }
  3376. _diff.subVectors( this.origin, a );
  3377. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3378. // b1 < 0, no intersection
  3379. if ( DdQxE2 < 0 ) {
  3380. return null;
  3381. }
  3382. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3383. // b2 < 0, no intersection
  3384. if ( DdE1xQ < 0 ) {
  3385. return null;
  3386. }
  3387. // b1+b2 > 1, no intersection
  3388. if ( DdQxE2 + DdE1xQ > DdN ) {
  3389. return null;
  3390. }
  3391. // Line intersects triangle, check if ray does.
  3392. const QdN = - sign * _diff.dot( _normal$1 );
  3393. // t < 0, no intersection
  3394. if ( QdN < 0 ) {
  3395. return null;
  3396. }
  3397. // Ray intersects triangle.
  3398. return this.at( QdN / DdN, target );
  3399. }
  3400. applyMatrix4( matrix4 ) {
  3401. this.origin.applyMatrix4( matrix4 );
  3402. this.direction.transformDirection( matrix4 );
  3403. return this;
  3404. }
  3405. equals( ray ) {
  3406. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3407. }
  3408. clone() {
  3409. return new this.constructor().copy( this );
  3410. }
  3411. }
  3412. class Matrix4 {
  3413. constructor() {
  3414. Matrix4.prototype.isMatrix4 = true;
  3415. this.elements = [
  3416. 1, 0, 0, 0,
  3417. 0, 1, 0, 0,
  3418. 0, 0, 1, 0,
  3419. 0, 0, 0, 1
  3420. ];
  3421. }
  3422. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3423. const te = this.elements;
  3424. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3425. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3426. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3427. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3428. return this;
  3429. }
  3430. identity() {
  3431. this.set(
  3432. 1, 0, 0, 0,
  3433. 0, 1, 0, 0,
  3434. 0, 0, 1, 0,
  3435. 0, 0, 0, 1
  3436. );
  3437. return this;
  3438. }
  3439. clone() {
  3440. return new Matrix4().fromArray( this.elements );
  3441. }
  3442. copy( m ) {
  3443. const te = this.elements;
  3444. const me = m.elements;
  3445. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3446. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3447. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3448. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3449. return this;
  3450. }
  3451. copyPosition( m ) {
  3452. const te = this.elements, me = m.elements;
  3453. te[ 12 ] = me[ 12 ];
  3454. te[ 13 ] = me[ 13 ];
  3455. te[ 14 ] = me[ 14 ];
  3456. return this;
  3457. }
  3458. setFromMatrix3( m ) {
  3459. const me = m.elements;
  3460. this.set(
  3461. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3462. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3463. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3464. 0, 0, 0, 1
  3465. );
  3466. return this;
  3467. }
  3468. extractBasis( xAxis, yAxis, zAxis ) {
  3469. xAxis.setFromMatrixColumn( this, 0 );
  3470. yAxis.setFromMatrixColumn( this, 1 );
  3471. zAxis.setFromMatrixColumn( this, 2 );
  3472. return this;
  3473. }
  3474. makeBasis( xAxis, yAxis, zAxis ) {
  3475. this.set(
  3476. xAxis.x, yAxis.x, zAxis.x, 0,
  3477. xAxis.y, yAxis.y, zAxis.y, 0,
  3478. xAxis.z, yAxis.z, zAxis.z, 0,
  3479. 0, 0, 0, 1
  3480. );
  3481. return this;
  3482. }
  3483. extractRotation( m ) {
  3484. // this method does not support reflection matrices
  3485. const te = this.elements;
  3486. const me = m.elements;
  3487. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3488. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3489. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3490. te[ 0 ] = me[ 0 ] * scaleX;
  3491. te[ 1 ] = me[ 1 ] * scaleX;
  3492. te[ 2 ] = me[ 2 ] * scaleX;
  3493. te[ 3 ] = 0;
  3494. te[ 4 ] = me[ 4 ] * scaleY;
  3495. te[ 5 ] = me[ 5 ] * scaleY;
  3496. te[ 6 ] = me[ 6 ] * scaleY;
  3497. te[ 7 ] = 0;
  3498. te[ 8 ] = me[ 8 ] * scaleZ;
  3499. te[ 9 ] = me[ 9 ] * scaleZ;
  3500. te[ 10 ] = me[ 10 ] * scaleZ;
  3501. te[ 11 ] = 0;
  3502. te[ 12 ] = 0;
  3503. te[ 13 ] = 0;
  3504. te[ 14 ] = 0;
  3505. te[ 15 ] = 1;
  3506. return this;
  3507. }
  3508. makeRotationFromEuler( euler ) {
  3509. const te = this.elements;
  3510. const x = euler.x, y = euler.y, z = euler.z;
  3511. const a = Math.cos( x ), b = Math.sin( x );
  3512. const c = Math.cos( y ), d = Math.sin( y );
  3513. const e = Math.cos( z ), f = Math.sin( z );
  3514. if ( euler.order === 'XYZ' ) {
  3515. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3516. te[ 0 ] = c * e;
  3517. te[ 4 ] = - c * f;
  3518. te[ 8 ] = d;
  3519. te[ 1 ] = af + be * d;
  3520. te[ 5 ] = ae - bf * d;
  3521. te[ 9 ] = - b * c;
  3522. te[ 2 ] = bf - ae * d;
  3523. te[ 6 ] = be + af * d;
  3524. te[ 10 ] = a * c;
  3525. } else if ( euler.order === 'YXZ' ) {
  3526. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3527. te[ 0 ] = ce + df * b;
  3528. te[ 4 ] = de * b - cf;
  3529. te[ 8 ] = a * d;
  3530. te[ 1 ] = a * f;
  3531. te[ 5 ] = a * e;
  3532. te[ 9 ] = - b;
  3533. te[ 2 ] = cf * b - de;
  3534. te[ 6 ] = df + ce * b;
  3535. te[ 10 ] = a * c;
  3536. } else if ( euler.order === 'ZXY' ) {
  3537. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3538. te[ 0 ] = ce - df * b;
  3539. te[ 4 ] = - a * f;
  3540. te[ 8 ] = de + cf * b;
  3541. te[ 1 ] = cf + de * b;
  3542. te[ 5 ] = a * e;
  3543. te[ 9 ] = df - ce * b;
  3544. te[ 2 ] = - a * d;
  3545. te[ 6 ] = b;
  3546. te[ 10 ] = a * c;
  3547. } else if ( euler.order === 'ZYX' ) {
  3548. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3549. te[ 0 ] = c * e;
  3550. te[ 4 ] = be * d - af;
  3551. te[ 8 ] = ae * d + bf;
  3552. te[ 1 ] = c * f;
  3553. te[ 5 ] = bf * d + ae;
  3554. te[ 9 ] = af * d - be;
  3555. te[ 2 ] = - d;
  3556. te[ 6 ] = b * c;
  3557. te[ 10 ] = a * c;
  3558. } else if ( euler.order === 'YZX' ) {
  3559. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3560. te[ 0 ] = c * e;
  3561. te[ 4 ] = bd - ac * f;
  3562. te[ 8 ] = bc * f + ad;
  3563. te[ 1 ] = f;
  3564. te[ 5 ] = a * e;
  3565. te[ 9 ] = - b * e;
  3566. te[ 2 ] = - d * e;
  3567. te[ 6 ] = ad * f + bc;
  3568. te[ 10 ] = ac - bd * f;
  3569. } else if ( euler.order === 'XZY' ) {
  3570. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3571. te[ 0 ] = c * e;
  3572. te[ 4 ] = - f;
  3573. te[ 8 ] = d * e;
  3574. te[ 1 ] = ac * f + bd;
  3575. te[ 5 ] = a * e;
  3576. te[ 9 ] = ad * f - bc;
  3577. te[ 2 ] = bc * f - ad;
  3578. te[ 6 ] = b * e;
  3579. te[ 10 ] = bd * f + ac;
  3580. }
  3581. // bottom row
  3582. te[ 3 ] = 0;
  3583. te[ 7 ] = 0;
  3584. te[ 11 ] = 0;
  3585. // last column
  3586. te[ 12 ] = 0;
  3587. te[ 13 ] = 0;
  3588. te[ 14 ] = 0;
  3589. te[ 15 ] = 1;
  3590. return this;
  3591. }
  3592. makeRotationFromQuaternion( q ) {
  3593. return this.compose( _zero, q, _one );
  3594. }
  3595. lookAt( eye, target, up ) {
  3596. const te = this.elements;
  3597. _z.subVectors( eye, target );
  3598. if ( _z.lengthSq() === 0 ) {
  3599. // eye and target are in the same position
  3600. _z.z = 1;
  3601. }
  3602. _z.normalize();
  3603. _x.crossVectors( up, _z );
  3604. if ( _x.lengthSq() === 0 ) {
  3605. // up and z are parallel
  3606. if ( Math.abs( up.z ) === 1 ) {
  3607. _z.x += 0.0001;
  3608. } else {
  3609. _z.z += 0.0001;
  3610. }
  3611. _z.normalize();
  3612. _x.crossVectors( up, _z );
  3613. }
  3614. _x.normalize();
  3615. _y.crossVectors( _z, _x );
  3616. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3617. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3618. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3619. return this;
  3620. }
  3621. multiply( m ) {
  3622. return this.multiplyMatrices( this, m );
  3623. }
  3624. premultiply( m ) {
  3625. return this.multiplyMatrices( m, this );
  3626. }
  3627. multiplyMatrices( a, b ) {
  3628. const ae = a.elements;
  3629. const be = b.elements;
  3630. const te = this.elements;
  3631. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3632. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3633. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3634. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3635. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3636. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3637. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3638. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3639. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3640. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3641. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3642. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3643. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3644. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3645. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3646. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3647. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3648. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3649. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3650. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3651. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3652. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3653. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3654. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3655. return this;
  3656. }
  3657. multiplyScalar( s ) {
  3658. const te = this.elements;
  3659. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3660. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3661. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3662. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3663. return this;
  3664. }
  3665. determinant() {
  3666. const te = this.elements;
  3667. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3668. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3669. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3670. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3671. //TODO: make this more efficient
  3672. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3673. return (
  3674. n41 * (
  3675. + n14 * n23 * n32
  3676. - n13 * n24 * n32
  3677. - n14 * n22 * n33
  3678. + n12 * n24 * n33
  3679. + n13 * n22 * n34
  3680. - n12 * n23 * n34
  3681. ) +
  3682. n42 * (
  3683. + n11 * n23 * n34
  3684. - n11 * n24 * n33
  3685. + n14 * n21 * n33
  3686. - n13 * n21 * n34
  3687. + n13 * n24 * n31
  3688. - n14 * n23 * n31
  3689. ) +
  3690. n43 * (
  3691. + n11 * n24 * n32
  3692. - n11 * n22 * n34
  3693. - n14 * n21 * n32
  3694. + n12 * n21 * n34
  3695. + n14 * n22 * n31
  3696. - n12 * n24 * n31
  3697. ) +
  3698. n44 * (
  3699. - n13 * n22 * n31
  3700. - n11 * n23 * n32
  3701. + n11 * n22 * n33
  3702. + n13 * n21 * n32
  3703. - n12 * n21 * n33
  3704. + n12 * n23 * n31
  3705. )
  3706. );
  3707. }
  3708. transpose() {
  3709. const te = this.elements;
  3710. let tmp;
  3711. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3712. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3713. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3714. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3715. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3716. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3717. return this;
  3718. }
  3719. setPosition( x, y, z ) {
  3720. const te = this.elements;
  3721. if ( x.isVector3 ) {
  3722. te[ 12 ] = x.x;
  3723. te[ 13 ] = x.y;
  3724. te[ 14 ] = x.z;
  3725. } else {
  3726. te[ 12 ] = x;
  3727. te[ 13 ] = y;
  3728. te[ 14 ] = z;
  3729. }
  3730. return this;
  3731. }
  3732. invert() {
  3733. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3734. const te = this.elements,
  3735. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3736. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3737. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3738. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3739. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3740. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3741. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3742. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3743. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3744. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3745. const detInv = 1 / det;
  3746. te[ 0 ] = t11 * detInv;
  3747. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3748. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3749. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3750. te[ 4 ] = t12 * detInv;
  3751. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3752. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3753. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3754. te[ 8 ] = t13 * detInv;
  3755. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3756. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3757. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3758. te[ 12 ] = t14 * detInv;
  3759. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3760. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3761. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3762. return this;
  3763. }
  3764. scale( v ) {
  3765. const te = this.elements;
  3766. const x = v.x, y = v.y, z = v.z;
  3767. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3768. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3769. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3770. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3771. return this;
  3772. }
  3773. getMaxScaleOnAxis() {
  3774. const te = this.elements;
  3775. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3776. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3777. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3778. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3779. }
  3780. makeTranslation( x, y, z ) {
  3781. this.set(
  3782. 1, 0, 0, x,
  3783. 0, 1, 0, y,
  3784. 0, 0, 1, z,
  3785. 0, 0, 0, 1
  3786. );
  3787. return this;
  3788. }
  3789. makeRotationX( theta ) {
  3790. const c = Math.cos( theta ), s = Math.sin( theta );
  3791. this.set(
  3792. 1, 0, 0, 0,
  3793. 0, c, - s, 0,
  3794. 0, s, c, 0,
  3795. 0, 0, 0, 1
  3796. );
  3797. return this;
  3798. }
  3799. makeRotationY( theta ) {
  3800. const c = Math.cos( theta ), s = Math.sin( theta );
  3801. this.set(
  3802. c, 0, s, 0,
  3803. 0, 1, 0, 0,
  3804. - s, 0, c, 0,
  3805. 0, 0, 0, 1
  3806. );
  3807. return this;
  3808. }
  3809. makeRotationZ( theta ) {
  3810. const c = Math.cos( theta ), s = Math.sin( theta );
  3811. this.set(
  3812. c, - s, 0, 0,
  3813. s, c, 0, 0,
  3814. 0, 0, 1, 0,
  3815. 0, 0, 0, 1
  3816. );
  3817. return this;
  3818. }
  3819. makeRotationAxis( axis, angle ) {
  3820. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3821. const c = Math.cos( angle );
  3822. const s = Math.sin( angle );
  3823. const t = 1 - c;
  3824. const x = axis.x, y = axis.y, z = axis.z;
  3825. const tx = t * x, ty = t * y;
  3826. this.set(
  3827. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3828. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3829. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3830. 0, 0, 0, 1
  3831. );
  3832. return this;
  3833. }
  3834. makeScale( x, y, z ) {
  3835. this.set(
  3836. x, 0, 0, 0,
  3837. 0, y, 0, 0,
  3838. 0, 0, z, 0,
  3839. 0, 0, 0, 1
  3840. );
  3841. return this;
  3842. }
  3843. makeShear( xy, xz, yx, yz, zx, zy ) {
  3844. this.set(
  3845. 1, yx, zx, 0,
  3846. xy, 1, zy, 0,
  3847. xz, yz, 1, 0,
  3848. 0, 0, 0, 1
  3849. );
  3850. return this;
  3851. }
  3852. compose( position, quaternion, scale ) {
  3853. const te = this.elements;
  3854. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3855. const x2 = x + x, y2 = y + y, z2 = z + z;
  3856. const xx = x * x2, xy = x * y2, xz = x * z2;
  3857. const yy = y * y2, yz = y * z2, zz = z * z2;
  3858. const wx = w * x2, wy = w * y2, wz = w * z2;
  3859. const sx = scale.x, sy = scale.y, sz = scale.z;
  3860. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3861. te[ 1 ] = ( xy + wz ) * sx;
  3862. te[ 2 ] = ( xz - wy ) * sx;
  3863. te[ 3 ] = 0;
  3864. te[ 4 ] = ( xy - wz ) * sy;
  3865. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3866. te[ 6 ] = ( yz + wx ) * sy;
  3867. te[ 7 ] = 0;
  3868. te[ 8 ] = ( xz + wy ) * sz;
  3869. te[ 9 ] = ( yz - wx ) * sz;
  3870. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3871. te[ 11 ] = 0;
  3872. te[ 12 ] = position.x;
  3873. te[ 13 ] = position.y;
  3874. te[ 14 ] = position.z;
  3875. te[ 15 ] = 1;
  3876. return this;
  3877. }
  3878. decompose( position, quaternion, scale ) {
  3879. const te = this.elements;
  3880. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3881. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3882. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3883. // if determine is negative, we need to invert one scale
  3884. const det = this.determinant();
  3885. if ( det < 0 ) sx = - sx;
  3886. position.x = te[ 12 ];
  3887. position.y = te[ 13 ];
  3888. position.z = te[ 14 ];
  3889. // scale the rotation part
  3890. _m1$2.copy( this );
  3891. const invSX = 1 / sx;
  3892. const invSY = 1 / sy;
  3893. const invSZ = 1 / sz;
  3894. _m1$2.elements[ 0 ] *= invSX;
  3895. _m1$2.elements[ 1 ] *= invSX;
  3896. _m1$2.elements[ 2 ] *= invSX;
  3897. _m1$2.elements[ 4 ] *= invSY;
  3898. _m1$2.elements[ 5 ] *= invSY;
  3899. _m1$2.elements[ 6 ] *= invSY;
  3900. _m1$2.elements[ 8 ] *= invSZ;
  3901. _m1$2.elements[ 9 ] *= invSZ;
  3902. _m1$2.elements[ 10 ] *= invSZ;
  3903. quaternion.setFromRotationMatrix( _m1$2 );
  3904. scale.x = sx;
  3905. scale.y = sy;
  3906. scale.z = sz;
  3907. return this;
  3908. }
  3909. makePerspective( left, right, top, bottom, near, far ) {
  3910. const te = this.elements;
  3911. const x = 2 * near / ( right - left );
  3912. const y = 2 * near / ( top - bottom );
  3913. const a = ( right + left ) / ( right - left );
  3914. const b = ( top + bottom ) / ( top - bottom );
  3915. const c = - ( far + near ) / ( far - near );
  3916. const d = - 2 * far * near / ( far - near );
  3917. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3918. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3919. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3920. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3921. return this;
  3922. }
  3923. makeOrthographic( left, right, top, bottom, near, far ) {
  3924. const te = this.elements;
  3925. const w = 1.0 / ( right - left );
  3926. const h = 1.0 / ( top - bottom );
  3927. const p = 1.0 / ( far - near );
  3928. const x = ( right + left ) * w;
  3929. const y = ( top + bottom ) * h;
  3930. const z = ( far + near ) * p;
  3931. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3932. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3933. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3934. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3935. return this;
  3936. }
  3937. equals( matrix ) {
  3938. const te = this.elements;
  3939. const me = matrix.elements;
  3940. for ( let i = 0; i < 16; i ++ ) {
  3941. if ( te[ i ] !== me[ i ] ) return false;
  3942. }
  3943. return true;
  3944. }
  3945. fromArray( array, offset = 0 ) {
  3946. for ( let i = 0; i < 16; i ++ ) {
  3947. this.elements[ i ] = array[ i + offset ];
  3948. }
  3949. return this;
  3950. }
  3951. toArray( array = [], offset = 0 ) {
  3952. const te = this.elements;
  3953. array[ offset ] = te[ 0 ];
  3954. array[ offset + 1 ] = te[ 1 ];
  3955. array[ offset + 2 ] = te[ 2 ];
  3956. array[ offset + 3 ] = te[ 3 ];
  3957. array[ offset + 4 ] = te[ 4 ];
  3958. array[ offset + 5 ] = te[ 5 ];
  3959. array[ offset + 6 ] = te[ 6 ];
  3960. array[ offset + 7 ] = te[ 7 ];
  3961. array[ offset + 8 ] = te[ 8 ];
  3962. array[ offset + 9 ] = te[ 9 ];
  3963. array[ offset + 10 ] = te[ 10 ];
  3964. array[ offset + 11 ] = te[ 11 ];
  3965. array[ offset + 12 ] = te[ 12 ];
  3966. array[ offset + 13 ] = te[ 13 ];
  3967. array[ offset + 14 ] = te[ 14 ];
  3968. array[ offset + 15 ] = te[ 15 ];
  3969. return array;
  3970. }
  3971. }
  3972. const _v1$5 = /*@__PURE__*/ new Vector3();
  3973. const _m1$2 = /*@__PURE__*/ new Matrix4();
  3974. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3975. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3976. const _x = /*@__PURE__*/ new Vector3();
  3977. const _y = /*@__PURE__*/ new Vector3();
  3978. const _z = /*@__PURE__*/ new Vector3();
  3979. const _matrix = /*@__PURE__*/ new Matrix4();
  3980. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  3981. class Euler {
  3982. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  3983. this.isEuler = true;
  3984. this._x = x;
  3985. this._y = y;
  3986. this._z = z;
  3987. this._order = order;
  3988. }
  3989. get x() {
  3990. return this._x;
  3991. }
  3992. set x( value ) {
  3993. this._x = value;
  3994. this._onChangeCallback();
  3995. }
  3996. get y() {
  3997. return this._y;
  3998. }
  3999. set y( value ) {
  4000. this._y = value;
  4001. this._onChangeCallback();
  4002. }
  4003. get z() {
  4004. return this._z;
  4005. }
  4006. set z( value ) {
  4007. this._z = value;
  4008. this._onChangeCallback();
  4009. }
  4010. get order() {
  4011. return this._order;
  4012. }
  4013. set order( value ) {
  4014. this._order = value;
  4015. this._onChangeCallback();
  4016. }
  4017. set( x, y, z, order = this._order ) {
  4018. this._x = x;
  4019. this._y = y;
  4020. this._z = z;
  4021. this._order = order;
  4022. this._onChangeCallback();
  4023. return this;
  4024. }
  4025. clone() {
  4026. return new this.constructor( this._x, this._y, this._z, this._order );
  4027. }
  4028. copy( euler ) {
  4029. this._x = euler._x;
  4030. this._y = euler._y;
  4031. this._z = euler._z;
  4032. this._order = euler._order;
  4033. this._onChangeCallback();
  4034. return this;
  4035. }
  4036. setFromRotationMatrix( m, order = this._order, update = true ) {
  4037. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4038. const te = m.elements;
  4039. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4040. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4041. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4042. switch ( order ) {
  4043. case 'XYZ':
  4044. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4045. if ( Math.abs( m13 ) < 0.9999999 ) {
  4046. this._x = Math.atan2( - m23, m33 );
  4047. this._z = Math.atan2( - m12, m11 );
  4048. } else {
  4049. this._x = Math.atan2( m32, m22 );
  4050. this._z = 0;
  4051. }
  4052. break;
  4053. case 'YXZ':
  4054. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4055. if ( Math.abs( m23 ) < 0.9999999 ) {
  4056. this._y = Math.atan2( m13, m33 );
  4057. this._z = Math.atan2( m21, m22 );
  4058. } else {
  4059. this._y = Math.atan2( - m31, m11 );
  4060. this._z = 0;
  4061. }
  4062. break;
  4063. case 'ZXY':
  4064. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4065. if ( Math.abs( m32 ) < 0.9999999 ) {
  4066. this._y = Math.atan2( - m31, m33 );
  4067. this._z = Math.atan2( - m12, m22 );
  4068. } else {
  4069. this._y = 0;
  4070. this._z = Math.atan2( m21, m11 );
  4071. }
  4072. break;
  4073. case 'ZYX':
  4074. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4075. if ( Math.abs( m31 ) < 0.9999999 ) {
  4076. this._x = Math.atan2( m32, m33 );
  4077. this._z = Math.atan2( m21, m11 );
  4078. } else {
  4079. this._x = 0;
  4080. this._z = Math.atan2( - m12, m22 );
  4081. }
  4082. break;
  4083. case 'YZX':
  4084. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4085. if ( Math.abs( m21 ) < 0.9999999 ) {
  4086. this._x = Math.atan2( - m23, m22 );
  4087. this._y = Math.atan2( - m31, m11 );
  4088. } else {
  4089. this._x = 0;
  4090. this._y = Math.atan2( m13, m33 );
  4091. }
  4092. break;
  4093. case 'XZY':
  4094. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4095. if ( Math.abs( m12 ) < 0.9999999 ) {
  4096. this._x = Math.atan2( m32, m22 );
  4097. this._y = Math.atan2( m13, m11 );
  4098. } else {
  4099. this._x = Math.atan2( - m23, m33 );
  4100. this._y = 0;
  4101. }
  4102. break;
  4103. default:
  4104. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4105. }
  4106. this._order = order;
  4107. if ( update === true ) this._onChangeCallback();
  4108. return this;
  4109. }
  4110. setFromQuaternion( q, order, update ) {
  4111. _matrix.makeRotationFromQuaternion( q );
  4112. return this.setFromRotationMatrix( _matrix, order, update );
  4113. }
  4114. setFromVector3( v, order = this._order ) {
  4115. return this.set( v.x, v.y, v.z, order );
  4116. }
  4117. reorder( newOrder ) {
  4118. // WARNING: this discards revolution information -bhouston
  4119. _quaternion$3.setFromEuler( this );
  4120. return this.setFromQuaternion( _quaternion$3, newOrder );
  4121. }
  4122. equals( euler ) {
  4123. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4124. }
  4125. fromArray( array ) {
  4126. this._x = array[ 0 ];
  4127. this._y = array[ 1 ];
  4128. this._z = array[ 2 ];
  4129. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4130. this._onChangeCallback();
  4131. return this;
  4132. }
  4133. toArray( array = [], offset = 0 ) {
  4134. array[ offset ] = this._x;
  4135. array[ offset + 1 ] = this._y;
  4136. array[ offset + 2 ] = this._z;
  4137. array[ offset + 3 ] = this._order;
  4138. return array;
  4139. }
  4140. _onChange( callback ) {
  4141. this._onChangeCallback = callback;
  4142. return this;
  4143. }
  4144. _onChangeCallback() {}
  4145. *[ Symbol.iterator ]() {
  4146. yield this._x;
  4147. yield this._y;
  4148. yield this._z;
  4149. yield this._order;
  4150. }
  4151. }
  4152. Euler.DEFAULT_ORDER = 'XYZ';
  4153. class Layers {
  4154. constructor() {
  4155. this.mask = 1 | 0;
  4156. }
  4157. set( channel ) {
  4158. this.mask = ( 1 << channel | 0 ) >>> 0;
  4159. }
  4160. enable( channel ) {
  4161. this.mask |= 1 << channel | 0;
  4162. }
  4163. enableAll() {
  4164. this.mask = 0xffffffff | 0;
  4165. }
  4166. toggle( channel ) {
  4167. this.mask ^= 1 << channel | 0;
  4168. }
  4169. disable( channel ) {
  4170. this.mask &= ~ ( 1 << channel | 0 );
  4171. }
  4172. disableAll() {
  4173. this.mask = 0;
  4174. }
  4175. test( layers ) {
  4176. return ( this.mask & layers.mask ) !== 0;
  4177. }
  4178. isEnabled( channel ) {
  4179. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4180. }
  4181. }
  4182. let _object3DId = 0;
  4183. const _v1$4 = /*@__PURE__*/ new Vector3();
  4184. const _q1 = /*@__PURE__*/ new Quaternion();
  4185. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4186. const _target = /*@__PURE__*/ new Vector3();
  4187. const _position$3 = /*@__PURE__*/ new Vector3();
  4188. const _scale$2 = /*@__PURE__*/ new Vector3();
  4189. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4190. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4191. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4192. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4193. const _addedEvent = { type: 'added' };
  4194. const _removedEvent = { type: 'removed' };
  4195. class Object3D extends EventDispatcher {
  4196. constructor() {
  4197. super();
  4198. this.isObject3D = true;
  4199. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4200. this.uuid = generateUUID();
  4201. this.name = '';
  4202. this.type = 'Object3D';
  4203. this.parent = null;
  4204. this.children = [];
  4205. this.up = Object3D.DEFAULT_UP.clone();
  4206. const position = new Vector3();
  4207. const rotation = new Euler();
  4208. const quaternion = new Quaternion();
  4209. const scale = new Vector3( 1, 1, 1 );
  4210. function onRotationChange() {
  4211. quaternion.setFromEuler( rotation, false );
  4212. }
  4213. function onQuaternionChange() {
  4214. rotation.setFromQuaternion( quaternion, undefined, false );
  4215. }
  4216. rotation._onChange( onRotationChange );
  4217. quaternion._onChange( onQuaternionChange );
  4218. Object.defineProperties( this, {
  4219. position: {
  4220. configurable: true,
  4221. enumerable: true,
  4222. value: position
  4223. },
  4224. rotation: {
  4225. configurable: true,
  4226. enumerable: true,
  4227. value: rotation
  4228. },
  4229. quaternion: {
  4230. configurable: true,
  4231. enumerable: true,
  4232. value: quaternion
  4233. },
  4234. scale: {
  4235. configurable: true,
  4236. enumerable: true,
  4237. value: scale
  4238. },
  4239. modelViewMatrix: {
  4240. value: new Matrix4()
  4241. },
  4242. normalMatrix: {
  4243. value: new Matrix3()
  4244. }
  4245. } );
  4246. this.matrix = new Matrix4();
  4247. this.matrixWorld = new Matrix4();
  4248. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4249. this.matrixWorldNeedsUpdate = false;
  4250. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4251. this.layers = new Layers();
  4252. this.visible = true;
  4253. this.castShadow = false;
  4254. this.receiveShadow = false;
  4255. this.frustumCulled = true;
  4256. this.renderOrder = 0;
  4257. this.animations = [];
  4258. this.userData = {};
  4259. }
  4260. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4261. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4262. applyMatrix4( matrix ) {
  4263. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4264. this.matrix.premultiply( matrix );
  4265. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4266. }
  4267. applyQuaternion( q ) {
  4268. this.quaternion.premultiply( q );
  4269. return this;
  4270. }
  4271. setRotationFromAxisAngle( axis, angle ) {
  4272. // assumes axis is normalized
  4273. this.quaternion.setFromAxisAngle( axis, angle );
  4274. }
  4275. setRotationFromEuler( euler ) {
  4276. this.quaternion.setFromEuler( euler, true );
  4277. }
  4278. setRotationFromMatrix( m ) {
  4279. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4280. this.quaternion.setFromRotationMatrix( m );
  4281. }
  4282. setRotationFromQuaternion( q ) {
  4283. // assumes q is normalized
  4284. this.quaternion.copy( q );
  4285. }
  4286. rotateOnAxis( axis, angle ) {
  4287. // rotate object on axis in object space
  4288. // axis is assumed to be normalized
  4289. _q1.setFromAxisAngle( axis, angle );
  4290. this.quaternion.multiply( _q1 );
  4291. return this;
  4292. }
  4293. rotateOnWorldAxis( axis, angle ) {
  4294. // rotate object on axis in world space
  4295. // axis is assumed to be normalized
  4296. // method assumes no rotated parent
  4297. _q1.setFromAxisAngle( axis, angle );
  4298. this.quaternion.premultiply( _q1 );
  4299. return this;
  4300. }
  4301. rotateX( angle ) {
  4302. return this.rotateOnAxis( _xAxis, angle );
  4303. }
  4304. rotateY( angle ) {
  4305. return this.rotateOnAxis( _yAxis, angle );
  4306. }
  4307. rotateZ( angle ) {
  4308. return this.rotateOnAxis( _zAxis, angle );
  4309. }
  4310. translateOnAxis( axis, distance ) {
  4311. // translate object by distance along axis in object space
  4312. // axis is assumed to be normalized
  4313. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4314. this.position.add( _v1$4.multiplyScalar( distance ) );
  4315. return this;
  4316. }
  4317. translateX( distance ) {
  4318. return this.translateOnAxis( _xAxis, distance );
  4319. }
  4320. translateY( distance ) {
  4321. return this.translateOnAxis( _yAxis, distance );
  4322. }
  4323. translateZ( distance ) {
  4324. return this.translateOnAxis( _zAxis, distance );
  4325. }
  4326. localToWorld( vector ) {
  4327. this.updateWorldMatrix( true, false );
  4328. return vector.applyMatrix4( this.matrixWorld );
  4329. }
  4330. worldToLocal( vector ) {
  4331. this.updateWorldMatrix( true, false );
  4332. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4333. }
  4334. lookAt( x, y, z ) {
  4335. // This method does not support objects having non-uniformly-scaled parent(s)
  4336. if ( x.isVector3 ) {
  4337. _target.copy( x );
  4338. } else {
  4339. _target.set( x, y, z );
  4340. }
  4341. const parent = this.parent;
  4342. this.updateWorldMatrix( true, false );
  4343. _position$3.setFromMatrixPosition( this.matrixWorld );
  4344. if ( this.isCamera || this.isLight ) {
  4345. _m1$1.lookAt( _position$3, _target, this.up );
  4346. } else {
  4347. _m1$1.lookAt( _target, _position$3, this.up );
  4348. }
  4349. this.quaternion.setFromRotationMatrix( _m1$1 );
  4350. if ( parent ) {
  4351. _m1$1.extractRotation( parent.matrixWorld );
  4352. _q1.setFromRotationMatrix( _m1$1 );
  4353. this.quaternion.premultiply( _q1.invert() );
  4354. }
  4355. }
  4356. add( object ) {
  4357. if ( arguments.length > 1 ) {
  4358. for ( let i = 0; i < arguments.length; i ++ ) {
  4359. this.add( arguments[ i ] );
  4360. }
  4361. return this;
  4362. }
  4363. if ( object === this ) {
  4364. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4365. return this;
  4366. }
  4367. if ( object && object.isObject3D ) {
  4368. if ( object.parent !== null ) {
  4369. object.parent.remove( object );
  4370. }
  4371. object.parent = this;
  4372. this.children.push( object );
  4373. object.dispatchEvent( _addedEvent );
  4374. } else {
  4375. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4376. }
  4377. return this;
  4378. }
  4379. remove( object ) {
  4380. if ( arguments.length > 1 ) {
  4381. for ( let i = 0; i < arguments.length; i ++ ) {
  4382. this.remove( arguments[ i ] );
  4383. }
  4384. return this;
  4385. }
  4386. const index = this.children.indexOf( object );
  4387. if ( index !== - 1 ) {
  4388. object.parent = null;
  4389. this.children.splice( index, 1 );
  4390. object.dispatchEvent( _removedEvent );
  4391. }
  4392. return this;
  4393. }
  4394. removeFromParent() {
  4395. const parent = this.parent;
  4396. if ( parent !== null ) {
  4397. parent.remove( this );
  4398. }
  4399. return this;
  4400. }
  4401. clear() {
  4402. for ( let i = 0; i < this.children.length; i ++ ) {
  4403. const object = this.children[ i ];
  4404. object.parent = null;
  4405. object.dispatchEvent( _removedEvent );
  4406. }
  4407. this.children.length = 0;
  4408. return this;
  4409. }
  4410. attach( object ) {
  4411. // adds object as a child of this, while maintaining the object's world transform
  4412. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4413. this.updateWorldMatrix( true, false );
  4414. _m1$1.copy( this.matrixWorld ).invert();
  4415. if ( object.parent !== null ) {
  4416. object.parent.updateWorldMatrix( true, false );
  4417. _m1$1.multiply( object.parent.matrixWorld );
  4418. }
  4419. object.applyMatrix4( _m1$1 );
  4420. this.add( object );
  4421. object.updateWorldMatrix( false, true );
  4422. return this;
  4423. }
  4424. getObjectById( id ) {
  4425. return this.getObjectByProperty( 'id', id );
  4426. }
  4427. getObjectByName( name ) {
  4428. return this.getObjectByProperty( 'name', name );
  4429. }
  4430. getObjectByProperty( name, value ) {
  4431. if ( this[ name ] === value ) return this;
  4432. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4433. const child = this.children[ i ];
  4434. const object = child.getObjectByProperty( name, value );
  4435. if ( object !== undefined ) {
  4436. return object;
  4437. }
  4438. }
  4439. return undefined;
  4440. }
  4441. getObjectsByProperty( name, value ) {
  4442. let result = [];
  4443. if ( this[ name ] === value ) result.push( this );
  4444. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4445. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4446. if ( childResult.length > 0 ) {
  4447. result = result.concat( childResult );
  4448. }
  4449. }
  4450. return result;
  4451. }
  4452. getWorldPosition( target ) {
  4453. this.updateWorldMatrix( true, false );
  4454. return target.setFromMatrixPosition( this.matrixWorld );
  4455. }
  4456. getWorldQuaternion( target ) {
  4457. this.updateWorldMatrix( true, false );
  4458. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4459. return target;
  4460. }
  4461. getWorldScale( target ) {
  4462. this.updateWorldMatrix( true, false );
  4463. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4464. return target;
  4465. }
  4466. getWorldDirection( target ) {
  4467. this.updateWorldMatrix( true, false );
  4468. const e = this.matrixWorld.elements;
  4469. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4470. }
  4471. raycast( /* raycaster, intersects */ ) {}
  4472. traverse( callback ) {
  4473. callback( this );
  4474. const children = this.children;
  4475. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4476. children[ i ].traverse( callback );
  4477. }
  4478. }
  4479. traverseVisible( callback ) {
  4480. if ( this.visible === false ) return;
  4481. callback( this );
  4482. const children = this.children;
  4483. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4484. children[ i ].traverseVisible( callback );
  4485. }
  4486. }
  4487. traverseAncestors( callback ) {
  4488. const parent = this.parent;
  4489. if ( parent !== null ) {
  4490. callback( parent );
  4491. parent.traverseAncestors( callback );
  4492. }
  4493. }
  4494. updateMatrix() {
  4495. this.matrix.compose( this.position, this.quaternion, this.scale );
  4496. this.matrixWorldNeedsUpdate = true;
  4497. }
  4498. updateMatrixWorld( force ) {
  4499. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4500. if ( this.matrixWorldNeedsUpdate || force ) {
  4501. if ( this.parent === null ) {
  4502. this.matrixWorld.copy( this.matrix );
  4503. } else {
  4504. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4505. }
  4506. this.matrixWorldNeedsUpdate = false;
  4507. force = true;
  4508. }
  4509. // update children
  4510. const children = this.children;
  4511. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4512. const child = children[ i ];
  4513. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4514. child.updateMatrixWorld( force );
  4515. }
  4516. }
  4517. }
  4518. updateWorldMatrix( updateParents, updateChildren ) {
  4519. const parent = this.parent;
  4520. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4521. parent.updateWorldMatrix( true, false );
  4522. }
  4523. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4524. if ( this.parent === null ) {
  4525. this.matrixWorld.copy( this.matrix );
  4526. } else {
  4527. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4528. }
  4529. // update children
  4530. if ( updateChildren === true ) {
  4531. const children = this.children;
  4532. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4533. const child = children[ i ];
  4534. if ( child.matrixWorldAutoUpdate === true ) {
  4535. child.updateWorldMatrix( false, true );
  4536. }
  4537. }
  4538. }
  4539. }
  4540. toJSON( meta ) {
  4541. // meta is a string when called from JSON.stringify
  4542. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4543. const output = {};
  4544. // meta is a hash used to collect geometries, materials.
  4545. // not providing it implies that this is the root object
  4546. // being serialized.
  4547. if ( isRootObject ) {
  4548. // initialize meta obj
  4549. meta = {
  4550. geometries: {},
  4551. materials: {},
  4552. textures: {},
  4553. images: {},
  4554. shapes: {},
  4555. skeletons: {},
  4556. animations: {},
  4557. nodes: {}
  4558. };
  4559. output.metadata = {
  4560. version: 4.5,
  4561. type: 'Object',
  4562. generator: 'Object3D.toJSON'
  4563. };
  4564. }
  4565. // standard Object3D serialization
  4566. const object = {};
  4567. object.uuid = this.uuid;
  4568. object.type = this.type;
  4569. if ( this.name !== '' ) object.name = this.name;
  4570. if ( this.castShadow === true ) object.castShadow = true;
  4571. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4572. if ( this.visible === false ) object.visible = false;
  4573. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4574. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4575. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4576. object.layers = this.layers.mask;
  4577. object.matrix = this.matrix.toArray();
  4578. object.up = this.up.toArray();
  4579. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4580. // object specific properties
  4581. if ( this.isInstancedMesh ) {
  4582. object.type = 'InstancedMesh';
  4583. object.count = this.count;
  4584. object.instanceMatrix = this.instanceMatrix.toJSON();
  4585. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4586. }
  4587. //
  4588. function serialize( library, element ) {
  4589. if ( library[ element.uuid ] === undefined ) {
  4590. library[ element.uuid ] = element.toJSON( meta );
  4591. }
  4592. return element.uuid;
  4593. }
  4594. if ( this.isScene ) {
  4595. if ( this.background ) {
  4596. if ( this.background.isColor ) {
  4597. object.background = this.background.toJSON();
  4598. } else if ( this.background.isTexture ) {
  4599. object.background = this.background.toJSON( meta ).uuid;
  4600. }
  4601. }
  4602. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4603. object.environment = this.environment.toJSON( meta ).uuid;
  4604. }
  4605. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4606. object.geometry = serialize( meta.geometries, this.geometry );
  4607. const parameters = this.geometry.parameters;
  4608. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4609. const shapes = parameters.shapes;
  4610. if ( Array.isArray( shapes ) ) {
  4611. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4612. const shape = shapes[ i ];
  4613. serialize( meta.shapes, shape );
  4614. }
  4615. } else {
  4616. serialize( meta.shapes, shapes );
  4617. }
  4618. }
  4619. }
  4620. if ( this.isSkinnedMesh ) {
  4621. object.bindMode = this.bindMode;
  4622. object.bindMatrix = this.bindMatrix.toArray();
  4623. if ( this.skeleton !== undefined ) {
  4624. serialize( meta.skeletons, this.skeleton );
  4625. object.skeleton = this.skeleton.uuid;
  4626. }
  4627. }
  4628. if ( this.material !== undefined ) {
  4629. if ( Array.isArray( this.material ) ) {
  4630. const uuids = [];
  4631. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4632. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4633. }
  4634. object.material = uuids;
  4635. } else {
  4636. object.material = serialize( meta.materials, this.material );
  4637. }
  4638. }
  4639. //
  4640. if ( this.children.length > 0 ) {
  4641. object.children = [];
  4642. for ( let i = 0; i < this.children.length; i ++ ) {
  4643. object.children.push( this.children[ i ].toJSON( meta ).object );
  4644. }
  4645. }
  4646. //
  4647. if ( this.animations.length > 0 ) {
  4648. object.animations = [];
  4649. for ( let i = 0; i < this.animations.length; i ++ ) {
  4650. const animation = this.animations[ i ];
  4651. object.animations.push( serialize( meta.animations, animation ) );
  4652. }
  4653. }
  4654. if ( isRootObject ) {
  4655. const geometries = extractFromCache( meta.geometries );
  4656. const materials = extractFromCache( meta.materials );
  4657. const textures = extractFromCache( meta.textures );
  4658. const images = extractFromCache( meta.images );
  4659. const shapes = extractFromCache( meta.shapes );
  4660. const skeletons = extractFromCache( meta.skeletons );
  4661. const animations = extractFromCache( meta.animations );
  4662. const nodes = extractFromCache( meta.nodes );
  4663. if ( geometries.length > 0 ) output.geometries = geometries;
  4664. if ( materials.length > 0 ) output.materials = materials;
  4665. if ( textures.length > 0 ) output.textures = textures;
  4666. if ( images.length > 0 ) output.images = images;
  4667. if ( shapes.length > 0 ) output.shapes = shapes;
  4668. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4669. if ( animations.length > 0 ) output.animations = animations;
  4670. if ( nodes.length > 0 ) output.nodes = nodes;
  4671. }
  4672. output.object = object;
  4673. return output;
  4674. // extract data from the cache hash
  4675. // remove metadata on each item
  4676. // and return as array
  4677. function extractFromCache( cache ) {
  4678. const values = [];
  4679. for ( const key in cache ) {
  4680. const data = cache[ key ];
  4681. delete data.metadata;
  4682. values.push( data );
  4683. }
  4684. return values;
  4685. }
  4686. }
  4687. clone( recursive ) {
  4688. return new this.constructor().copy( this, recursive );
  4689. }
  4690. copy( source, recursive = true ) {
  4691. this.name = source.name;
  4692. this.up.copy( source.up );
  4693. this.position.copy( source.position );
  4694. this.rotation.order = source.rotation.order;
  4695. this.quaternion.copy( source.quaternion );
  4696. this.scale.copy( source.scale );
  4697. this.matrix.copy( source.matrix );
  4698. this.matrixWorld.copy( source.matrixWorld );
  4699. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4700. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4701. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4702. this.layers.mask = source.layers.mask;
  4703. this.visible = source.visible;
  4704. this.castShadow = source.castShadow;
  4705. this.receiveShadow = source.receiveShadow;
  4706. this.frustumCulled = source.frustumCulled;
  4707. this.renderOrder = source.renderOrder;
  4708. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4709. if ( recursive === true ) {
  4710. for ( let i = 0; i < source.children.length; i ++ ) {
  4711. const child = source.children[ i ];
  4712. this.add( child.clone() );
  4713. }
  4714. }
  4715. return this;
  4716. }
  4717. }
  4718. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4719. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4720. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4721. const _v0$1 = /*@__PURE__*/ new Vector3();
  4722. const _v1$3 = /*@__PURE__*/ new Vector3();
  4723. const _v2$2 = /*@__PURE__*/ new Vector3();
  4724. const _v3$1 = /*@__PURE__*/ new Vector3();
  4725. const _vab = /*@__PURE__*/ new Vector3();
  4726. const _vac = /*@__PURE__*/ new Vector3();
  4727. const _vbc = /*@__PURE__*/ new Vector3();
  4728. const _vap = /*@__PURE__*/ new Vector3();
  4729. const _vbp = /*@__PURE__*/ new Vector3();
  4730. const _vcp = /*@__PURE__*/ new Vector3();
  4731. let warnedGetUV = false;
  4732. class Triangle {
  4733. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4734. this.a = a;
  4735. this.b = b;
  4736. this.c = c;
  4737. }
  4738. static getNormal( a, b, c, target ) {
  4739. target.subVectors( c, b );
  4740. _v0$1.subVectors( a, b );
  4741. target.cross( _v0$1 );
  4742. const targetLengthSq = target.lengthSq();
  4743. if ( targetLengthSq > 0 ) {
  4744. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4745. }
  4746. return target.set( 0, 0, 0 );
  4747. }
  4748. // static/instance method to calculate barycentric coordinates
  4749. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4750. static getBarycoord( point, a, b, c, target ) {
  4751. _v0$1.subVectors( c, a );
  4752. _v1$3.subVectors( b, a );
  4753. _v2$2.subVectors( point, a );
  4754. const dot00 = _v0$1.dot( _v0$1 );
  4755. const dot01 = _v0$1.dot( _v1$3 );
  4756. const dot02 = _v0$1.dot( _v2$2 );
  4757. const dot11 = _v1$3.dot( _v1$3 );
  4758. const dot12 = _v1$3.dot( _v2$2 );
  4759. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4760. // collinear or singular triangle
  4761. if ( denom === 0 ) {
  4762. // arbitrary location outside of triangle?
  4763. // not sure if this is the best idea, maybe should be returning undefined
  4764. return target.set( - 2, - 1, - 1 );
  4765. }
  4766. const invDenom = 1 / denom;
  4767. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4768. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4769. // barycentric coordinates must always sum to 1
  4770. return target.set( 1 - u - v, v, u );
  4771. }
  4772. static containsPoint( point, a, b, c ) {
  4773. this.getBarycoord( point, a, b, c, _v3$1 );
  4774. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4775. }
  4776. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { // @deprecated, r151
  4777. if ( warnedGetUV === false ) {
  4778. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4779. warnedGetUV = true;
  4780. }
  4781. return this.getInterpolation( point, p1, p2, p3, uv1, uv2, uv3, target );
  4782. }
  4783. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4784. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4785. target.setScalar( 0 );
  4786. target.addScaledVector( v1, _v3$1.x );
  4787. target.addScaledVector( v2, _v3$1.y );
  4788. target.addScaledVector( v3, _v3$1.z );
  4789. return target;
  4790. }
  4791. static isFrontFacing( a, b, c, direction ) {
  4792. _v0$1.subVectors( c, b );
  4793. _v1$3.subVectors( a, b );
  4794. // strictly front facing
  4795. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4796. }
  4797. set( a, b, c ) {
  4798. this.a.copy( a );
  4799. this.b.copy( b );
  4800. this.c.copy( c );
  4801. return this;
  4802. }
  4803. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4804. this.a.copy( points[ i0 ] );
  4805. this.b.copy( points[ i1 ] );
  4806. this.c.copy( points[ i2 ] );
  4807. return this;
  4808. }
  4809. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4810. this.a.fromBufferAttribute( attribute, i0 );
  4811. this.b.fromBufferAttribute( attribute, i1 );
  4812. this.c.fromBufferAttribute( attribute, i2 );
  4813. return this;
  4814. }
  4815. clone() {
  4816. return new this.constructor().copy( this );
  4817. }
  4818. copy( triangle ) {
  4819. this.a.copy( triangle.a );
  4820. this.b.copy( triangle.b );
  4821. this.c.copy( triangle.c );
  4822. return this;
  4823. }
  4824. getArea() {
  4825. _v0$1.subVectors( this.c, this.b );
  4826. _v1$3.subVectors( this.a, this.b );
  4827. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4828. }
  4829. getMidpoint( target ) {
  4830. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4831. }
  4832. getNormal( target ) {
  4833. return Triangle.getNormal( this.a, this.b, this.c, target );
  4834. }
  4835. getPlane( target ) {
  4836. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4837. }
  4838. getBarycoord( point, target ) {
  4839. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4840. }
  4841. getUV( point, uv1, uv2, uv3, target ) { // @deprecated, r151
  4842. if ( warnedGetUV === false ) {
  4843. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4844. warnedGetUV = true;
  4845. }
  4846. return Triangle.getInterpolation( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4847. }
  4848. getInterpolation( point, v1, v2, v3, target ) {
  4849. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  4850. }
  4851. containsPoint( point ) {
  4852. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4853. }
  4854. isFrontFacing( direction ) {
  4855. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4856. }
  4857. intersectsBox( box ) {
  4858. return box.intersectsTriangle( this );
  4859. }
  4860. closestPointToPoint( p, target ) {
  4861. const a = this.a, b = this.b, c = this.c;
  4862. let v, w;
  4863. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4864. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4865. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4866. // basically, we're distinguishing which of the voronoi regions of the triangle
  4867. // the point lies in with the minimum amount of redundant computation.
  4868. _vab.subVectors( b, a );
  4869. _vac.subVectors( c, a );
  4870. _vap.subVectors( p, a );
  4871. const d1 = _vab.dot( _vap );
  4872. const d2 = _vac.dot( _vap );
  4873. if ( d1 <= 0 && d2 <= 0 ) {
  4874. // vertex region of A; barycentric coords (1, 0, 0)
  4875. return target.copy( a );
  4876. }
  4877. _vbp.subVectors( p, b );
  4878. const d3 = _vab.dot( _vbp );
  4879. const d4 = _vac.dot( _vbp );
  4880. if ( d3 >= 0 && d4 <= d3 ) {
  4881. // vertex region of B; barycentric coords (0, 1, 0)
  4882. return target.copy( b );
  4883. }
  4884. const vc = d1 * d4 - d3 * d2;
  4885. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4886. v = d1 / ( d1 - d3 );
  4887. // edge region of AB; barycentric coords (1-v, v, 0)
  4888. return target.copy( a ).addScaledVector( _vab, v );
  4889. }
  4890. _vcp.subVectors( p, c );
  4891. const d5 = _vab.dot( _vcp );
  4892. const d6 = _vac.dot( _vcp );
  4893. if ( d6 >= 0 && d5 <= d6 ) {
  4894. // vertex region of C; barycentric coords (0, 0, 1)
  4895. return target.copy( c );
  4896. }
  4897. const vb = d5 * d2 - d1 * d6;
  4898. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4899. w = d2 / ( d2 - d6 );
  4900. // edge region of AC; barycentric coords (1-w, 0, w)
  4901. return target.copy( a ).addScaledVector( _vac, w );
  4902. }
  4903. const va = d3 * d6 - d5 * d4;
  4904. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4905. _vbc.subVectors( c, b );
  4906. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4907. // edge region of BC; barycentric coords (0, 1-w, w)
  4908. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4909. }
  4910. // face region
  4911. const denom = 1 / ( va + vb + vc );
  4912. // u = va * denom
  4913. v = vb * denom;
  4914. w = vc * denom;
  4915. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4916. }
  4917. equals( triangle ) {
  4918. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4919. }
  4920. }
  4921. let materialId = 0;
  4922. class Material extends EventDispatcher {
  4923. constructor() {
  4924. super();
  4925. this.isMaterial = true;
  4926. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4927. this.uuid = generateUUID();
  4928. this.name = '';
  4929. this.type = 'Material';
  4930. this.blending = NormalBlending;
  4931. this.side = FrontSide;
  4932. this.vertexColors = false;
  4933. this.opacity = 1;
  4934. this.transparent = false;
  4935. this.blendSrc = SrcAlphaFactor;
  4936. this.blendDst = OneMinusSrcAlphaFactor;
  4937. this.blendEquation = AddEquation;
  4938. this.blendSrcAlpha = null;
  4939. this.blendDstAlpha = null;
  4940. this.blendEquationAlpha = null;
  4941. this.depthFunc = LessEqualDepth;
  4942. this.depthTest = true;
  4943. this.depthWrite = true;
  4944. this.stencilWriteMask = 0xff;
  4945. this.stencilFunc = AlwaysStencilFunc;
  4946. this.stencilRef = 0;
  4947. this.stencilFuncMask = 0xff;
  4948. this.stencilFail = KeepStencilOp;
  4949. this.stencilZFail = KeepStencilOp;
  4950. this.stencilZPass = KeepStencilOp;
  4951. this.stencilWrite = false;
  4952. this.clippingPlanes = null;
  4953. this.clipIntersection = false;
  4954. this.clipShadows = false;
  4955. this.shadowSide = null;
  4956. this.colorWrite = true;
  4957. this.precision = null; // override the renderer's default precision for this material
  4958. this.polygonOffset = false;
  4959. this.polygonOffsetFactor = 0;
  4960. this.polygonOffsetUnits = 0;
  4961. this.dithering = false;
  4962. this.alphaToCoverage = false;
  4963. this.premultipliedAlpha = false;
  4964. this.forceSinglePass = false;
  4965. this.visible = true;
  4966. this.toneMapped = true;
  4967. this.userData = {};
  4968. this.version = 0;
  4969. this._alphaTest = 0;
  4970. }
  4971. get alphaTest() {
  4972. return this._alphaTest;
  4973. }
  4974. set alphaTest( value ) {
  4975. if ( this._alphaTest > 0 !== value > 0 ) {
  4976. this.version ++;
  4977. }
  4978. this._alphaTest = value;
  4979. }
  4980. onBuild( /* shaderobject, renderer */ ) {}
  4981. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  4982. onBeforeCompile( /* shaderobject, renderer */ ) {}
  4983. customProgramCacheKey() {
  4984. return this.onBeforeCompile.toString();
  4985. }
  4986. setValues( values ) {
  4987. if ( values === undefined ) return;
  4988. for ( const key in values ) {
  4989. const newValue = values[ key ];
  4990. if ( newValue === undefined ) {
  4991. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  4992. continue;
  4993. }
  4994. const currentValue = this[ key ];
  4995. if ( currentValue === undefined ) {
  4996. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  4997. continue;
  4998. }
  4999. if ( currentValue && currentValue.isColor ) {
  5000. currentValue.set( newValue );
  5001. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5002. currentValue.copy( newValue );
  5003. } else {
  5004. this[ key ] = newValue;
  5005. }
  5006. }
  5007. }
  5008. toJSON( meta ) {
  5009. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5010. if ( isRootObject ) {
  5011. meta = {
  5012. textures: {},
  5013. images: {}
  5014. };
  5015. }
  5016. const data = {
  5017. metadata: {
  5018. version: 4.5,
  5019. type: 'Material',
  5020. generator: 'Material.toJSON'
  5021. }
  5022. };
  5023. // standard Material serialization
  5024. data.uuid = this.uuid;
  5025. data.type = this.type;
  5026. if ( this.name !== '' ) data.name = this.name;
  5027. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5028. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5029. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5030. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5031. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5032. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5033. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5034. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5035. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5036. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5037. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5038. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5039. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5040. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5041. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5042. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5043. }
  5044. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5045. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5046. }
  5047. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5048. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5049. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5050. }
  5051. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5052. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5053. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5054. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5055. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5056. }
  5057. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5058. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5059. }
  5060. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5061. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5062. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5063. if ( this.lightMap && this.lightMap.isTexture ) {
  5064. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5065. data.lightMapIntensity = this.lightMapIntensity;
  5066. }
  5067. if ( this.aoMap && this.aoMap.isTexture ) {
  5068. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5069. data.aoMapIntensity = this.aoMapIntensity;
  5070. }
  5071. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5072. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5073. data.bumpScale = this.bumpScale;
  5074. }
  5075. if ( this.normalMap && this.normalMap.isTexture ) {
  5076. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5077. data.normalMapType = this.normalMapType;
  5078. data.normalScale = this.normalScale.toArray();
  5079. }
  5080. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5081. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5082. data.displacementScale = this.displacementScale;
  5083. data.displacementBias = this.displacementBias;
  5084. }
  5085. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5086. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5087. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5088. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5089. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5090. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5091. if ( this.envMap && this.envMap.isTexture ) {
  5092. data.envMap = this.envMap.toJSON( meta ).uuid;
  5093. if ( this.combine !== undefined ) data.combine = this.combine;
  5094. }
  5095. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5096. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5097. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5098. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5099. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5100. }
  5101. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5102. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5103. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5104. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5105. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5106. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5107. if ( this.size !== undefined ) data.size = this.size;
  5108. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5109. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5110. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5111. if ( this.side !== FrontSide ) data.side = this.side;
  5112. if ( this.vertexColors ) data.vertexColors = true;
  5113. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5114. if ( this.transparent === true ) data.transparent = this.transparent;
  5115. data.depthFunc = this.depthFunc;
  5116. data.depthTest = this.depthTest;
  5117. data.depthWrite = this.depthWrite;
  5118. data.colorWrite = this.colorWrite;
  5119. data.stencilWrite = this.stencilWrite;
  5120. data.stencilWriteMask = this.stencilWriteMask;
  5121. data.stencilFunc = this.stencilFunc;
  5122. data.stencilRef = this.stencilRef;
  5123. data.stencilFuncMask = this.stencilFuncMask;
  5124. data.stencilFail = this.stencilFail;
  5125. data.stencilZFail = this.stencilZFail;
  5126. data.stencilZPass = this.stencilZPass;
  5127. // rotation (SpriteMaterial)
  5128. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5129. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5130. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5131. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5132. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5133. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5134. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5135. if ( this.scale !== undefined ) data.scale = this.scale;
  5136. if ( this.dithering === true ) data.dithering = true;
  5137. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5138. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5139. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5140. if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;
  5141. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5142. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5143. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5144. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5145. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5146. if ( this.visible === false ) data.visible = false;
  5147. if ( this.toneMapped === false ) data.toneMapped = false;
  5148. if ( this.fog === false ) data.fog = false;
  5149. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5150. // TODO: Copied from Object3D.toJSON
  5151. function extractFromCache( cache ) {
  5152. const values = [];
  5153. for ( const key in cache ) {
  5154. const data = cache[ key ];
  5155. delete data.metadata;
  5156. values.push( data );
  5157. }
  5158. return values;
  5159. }
  5160. if ( isRootObject ) {
  5161. const textures = extractFromCache( meta.textures );
  5162. const images = extractFromCache( meta.images );
  5163. if ( textures.length > 0 ) data.textures = textures;
  5164. if ( images.length > 0 ) data.images = images;
  5165. }
  5166. return data;
  5167. }
  5168. clone() {
  5169. return new this.constructor().copy( this );
  5170. }
  5171. copy( source ) {
  5172. this.name = source.name;
  5173. this.blending = source.blending;
  5174. this.side = source.side;
  5175. this.vertexColors = source.vertexColors;
  5176. this.opacity = source.opacity;
  5177. this.transparent = source.transparent;
  5178. this.blendSrc = source.blendSrc;
  5179. this.blendDst = source.blendDst;
  5180. this.blendEquation = source.blendEquation;
  5181. this.blendSrcAlpha = source.blendSrcAlpha;
  5182. this.blendDstAlpha = source.blendDstAlpha;
  5183. this.blendEquationAlpha = source.blendEquationAlpha;
  5184. this.depthFunc = source.depthFunc;
  5185. this.depthTest = source.depthTest;
  5186. this.depthWrite = source.depthWrite;
  5187. this.stencilWriteMask = source.stencilWriteMask;
  5188. this.stencilFunc = source.stencilFunc;
  5189. this.stencilRef = source.stencilRef;
  5190. this.stencilFuncMask = source.stencilFuncMask;
  5191. this.stencilFail = source.stencilFail;
  5192. this.stencilZFail = source.stencilZFail;
  5193. this.stencilZPass = source.stencilZPass;
  5194. this.stencilWrite = source.stencilWrite;
  5195. const srcPlanes = source.clippingPlanes;
  5196. let dstPlanes = null;
  5197. if ( srcPlanes !== null ) {
  5198. const n = srcPlanes.length;
  5199. dstPlanes = new Array( n );
  5200. for ( let i = 0; i !== n; ++ i ) {
  5201. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5202. }
  5203. }
  5204. this.clippingPlanes = dstPlanes;
  5205. this.clipIntersection = source.clipIntersection;
  5206. this.clipShadows = source.clipShadows;
  5207. this.shadowSide = source.shadowSide;
  5208. this.colorWrite = source.colorWrite;
  5209. this.precision = source.precision;
  5210. this.polygonOffset = source.polygonOffset;
  5211. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5212. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5213. this.dithering = source.dithering;
  5214. this.alphaTest = source.alphaTest;
  5215. this.alphaToCoverage = source.alphaToCoverage;
  5216. this.premultipliedAlpha = source.premultipliedAlpha;
  5217. this.forceSinglePass = source.forceSinglePass;
  5218. this.visible = source.visible;
  5219. this.toneMapped = source.toneMapped;
  5220. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5221. return this;
  5222. }
  5223. dispose() {
  5224. this.dispatchEvent( { type: 'dispose' } );
  5225. }
  5226. set needsUpdate( value ) {
  5227. if ( value === true ) this.version ++;
  5228. }
  5229. }
  5230. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5231. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5232. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5233. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5234. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5235. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5236. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5237. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5238. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5239. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5240. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5241. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5242. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5243. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5244. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5245. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5246. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5247. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5248. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5249. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5250. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5251. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5252. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5253. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5254. const _hslA = { h: 0, s: 0, l: 0 };
  5255. const _hslB = { h: 0, s: 0, l: 0 };
  5256. function hue2rgb( p, q, t ) {
  5257. if ( t < 0 ) t += 1;
  5258. if ( t > 1 ) t -= 1;
  5259. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5260. if ( t < 1 / 2 ) return q;
  5261. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5262. return p;
  5263. }
  5264. class Color {
  5265. constructor( r, g, b ) {
  5266. this.isColor = true;
  5267. this.r = 1;
  5268. this.g = 1;
  5269. this.b = 1;
  5270. if ( g === undefined && b === undefined ) {
  5271. // r is THREE.Color, hex or string
  5272. return this.set( r );
  5273. }
  5274. return this.setRGB( r, g, b );
  5275. }
  5276. set( value ) {
  5277. if ( value && value.isColor ) {
  5278. this.copy( value );
  5279. } else if ( typeof value === 'number' ) {
  5280. this.setHex( value );
  5281. } else if ( typeof value === 'string' ) {
  5282. this.setStyle( value );
  5283. }
  5284. return this;
  5285. }
  5286. setScalar( scalar ) {
  5287. this.r = scalar;
  5288. this.g = scalar;
  5289. this.b = scalar;
  5290. return this;
  5291. }
  5292. setHex( hex, colorSpace = SRGBColorSpace ) {
  5293. hex = Math.floor( hex );
  5294. this.r = ( hex >> 16 & 255 ) / 255;
  5295. this.g = ( hex >> 8 & 255 ) / 255;
  5296. this.b = ( hex & 255 ) / 255;
  5297. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5298. return this;
  5299. }
  5300. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5301. this.r = r;
  5302. this.g = g;
  5303. this.b = b;
  5304. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5305. return this;
  5306. }
  5307. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5308. // h,s,l ranges are in 0.0 - 1.0
  5309. h = euclideanModulo( h, 1 );
  5310. s = clamp( s, 0, 1 );
  5311. l = clamp( l, 0, 1 );
  5312. if ( s === 0 ) {
  5313. this.r = this.g = this.b = l;
  5314. } else {
  5315. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5316. const q = ( 2 * l ) - p;
  5317. this.r = hue2rgb( q, p, h + 1 / 3 );
  5318. this.g = hue2rgb( q, p, h );
  5319. this.b = hue2rgb( q, p, h - 1 / 3 );
  5320. }
  5321. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5322. return this;
  5323. }
  5324. setStyle( style, colorSpace = SRGBColorSpace ) {
  5325. function handleAlpha( string ) {
  5326. if ( string === undefined ) return;
  5327. if ( parseFloat( string ) < 1 ) {
  5328. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5329. }
  5330. }
  5331. let m;
  5332. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5333. // rgb / hsl
  5334. let color;
  5335. const name = m[ 1 ];
  5336. const components = m[ 2 ];
  5337. switch ( name ) {
  5338. case 'rgb':
  5339. case 'rgba':
  5340. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5341. // rgb(255,0,0) rgba(255,0,0,0.5)
  5342. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5343. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5344. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5345. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5346. handleAlpha( color[ 4 ] );
  5347. return this;
  5348. }
  5349. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5350. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5351. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5352. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5353. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5354. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5355. handleAlpha( color[ 4 ] );
  5356. return this;
  5357. }
  5358. break;
  5359. case 'hsl':
  5360. case 'hsla':
  5361. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5362. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5363. const h = parseFloat( color[ 1 ] ) / 360;
  5364. const s = parseFloat( color[ 2 ] ) / 100;
  5365. const l = parseFloat( color[ 3 ] ) / 100;
  5366. handleAlpha( color[ 4 ] );
  5367. return this.setHSL( h, s, l, colorSpace );
  5368. }
  5369. break;
  5370. default:
  5371. console.warn( 'THREE.Color: Unknown color model ' + style );
  5372. }
  5373. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5374. // hex color
  5375. const hex = m[ 1 ];
  5376. const size = hex.length;
  5377. if ( size === 3 ) {
  5378. // #ff0
  5379. return this.setRGB(
  5380. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5381. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5382. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5383. colorSpace
  5384. );
  5385. } else if ( size === 6 ) {
  5386. // #ff0000
  5387. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5388. } else {
  5389. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5390. }
  5391. } else if ( style && style.length > 0 ) {
  5392. return this.setColorName( style, colorSpace );
  5393. }
  5394. return this;
  5395. }
  5396. setColorName( style, colorSpace = SRGBColorSpace ) {
  5397. // color keywords
  5398. const hex = _colorKeywords[ style.toLowerCase() ];
  5399. if ( hex !== undefined ) {
  5400. // red
  5401. this.setHex( hex, colorSpace );
  5402. } else {
  5403. // unknown color
  5404. console.warn( 'THREE.Color: Unknown color ' + style );
  5405. }
  5406. return this;
  5407. }
  5408. clone() {
  5409. return new this.constructor( this.r, this.g, this.b );
  5410. }
  5411. copy( color ) {
  5412. this.r = color.r;
  5413. this.g = color.g;
  5414. this.b = color.b;
  5415. return this;
  5416. }
  5417. copySRGBToLinear( color ) {
  5418. this.r = SRGBToLinear( color.r );
  5419. this.g = SRGBToLinear( color.g );
  5420. this.b = SRGBToLinear( color.b );
  5421. return this;
  5422. }
  5423. copyLinearToSRGB( color ) {
  5424. this.r = LinearToSRGB( color.r );
  5425. this.g = LinearToSRGB( color.g );
  5426. this.b = LinearToSRGB( color.b );
  5427. return this;
  5428. }
  5429. convertSRGBToLinear() {
  5430. this.copySRGBToLinear( this );
  5431. return this;
  5432. }
  5433. convertLinearToSRGB() {
  5434. this.copyLinearToSRGB( this );
  5435. return this;
  5436. }
  5437. getHex( colorSpace = SRGBColorSpace ) {
  5438. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5439. return clamp( _color.r * 255, 0, 255 ) << 16 ^ clamp( _color.g * 255, 0, 255 ) << 8 ^ clamp( _color.b * 255, 0, 255 ) << 0;
  5440. }
  5441. getHexString( colorSpace = SRGBColorSpace ) {
  5442. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5443. }
  5444. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5445. // h,s,l ranges are in 0.0 - 1.0
  5446. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5447. const r = _color.r, g = _color.g, b = _color.b;
  5448. const max = Math.max( r, g, b );
  5449. const min = Math.min( r, g, b );
  5450. let hue, saturation;
  5451. const lightness = ( min + max ) / 2.0;
  5452. if ( min === max ) {
  5453. hue = 0;
  5454. saturation = 0;
  5455. } else {
  5456. const delta = max - min;
  5457. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5458. switch ( max ) {
  5459. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5460. case g: hue = ( b - r ) / delta + 2; break;
  5461. case b: hue = ( r - g ) / delta + 4; break;
  5462. }
  5463. hue /= 6;
  5464. }
  5465. target.h = hue;
  5466. target.s = saturation;
  5467. target.l = lightness;
  5468. return target;
  5469. }
  5470. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5471. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5472. target.r = _color.r;
  5473. target.g = _color.g;
  5474. target.b = _color.b;
  5475. return target;
  5476. }
  5477. getStyle( colorSpace = SRGBColorSpace ) {
  5478. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5479. const r = _color.r, g = _color.g, b = _color.b;
  5480. if ( colorSpace !== SRGBColorSpace ) {
  5481. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5482. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5483. }
  5484. return `rgb(${( r * 255 ) | 0},${( g * 255 ) | 0},${( b * 255 ) | 0})`;
  5485. }
  5486. offsetHSL( h, s, l ) {
  5487. this.getHSL( _hslA );
  5488. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5489. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5490. return this;
  5491. }
  5492. add( color ) {
  5493. this.r += color.r;
  5494. this.g += color.g;
  5495. this.b += color.b;
  5496. return this;
  5497. }
  5498. addColors( color1, color2 ) {
  5499. this.r = color1.r + color2.r;
  5500. this.g = color1.g + color2.g;
  5501. this.b = color1.b + color2.b;
  5502. return this;
  5503. }
  5504. addScalar( s ) {
  5505. this.r += s;
  5506. this.g += s;
  5507. this.b += s;
  5508. return this;
  5509. }
  5510. sub( color ) {
  5511. this.r = Math.max( 0, this.r - color.r );
  5512. this.g = Math.max( 0, this.g - color.g );
  5513. this.b = Math.max( 0, this.b - color.b );
  5514. return this;
  5515. }
  5516. multiply( color ) {
  5517. this.r *= color.r;
  5518. this.g *= color.g;
  5519. this.b *= color.b;
  5520. return this;
  5521. }
  5522. multiplyScalar( s ) {
  5523. this.r *= s;
  5524. this.g *= s;
  5525. this.b *= s;
  5526. return this;
  5527. }
  5528. lerp( color, alpha ) {
  5529. this.r += ( color.r - this.r ) * alpha;
  5530. this.g += ( color.g - this.g ) * alpha;
  5531. this.b += ( color.b - this.b ) * alpha;
  5532. return this;
  5533. }
  5534. lerpColors( color1, color2, alpha ) {
  5535. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5536. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5537. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5538. return this;
  5539. }
  5540. lerpHSL( color, alpha ) {
  5541. this.getHSL( _hslA );
  5542. color.getHSL( _hslB );
  5543. const h = lerp( _hslA.h, _hslB.h, alpha );
  5544. const s = lerp( _hslA.s, _hslB.s, alpha );
  5545. const l = lerp( _hslA.l, _hslB.l, alpha );
  5546. this.setHSL( h, s, l );
  5547. return this;
  5548. }
  5549. setFromVector3( v ) {
  5550. this.r = v.x;
  5551. this.g = v.y;
  5552. this.b = v.z;
  5553. return this;
  5554. }
  5555. applyMatrix3( m ) {
  5556. const r = this.r, g = this.g, b = this.b;
  5557. const e = m.elements;
  5558. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5559. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5560. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5561. return this;
  5562. }
  5563. equals( c ) {
  5564. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5565. }
  5566. fromArray( array, offset = 0 ) {
  5567. this.r = array[ offset ];
  5568. this.g = array[ offset + 1 ];
  5569. this.b = array[ offset + 2 ];
  5570. return this;
  5571. }
  5572. toArray( array = [], offset = 0 ) {
  5573. array[ offset ] = this.r;
  5574. array[ offset + 1 ] = this.g;
  5575. array[ offset + 2 ] = this.b;
  5576. return array;
  5577. }
  5578. fromBufferAttribute( attribute, index ) {
  5579. this.r = attribute.getX( index );
  5580. this.g = attribute.getY( index );
  5581. this.b = attribute.getZ( index );
  5582. return this;
  5583. }
  5584. toJSON() {
  5585. return this.getHex();
  5586. }
  5587. *[ Symbol.iterator ]() {
  5588. yield this.r;
  5589. yield this.g;
  5590. yield this.b;
  5591. }
  5592. }
  5593. const _color = /*@__PURE__*/ new Color();
  5594. Color.NAMES = _colorKeywords;
  5595. class MeshBasicMaterial extends Material {
  5596. constructor( parameters ) {
  5597. super();
  5598. this.isMeshBasicMaterial = true;
  5599. this.type = 'MeshBasicMaterial';
  5600. this.color = new Color( 0xffffff ); // emissive
  5601. this.map = null;
  5602. this.lightMap = null;
  5603. this.lightMapIntensity = 1.0;
  5604. this.aoMap = null;
  5605. this.aoMapIntensity = 1.0;
  5606. this.specularMap = null;
  5607. this.alphaMap = null;
  5608. this.envMap = null;
  5609. this.combine = MultiplyOperation;
  5610. this.reflectivity = 1;
  5611. this.refractionRatio = 0.98;
  5612. this.wireframe = false;
  5613. this.wireframeLinewidth = 1;
  5614. this.wireframeLinecap = 'round';
  5615. this.wireframeLinejoin = 'round';
  5616. this.fog = true;
  5617. this.setValues( parameters );
  5618. }
  5619. copy( source ) {
  5620. super.copy( source );
  5621. this.color.copy( source.color );
  5622. this.map = source.map;
  5623. this.lightMap = source.lightMap;
  5624. this.lightMapIntensity = source.lightMapIntensity;
  5625. this.aoMap = source.aoMap;
  5626. this.aoMapIntensity = source.aoMapIntensity;
  5627. this.specularMap = source.specularMap;
  5628. this.alphaMap = source.alphaMap;
  5629. this.envMap = source.envMap;
  5630. this.combine = source.combine;
  5631. this.reflectivity = source.reflectivity;
  5632. this.refractionRatio = source.refractionRatio;
  5633. this.wireframe = source.wireframe;
  5634. this.wireframeLinewidth = source.wireframeLinewidth;
  5635. this.wireframeLinecap = source.wireframeLinecap;
  5636. this.wireframeLinejoin = source.wireframeLinejoin;
  5637. this.fog = source.fog;
  5638. return this;
  5639. }
  5640. }
  5641. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5642. const _tables = /*@__PURE__*/ _generateTables();
  5643. function _generateTables() {
  5644. // float32 to float16 helpers
  5645. const buffer = new ArrayBuffer( 4 );
  5646. const floatView = new Float32Array( buffer );
  5647. const uint32View = new Uint32Array( buffer );
  5648. const baseTable = new Uint32Array( 512 );
  5649. const shiftTable = new Uint32Array( 512 );
  5650. for ( let i = 0; i < 256; ++ i ) {
  5651. const e = i - 127;
  5652. // very small number (0, -0)
  5653. if ( e < - 27 ) {
  5654. baseTable[ i ] = 0x0000;
  5655. baseTable[ i | 0x100 ] = 0x8000;
  5656. shiftTable[ i ] = 24;
  5657. shiftTable[ i | 0x100 ] = 24;
  5658. // small number (denorm)
  5659. } else if ( e < - 14 ) {
  5660. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5661. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5662. shiftTable[ i ] = - e - 1;
  5663. shiftTable[ i | 0x100 ] = - e - 1;
  5664. // normal number
  5665. } else if ( e <= 15 ) {
  5666. baseTable[ i ] = ( e + 15 ) << 10;
  5667. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5668. shiftTable[ i ] = 13;
  5669. shiftTable[ i | 0x100 ] = 13;
  5670. // large number (Infinity, -Infinity)
  5671. } else if ( e < 128 ) {
  5672. baseTable[ i ] = 0x7c00;
  5673. baseTable[ i | 0x100 ] = 0xfc00;
  5674. shiftTable[ i ] = 24;
  5675. shiftTable[ i | 0x100 ] = 24;
  5676. // stay (NaN, Infinity, -Infinity)
  5677. } else {
  5678. baseTable[ i ] = 0x7c00;
  5679. baseTable[ i | 0x100 ] = 0xfc00;
  5680. shiftTable[ i ] = 13;
  5681. shiftTable[ i | 0x100 ] = 13;
  5682. }
  5683. }
  5684. // float16 to float32 helpers
  5685. const mantissaTable = new Uint32Array( 2048 );
  5686. const exponentTable = new Uint32Array( 64 );
  5687. const offsetTable = new Uint32Array( 64 );
  5688. for ( let i = 1; i < 1024; ++ i ) {
  5689. let m = i << 13; // zero pad mantissa bits
  5690. let e = 0; // zero exponent
  5691. // normalized
  5692. while ( ( m & 0x00800000 ) === 0 ) {
  5693. m <<= 1;
  5694. e -= 0x00800000; // decrement exponent
  5695. }
  5696. m &= ~ 0x00800000; // clear leading 1 bit
  5697. e += 0x38800000; // adjust bias
  5698. mantissaTable[ i ] = m | e;
  5699. }
  5700. for ( let i = 1024; i < 2048; ++ i ) {
  5701. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5702. }
  5703. for ( let i = 1; i < 31; ++ i ) {
  5704. exponentTable[ i ] = i << 23;
  5705. }
  5706. exponentTable[ 31 ] = 0x47800000;
  5707. exponentTable[ 32 ] = 0x80000000;
  5708. for ( let i = 33; i < 63; ++ i ) {
  5709. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5710. }
  5711. exponentTable[ 63 ] = 0xc7800000;
  5712. for ( let i = 1; i < 64; ++ i ) {
  5713. if ( i !== 32 ) {
  5714. offsetTable[ i ] = 1024;
  5715. }
  5716. }
  5717. return {
  5718. floatView: floatView,
  5719. uint32View: uint32View,
  5720. baseTable: baseTable,
  5721. shiftTable: shiftTable,
  5722. mantissaTable: mantissaTable,
  5723. exponentTable: exponentTable,
  5724. offsetTable: offsetTable
  5725. };
  5726. }
  5727. // float32 to float16
  5728. function toHalfFloat( val ) {
  5729. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5730. val = clamp( val, - 65504, 65504 );
  5731. _tables.floatView[ 0 ] = val;
  5732. const f = _tables.uint32View[ 0 ];
  5733. const e = ( f >> 23 ) & 0x1ff;
  5734. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5735. }
  5736. // float16 to float32
  5737. function fromHalfFloat( val ) {
  5738. const m = val >> 10;
  5739. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5740. return _tables.floatView[ 0 ];
  5741. }
  5742. const DataUtils = {
  5743. toHalfFloat: toHalfFloat,
  5744. fromHalfFloat: fromHalfFloat,
  5745. };
  5746. const _vector$8 = /*@__PURE__*/ new Vector3();
  5747. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5748. class BufferAttribute {
  5749. constructor( array, itemSize, normalized = false ) {
  5750. if ( Array.isArray( array ) ) {
  5751. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5752. }
  5753. this.isBufferAttribute = true;
  5754. this.name = '';
  5755. this.array = array;
  5756. this.itemSize = itemSize;
  5757. this.count = array !== undefined ? array.length / itemSize : 0;
  5758. this.normalized = normalized;
  5759. this.usage = StaticDrawUsage;
  5760. this.updateRange = { offset: 0, count: - 1 };
  5761. this.version = 0;
  5762. }
  5763. onUploadCallback() {}
  5764. set needsUpdate( value ) {
  5765. if ( value === true ) this.version ++;
  5766. }
  5767. setUsage( value ) {
  5768. this.usage = value;
  5769. return this;
  5770. }
  5771. copy( source ) {
  5772. this.name = source.name;
  5773. this.array = new source.array.constructor( source.array );
  5774. this.itemSize = source.itemSize;
  5775. this.count = source.count;
  5776. this.normalized = source.normalized;
  5777. this.usage = source.usage;
  5778. return this;
  5779. }
  5780. copyAt( index1, attribute, index2 ) {
  5781. index1 *= this.itemSize;
  5782. index2 *= attribute.itemSize;
  5783. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5784. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5785. }
  5786. return this;
  5787. }
  5788. copyArray( array ) {
  5789. this.array.set( array );
  5790. return this;
  5791. }
  5792. applyMatrix3( m ) {
  5793. if ( this.itemSize === 2 ) {
  5794. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5795. _vector2$1.fromBufferAttribute( this, i );
  5796. _vector2$1.applyMatrix3( m );
  5797. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5798. }
  5799. } else if ( this.itemSize === 3 ) {
  5800. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5801. _vector$8.fromBufferAttribute( this, i );
  5802. _vector$8.applyMatrix3( m );
  5803. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5804. }
  5805. }
  5806. return this;
  5807. }
  5808. applyMatrix4( m ) {
  5809. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5810. _vector$8.fromBufferAttribute( this, i );
  5811. _vector$8.applyMatrix4( m );
  5812. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5813. }
  5814. return this;
  5815. }
  5816. applyNormalMatrix( m ) {
  5817. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5818. _vector$8.fromBufferAttribute( this, i );
  5819. _vector$8.applyNormalMatrix( m );
  5820. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5821. }
  5822. return this;
  5823. }
  5824. transformDirection( m ) {
  5825. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5826. _vector$8.fromBufferAttribute( this, i );
  5827. _vector$8.transformDirection( m );
  5828. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5829. }
  5830. return this;
  5831. }
  5832. set( value, offset = 0 ) {
  5833. // Matching BufferAttribute constructor, do not normalize the array.
  5834. this.array.set( value, offset );
  5835. return this;
  5836. }
  5837. getX( index ) {
  5838. let x = this.array[ index * this.itemSize ];
  5839. if ( this.normalized ) x = denormalize( x, this.array );
  5840. return x;
  5841. }
  5842. setX( index, x ) {
  5843. if ( this.normalized ) x = normalize( x, this.array );
  5844. this.array[ index * this.itemSize ] = x;
  5845. return this;
  5846. }
  5847. getY( index ) {
  5848. let y = this.array[ index * this.itemSize + 1 ];
  5849. if ( this.normalized ) y = denormalize( y, this.array );
  5850. return y;
  5851. }
  5852. setY( index, y ) {
  5853. if ( this.normalized ) y = normalize( y, this.array );
  5854. this.array[ index * this.itemSize + 1 ] = y;
  5855. return this;
  5856. }
  5857. getZ( index ) {
  5858. let z = this.array[ index * this.itemSize + 2 ];
  5859. if ( this.normalized ) z = denormalize( z, this.array );
  5860. return z;
  5861. }
  5862. setZ( index, z ) {
  5863. if ( this.normalized ) z = normalize( z, this.array );
  5864. this.array[ index * this.itemSize + 2 ] = z;
  5865. return this;
  5866. }
  5867. getW( index ) {
  5868. let w = this.array[ index * this.itemSize + 3 ];
  5869. if ( this.normalized ) w = denormalize( w, this.array );
  5870. return w;
  5871. }
  5872. setW( index, w ) {
  5873. if ( this.normalized ) w = normalize( w, this.array );
  5874. this.array[ index * this.itemSize + 3 ] = w;
  5875. return this;
  5876. }
  5877. setXY( index, x, y ) {
  5878. index *= this.itemSize;
  5879. if ( this.normalized ) {
  5880. x = normalize( x, this.array );
  5881. y = normalize( y, this.array );
  5882. }
  5883. this.array[ index + 0 ] = x;
  5884. this.array[ index + 1 ] = y;
  5885. return this;
  5886. }
  5887. setXYZ( index, x, y, z ) {
  5888. index *= this.itemSize;
  5889. if ( this.normalized ) {
  5890. x = normalize( x, this.array );
  5891. y = normalize( y, this.array );
  5892. z = normalize( z, this.array );
  5893. }
  5894. this.array[ index + 0 ] = x;
  5895. this.array[ index + 1 ] = y;
  5896. this.array[ index + 2 ] = z;
  5897. return this;
  5898. }
  5899. setXYZW( index, x, y, z, w ) {
  5900. index *= this.itemSize;
  5901. if ( this.normalized ) {
  5902. x = normalize( x, this.array );
  5903. y = normalize( y, this.array );
  5904. z = normalize( z, this.array );
  5905. w = normalize( w, this.array );
  5906. }
  5907. this.array[ index + 0 ] = x;
  5908. this.array[ index + 1 ] = y;
  5909. this.array[ index + 2 ] = z;
  5910. this.array[ index + 3 ] = w;
  5911. return this;
  5912. }
  5913. onUpload( callback ) {
  5914. this.onUploadCallback = callback;
  5915. return this;
  5916. }
  5917. clone() {
  5918. return new this.constructor( this.array, this.itemSize ).copy( this );
  5919. }
  5920. toJSON() {
  5921. const data = {
  5922. itemSize: this.itemSize,
  5923. type: this.array.constructor.name,
  5924. array: Array.from( this.array ),
  5925. normalized: this.normalized
  5926. };
  5927. if ( this.name !== '' ) data.name = this.name;
  5928. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5929. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5930. return data;
  5931. }
  5932. copyColorsArray() { // @deprecated, r144
  5933. console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );
  5934. }
  5935. copyVector2sArray() { // @deprecated, r144
  5936. console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );
  5937. }
  5938. copyVector3sArray() { // @deprecated, r144
  5939. console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );
  5940. }
  5941. copyVector4sArray() { // @deprecated, r144
  5942. console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );
  5943. }
  5944. }
  5945. //
  5946. class Int8BufferAttribute extends BufferAttribute {
  5947. constructor( array, itemSize, normalized ) {
  5948. super( new Int8Array( array ), itemSize, normalized );
  5949. }
  5950. }
  5951. class Uint8BufferAttribute extends BufferAttribute {
  5952. constructor( array, itemSize, normalized ) {
  5953. super( new Uint8Array( array ), itemSize, normalized );
  5954. }
  5955. }
  5956. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5957. constructor( array, itemSize, normalized ) {
  5958. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5959. }
  5960. }
  5961. class Int16BufferAttribute extends BufferAttribute {
  5962. constructor( array, itemSize, normalized ) {
  5963. super( new Int16Array( array ), itemSize, normalized );
  5964. }
  5965. }
  5966. class Uint16BufferAttribute extends BufferAttribute {
  5967. constructor( array, itemSize, normalized ) {
  5968. super( new Uint16Array( array ), itemSize, normalized );
  5969. }
  5970. }
  5971. class Int32BufferAttribute extends BufferAttribute {
  5972. constructor( array, itemSize, normalized ) {
  5973. super( new Int32Array( array ), itemSize, normalized );
  5974. }
  5975. }
  5976. class Uint32BufferAttribute extends BufferAttribute {
  5977. constructor( array, itemSize, normalized ) {
  5978. super( new Uint32Array( array ), itemSize, normalized );
  5979. }
  5980. }
  5981. class Float16BufferAttribute extends BufferAttribute {
  5982. constructor( array, itemSize, normalized ) {
  5983. super( new Uint16Array( array ), itemSize, normalized );
  5984. this.isFloat16BufferAttribute = true;
  5985. }
  5986. getX( index ) {
  5987. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  5988. if ( this.normalized ) x = denormalize( x, this.array );
  5989. return x;
  5990. }
  5991. setX( index, x ) {
  5992. if ( this.normalized ) x = normalize( x, this.array );
  5993. this.array[ index * this.itemSize ] = toHalfFloat( x );
  5994. return this;
  5995. }
  5996. getY( index ) {
  5997. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  5998. if ( this.normalized ) y = denormalize( y, this.array );
  5999. return y;
  6000. }
  6001. setY( index, y ) {
  6002. if ( this.normalized ) y = normalize( y, this.array );
  6003. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6004. return this;
  6005. }
  6006. getZ( index ) {
  6007. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6008. if ( this.normalized ) z = denormalize( z, this.array );
  6009. return z;
  6010. }
  6011. setZ( index, z ) {
  6012. if ( this.normalized ) z = normalize( z, this.array );
  6013. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6014. return this;
  6015. }
  6016. getW( index ) {
  6017. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6018. if ( this.normalized ) w = denormalize( w, this.array );
  6019. return w;
  6020. }
  6021. setW( index, w ) {
  6022. if ( this.normalized ) w = normalize( w, this.array );
  6023. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6024. return this;
  6025. }
  6026. setXY( index, x, y ) {
  6027. index *= this.itemSize;
  6028. if ( this.normalized ) {
  6029. x = normalize( x, this.array );
  6030. y = normalize( y, this.array );
  6031. }
  6032. this.array[ index + 0 ] = toHalfFloat( x );
  6033. this.array[ index + 1 ] = toHalfFloat( y );
  6034. return this;
  6035. }
  6036. setXYZ( index, x, y, z ) {
  6037. index *= this.itemSize;
  6038. if ( this.normalized ) {
  6039. x = normalize( x, this.array );
  6040. y = normalize( y, this.array );
  6041. z = normalize( z, this.array );
  6042. }
  6043. this.array[ index + 0 ] = toHalfFloat( x );
  6044. this.array[ index + 1 ] = toHalfFloat( y );
  6045. this.array[ index + 2 ] = toHalfFloat( z );
  6046. return this;
  6047. }
  6048. setXYZW( index, x, y, z, w ) {
  6049. index *= this.itemSize;
  6050. if ( this.normalized ) {
  6051. x = normalize( x, this.array );
  6052. y = normalize( y, this.array );
  6053. z = normalize( z, this.array );
  6054. w = normalize( w, this.array );
  6055. }
  6056. this.array[ index + 0 ] = toHalfFloat( x );
  6057. this.array[ index + 1 ] = toHalfFloat( y );
  6058. this.array[ index + 2 ] = toHalfFloat( z );
  6059. this.array[ index + 3 ] = toHalfFloat( w );
  6060. return this;
  6061. }
  6062. }
  6063. class Float32BufferAttribute extends BufferAttribute {
  6064. constructor( array, itemSize, normalized ) {
  6065. super( new Float32Array( array ), itemSize, normalized );
  6066. }
  6067. }
  6068. class Float64BufferAttribute extends BufferAttribute {
  6069. constructor( array, itemSize, normalized ) {
  6070. super( new Float64Array( array ), itemSize, normalized );
  6071. }
  6072. }
  6073. let _id$1 = 0;
  6074. const _m1 = /*@__PURE__*/ new Matrix4();
  6075. const _obj = /*@__PURE__*/ new Object3D();
  6076. const _offset = /*@__PURE__*/ new Vector3();
  6077. const _box$1 = /*@__PURE__*/ new Box3();
  6078. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6079. const _vector$7 = /*@__PURE__*/ new Vector3();
  6080. class BufferGeometry extends EventDispatcher {
  6081. constructor() {
  6082. super();
  6083. this.isBufferGeometry = true;
  6084. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  6085. this.uuid = generateUUID();
  6086. this.name = '';
  6087. this.type = 'BufferGeometry';
  6088. this.index = null;
  6089. this.attributes = {};
  6090. this.morphAttributes = {};
  6091. this.morphTargetsRelative = false;
  6092. this.groups = [];
  6093. this.boundingBox = null;
  6094. this.boundingSphere = null;
  6095. this.drawRange = { start: 0, count: Infinity };
  6096. this.userData = {};
  6097. }
  6098. getIndex() {
  6099. return this.index;
  6100. }
  6101. setIndex( index ) {
  6102. if ( Array.isArray( index ) ) {
  6103. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6104. } else {
  6105. this.index = index;
  6106. }
  6107. return this;
  6108. }
  6109. getAttribute( name ) {
  6110. return this.attributes[ name ];
  6111. }
  6112. setAttribute( name, attribute ) {
  6113. this.attributes[ name ] = attribute;
  6114. return this;
  6115. }
  6116. deleteAttribute( name ) {
  6117. delete this.attributes[ name ];
  6118. return this;
  6119. }
  6120. hasAttribute( name ) {
  6121. return this.attributes[ name ] !== undefined;
  6122. }
  6123. addGroup( start, count, materialIndex = 0 ) {
  6124. this.groups.push( {
  6125. start: start,
  6126. count: count,
  6127. materialIndex: materialIndex
  6128. } );
  6129. }
  6130. clearGroups() {
  6131. this.groups = [];
  6132. }
  6133. setDrawRange( start, count ) {
  6134. this.drawRange.start = start;
  6135. this.drawRange.count = count;
  6136. }
  6137. applyMatrix4( matrix ) {
  6138. const position = this.attributes.position;
  6139. if ( position !== undefined ) {
  6140. position.applyMatrix4( matrix );
  6141. position.needsUpdate = true;
  6142. }
  6143. const normal = this.attributes.normal;
  6144. if ( normal !== undefined ) {
  6145. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6146. normal.applyNormalMatrix( normalMatrix );
  6147. normal.needsUpdate = true;
  6148. }
  6149. const tangent = this.attributes.tangent;
  6150. if ( tangent !== undefined ) {
  6151. tangent.transformDirection( matrix );
  6152. tangent.needsUpdate = true;
  6153. }
  6154. if ( this.boundingBox !== null ) {
  6155. this.computeBoundingBox();
  6156. }
  6157. if ( this.boundingSphere !== null ) {
  6158. this.computeBoundingSphere();
  6159. }
  6160. return this;
  6161. }
  6162. applyQuaternion( q ) {
  6163. _m1.makeRotationFromQuaternion( q );
  6164. this.applyMatrix4( _m1 );
  6165. return this;
  6166. }
  6167. rotateX( angle ) {
  6168. // rotate geometry around world x-axis
  6169. _m1.makeRotationX( angle );
  6170. this.applyMatrix4( _m1 );
  6171. return this;
  6172. }
  6173. rotateY( angle ) {
  6174. // rotate geometry around world y-axis
  6175. _m1.makeRotationY( angle );
  6176. this.applyMatrix4( _m1 );
  6177. return this;
  6178. }
  6179. rotateZ( angle ) {
  6180. // rotate geometry around world z-axis
  6181. _m1.makeRotationZ( angle );
  6182. this.applyMatrix4( _m1 );
  6183. return this;
  6184. }
  6185. translate( x, y, z ) {
  6186. // translate geometry
  6187. _m1.makeTranslation( x, y, z );
  6188. this.applyMatrix4( _m1 );
  6189. return this;
  6190. }
  6191. scale( x, y, z ) {
  6192. // scale geometry
  6193. _m1.makeScale( x, y, z );
  6194. this.applyMatrix4( _m1 );
  6195. return this;
  6196. }
  6197. lookAt( vector ) {
  6198. _obj.lookAt( vector );
  6199. _obj.updateMatrix();
  6200. this.applyMatrix4( _obj.matrix );
  6201. return this;
  6202. }
  6203. center() {
  6204. this.computeBoundingBox();
  6205. this.boundingBox.getCenter( _offset ).negate();
  6206. this.translate( _offset.x, _offset.y, _offset.z );
  6207. return this;
  6208. }
  6209. setFromPoints( points ) {
  6210. const position = [];
  6211. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6212. const point = points[ i ];
  6213. position.push( point.x, point.y, point.z || 0 );
  6214. }
  6215. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6216. return this;
  6217. }
  6218. computeBoundingBox() {
  6219. if ( this.boundingBox === null ) {
  6220. this.boundingBox = new Box3();
  6221. }
  6222. const position = this.attributes.position;
  6223. const morphAttributesPosition = this.morphAttributes.position;
  6224. if ( position && position.isGLBufferAttribute ) {
  6225. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6226. this.boundingBox.set(
  6227. new Vector3( - Infinity, - Infinity, - Infinity ),
  6228. new Vector3( + Infinity, + Infinity, + Infinity )
  6229. );
  6230. return;
  6231. }
  6232. if ( position !== undefined ) {
  6233. this.boundingBox.setFromBufferAttribute( position );
  6234. // process morph attributes if present
  6235. if ( morphAttributesPosition ) {
  6236. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6237. const morphAttribute = morphAttributesPosition[ i ];
  6238. _box$1.setFromBufferAttribute( morphAttribute );
  6239. if ( this.morphTargetsRelative ) {
  6240. _vector$7.addVectors( this.boundingBox.min, _box$1.min );
  6241. this.boundingBox.expandByPoint( _vector$7 );
  6242. _vector$7.addVectors( this.boundingBox.max, _box$1.max );
  6243. this.boundingBox.expandByPoint( _vector$7 );
  6244. } else {
  6245. this.boundingBox.expandByPoint( _box$1.min );
  6246. this.boundingBox.expandByPoint( _box$1.max );
  6247. }
  6248. }
  6249. }
  6250. } else {
  6251. this.boundingBox.makeEmpty();
  6252. }
  6253. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6254. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6255. }
  6256. }
  6257. computeBoundingSphere() {
  6258. if ( this.boundingSphere === null ) {
  6259. this.boundingSphere = new Sphere();
  6260. }
  6261. const position = this.attributes.position;
  6262. const morphAttributesPosition = this.morphAttributes.position;
  6263. if ( position && position.isGLBufferAttribute ) {
  6264. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6265. this.boundingSphere.set( new Vector3(), Infinity );
  6266. return;
  6267. }
  6268. if ( position ) {
  6269. // first, find the center of the bounding sphere
  6270. const center = this.boundingSphere.center;
  6271. _box$1.setFromBufferAttribute( position );
  6272. // process morph attributes if present
  6273. if ( morphAttributesPosition ) {
  6274. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6275. const morphAttribute = morphAttributesPosition[ i ];
  6276. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6277. if ( this.morphTargetsRelative ) {
  6278. _vector$7.addVectors( _box$1.min, _boxMorphTargets.min );
  6279. _box$1.expandByPoint( _vector$7 );
  6280. _vector$7.addVectors( _box$1.max, _boxMorphTargets.max );
  6281. _box$1.expandByPoint( _vector$7 );
  6282. } else {
  6283. _box$1.expandByPoint( _boxMorphTargets.min );
  6284. _box$1.expandByPoint( _boxMorphTargets.max );
  6285. }
  6286. }
  6287. }
  6288. _box$1.getCenter( center );
  6289. // second, try to find a boundingSphere with a radius smaller than the
  6290. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6291. let maxRadiusSq = 0;
  6292. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6293. _vector$7.fromBufferAttribute( position, i );
  6294. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6295. }
  6296. // process morph attributes if present
  6297. if ( morphAttributesPosition ) {
  6298. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6299. const morphAttribute = morphAttributesPosition[ i ];
  6300. const morphTargetsRelative = this.morphTargetsRelative;
  6301. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6302. _vector$7.fromBufferAttribute( morphAttribute, j );
  6303. if ( morphTargetsRelative ) {
  6304. _offset.fromBufferAttribute( position, j );
  6305. _vector$7.add( _offset );
  6306. }
  6307. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6308. }
  6309. }
  6310. }
  6311. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6312. if ( isNaN( this.boundingSphere.radius ) ) {
  6313. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6314. }
  6315. }
  6316. }
  6317. computeTangents() {
  6318. const index = this.index;
  6319. const attributes = this.attributes;
  6320. // based on http://www.terathon.com/code/tangent.html
  6321. // (per vertex tangents)
  6322. if ( index === null ||
  6323. attributes.position === undefined ||
  6324. attributes.normal === undefined ||
  6325. attributes.uv === undefined ) {
  6326. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6327. return;
  6328. }
  6329. const indices = index.array;
  6330. const positions = attributes.position.array;
  6331. const normals = attributes.normal.array;
  6332. const uvs = attributes.uv.array;
  6333. const nVertices = positions.length / 3;
  6334. if ( this.hasAttribute( 'tangent' ) === false ) {
  6335. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6336. }
  6337. const tangents = this.getAttribute( 'tangent' ).array;
  6338. const tan1 = [], tan2 = [];
  6339. for ( let i = 0; i < nVertices; i ++ ) {
  6340. tan1[ i ] = new Vector3();
  6341. tan2[ i ] = new Vector3();
  6342. }
  6343. const vA = new Vector3(),
  6344. vB = new Vector3(),
  6345. vC = new Vector3(),
  6346. uvA = new Vector2(),
  6347. uvB = new Vector2(),
  6348. uvC = new Vector2(),
  6349. sdir = new Vector3(),
  6350. tdir = new Vector3();
  6351. function handleTriangle( a, b, c ) {
  6352. vA.fromArray( positions, a * 3 );
  6353. vB.fromArray( positions, b * 3 );
  6354. vC.fromArray( positions, c * 3 );
  6355. uvA.fromArray( uvs, a * 2 );
  6356. uvB.fromArray( uvs, b * 2 );
  6357. uvC.fromArray( uvs, c * 2 );
  6358. vB.sub( vA );
  6359. vC.sub( vA );
  6360. uvB.sub( uvA );
  6361. uvC.sub( uvA );
  6362. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6363. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6364. if ( ! isFinite( r ) ) return;
  6365. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6366. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6367. tan1[ a ].add( sdir );
  6368. tan1[ b ].add( sdir );
  6369. tan1[ c ].add( sdir );
  6370. tan2[ a ].add( tdir );
  6371. tan2[ b ].add( tdir );
  6372. tan2[ c ].add( tdir );
  6373. }
  6374. let groups = this.groups;
  6375. if ( groups.length === 0 ) {
  6376. groups = [ {
  6377. start: 0,
  6378. count: indices.length
  6379. } ];
  6380. }
  6381. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6382. const group = groups[ i ];
  6383. const start = group.start;
  6384. const count = group.count;
  6385. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6386. handleTriangle(
  6387. indices[ j + 0 ],
  6388. indices[ j + 1 ],
  6389. indices[ j + 2 ]
  6390. );
  6391. }
  6392. }
  6393. const tmp = new Vector3(), tmp2 = new Vector3();
  6394. const n = new Vector3(), n2 = new Vector3();
  6395. function handleVertex( v ) {
  6396. n.fromArray( normals, v * 3 );
  6397. n2.copy( n );
  6398. const t = tan1[ v ];
  6399. // Gram-Schmidt orthogonalize
  6400. tmp.copy( t );
  6401. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6402. // Calculate handedness
  6403. tmp2.crossVectors( n2, t );
  6404. const test = tmp2.dot( tan2[ v ] );
  6405. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6406. tangents[ v * 4 ] = tmp.x;
  6407. tangents[ v * 4 + 1 ] = tmp.y;
  6408. tangents[ v * 4 + 2 ] = tmp.z;
  6409. tangents[ v * 4 + 3 ] = w;
  6410. }
  6411. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6412. const group = groups[ i ];
  6413. const start = group.start;
  6414. const count = group.count;
  6415. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6416. handleVertex( indices[ j + 0 ] );
  6417. handleVertex( indices[ j + 1 ] );
  6418. handleVertex( indices[ j + 2 ] );
  6419. }
  6420. }
  6421. }
  6422. computeVertexNormals() {
  6423. const index = this.index;
  6424. const positionAttribute = this.getAttribute( 'position' );
  6425. if ( positionAttribute !== undefined ) {
  6426. let normalAttribute = this.getAttribute( 'normal' );
  6427. if ( normalAttribute === undefined ) {
  6428. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6429. this.setAttribute( 'normal', normalAttribute );
  6430. } else {
  6431. // reset existing normals to zero
  6432. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6433. normalAttribute.setXYZ( i, 0, 0, 0 );
  6434. }
  6435. }
  6436. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6437. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6438. const cb = new Vector3(), ab = new Vector3();
  6439. // indexed elements
  6440. if ( index ) {
  6441. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6442. const vA = index.getX( i + 0 );
  6443. const vB = index.getX( i + 1 );
  6444. const vC = index.getX( i + 2 );
  6445. pA.fromBufferAttribute( positionAttribute, vA );
  6446. pB.fromBufferAttribute( positionAttribute, vB );
  6447. pC.fromBufferAttribute( positionAttribute, vC );
  6448. cb.subVectors( pC, pB );
  6449. ab.subVectors( pA, pB );
  6450. cb.cross( ab );
  6451. nA.fromBufferAttribute( normalAttribute, vA );
  6452. nB.fromBufferAttribute( normalAttribute, vB );
  6453. nC.fromBufferAttribute( normalAttribute, vC );
  6454. nA.add( cb );
  6455. nB.add( cb );
  6456. nC.add( cb );
  6457. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6458. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6459. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6460. }
  6461. } else {
  6462. // non-indexed elements (unconnected triangle soup)
  6463. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6464. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6465. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6466. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6467. cb.subVectors( pC, pB );
  6468. ab.subVectors( pA, pB );
  6469. cb.cross( ab );
  6470. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6471. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6472. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6473. }
  6474. }
  6475. this.normalizeNormals();
  6476. normalAttribute.needsUpdate = true;
  6477. }
  6478. }
  6479. merge() { // @deprecated, r144
  6480. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeGeometries() instead.' );
  6481. return this;
  6482. }
  6483. normalizeNormals() {
  6484. const normals = this.attributes.normal;
  6485. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6486. _vector$7.fromBufferAttribute( normals, i );
  6487. _vector$7.normalize();
  6488. normals.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  6489. }
  6490. }
  6491. toNonIndexed() {
  6492. function convertBufferAttribute( attribute, indices ) {
  6493. const array = attribute.array;
  6494. const itemSize = attribute.itemSize;
  6495. const normalized = attribute.normalized;
  6496. const array2 = new array.constructor( indices.length * itemSize );
  6497. let index = 0, index2 = 0;
  6498. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6499. if ( attribute.isInterleavedBufferAttribute ) {
  6500. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6501. } else {
  6502. index = indices[ i ] * itemSize;
  6503. }
  6504. for ( let j = 0; j < itemSize; j ++ ) {
  6505. array2[ index2 ++ ] = array[ index ++ ];
  6506. }
  6507. }
  6508. return new BufferAttribute( array2, itemSize, normalized );
  6509. }
  6510. //
  6511. if ( this.index === null ) {
  6512. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6513. return this;
  6514. }
  6515. const geometry2 = new BufferGeometry();
  6516. const indices = this.index.array;
  6517. const attributes = this.attributes;
  6518. // attributes
  6519. for ( const name in attributes ) {
  6520. const attribute = attributes[ name ];
  6521. const newAttribute = convertBufferAttribute( attribute, indices );
  6522. geometry2.setAttribute( name, newAttribute );
  6523. }
  6524. // morph attributes
  6525. const morphAttributes = this.morphAttributes;
  6526. for ( const name in morphAttributes ) {
  6527. const morphArray = [];
  6528. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6529. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6530. const attribute = morphAttribute[ i ];
  6531. const newAttribute = convertBufferAttribute( attribute, indices );
  6532. morphArray.push( newAttribute );
  6533. }
  6534. geometry2.morphAttributes[ name ] = morphArray;
  6535. }
  6536. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6537. // groups
  6538. const groups = this.groups;
  6539. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6540. const group = groups[ i ];
  6541. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6542. }
  6543. return geometry2;
  6544. }
  6545. toJSON() {
  6546. const data = {
  6547. metadata: {
  6548. version: 4.5,
  6549. type: 'BufferGeometry',
  6550. generator: 'BufferGeometry.toJSON'
  6551. }
  6552. };
  6553. // standard BufferGeometry serialization
  6554. data.uuid = this.uuid;
  6555. data.type = this.type;
  6556. if ( this.name !== '' ) data.name = this.name;
  6557. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6558. if ( this.parameters !== undefined ) {
  6559. const parameters = this.parameters;
  6560. for ( const key in parameters ) {
  6561. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6562. }
  6563. return data;
  6564. }
  6565. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6566. data.data = { attributes: {} };
  6567. const index = this.index;
  6568. if ( index !== null ) {
  6569. data.data.index = {
  6570. type: index.array.constructor.name,
  6571. array: Array.prototype.slice.call( index.array )
  6572. };
  6573. }
  6574. const attributes = this.attributes;
  6575. for ( const key in attributes ) {
  6576. const attribute = attributes[ key ];
  6577. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6578. }
  6579. const morphAttributes = {};
  6580. let hasMorphAttributes = false;
  6581. for ( const key in this.morphAttributes ) {
  6582. const attributeArray = this.morphAttributes[ key ];
  6583. const array = [];
  6584. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6585. const attribute = attributeArray[ i ];
  6586. array.push( attribute.toJSON( data.data ) );
  6587. }
  6588. if ( array.length > 0 ) {
  6589. morphAttributes[ key ] = array;
  6590. hasMorphAttributes = true;
  6591. }
  6592. }
  6593. if ( hasMorphAttributes ) {
  6594. data.data.morphAttributes = morphAttributes;
  6595. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6596. }
  6597. const groups = this.groups;
  6598. if ( groups.length > 0 ) {
  6599. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6600. }
  6601. const boundingSphere = this.boundingSphere;
  6602. if ( boundingSphere !== null ) {
  6603. data.data.boundingSphere = {
  6604. center: boundingSphere.center.toArray(),
  6605. radius: boundingSphere.radius
  6606. };
  6607. }
  6608. return data;
  6609. }
  6610. clone() {
  6611. return new this.constructor().copy( this );
  6612. }
  6613. copy( source ) {
  6614. // reset
  6615. this.index = null;
  6616. this.attributes = {};
  6617. this.morphAttributes = {};
  6618. this.groups = [];
  6619. this.boundingBox = null;
  6620. this.boundingSphere = null;
  6621. // used for storing cloned, shared data
  6622. const data = {};
  6623. // name
  6624. this.name = source.name;
  6625. // index
  6626. const index = source.index;
  6627. if ( index !== null ) {
  6628. this.setIndex( index.clone( data ) );
  6629. }
  6630. // attributes
  6631. const attributes = source.attributes;
  6632. for ( const name in attributes ) {
  6633. const attribute = attributes[ name ];
  6634. this.setAttribute( name, attribute.clone( data ) );
  6635. }
  6636. // morph attributes
  6637. const morphAttributes = source.morphAttributes;
  6638. for ( const name in morphAttributes ) {
  6639. const array = [];
  6640. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6641. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6642. array.push( morphAttribute[ i ].clone( data ) );
  6643. }
  6644. this.morphAttributes[ name ] = array;
  6645. }
  6646. this.morphTargetsRelative = source.morphTargetsRelative;
  6647. // groups
  6648. const groups = source.groups;
  6649. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6650. const group = groups[ i ];
  6651. this.addGroup( group.start, group.count, group.materialIndex );
  6652. }
  6653. // bounding box
  6654. const boundingBox = source.boundingBox;
  6655. if ( boundingBox !== null ) {
  6656. this.boundingBox = boundingBox.clone();
  6657. }
  6658. // bounding sphere
  6659. const boundingSphere = source.boundingSphere;
  6660. if ( boundingSphere !== null ) {
  6661. this.boundingSphere = boundingSphere.clone();
  6662. }
  6663. // draw range
  6664. this.drawRange.start = source.drawRange.start;
  6665. this.drawRange.count = source.drawRange.count;
  6666. // user data
  6667. this.userData = source.userData;
  6668. return this;
  6669. }
  6670. dispose() {
  6671. this.dispatchEvent( { type: 'dispose' } );
  6672. }
  6673. }
  6674. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6675. const _ray$2 = /*@__PURE__*/ new Ray();
  6676. const _sphere$4 = /*@__PURE__*/ new Sphere();
  6677. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6678. const _vA$1 = /*@__PURE__*/ new Vector3();
  6679. const _vB$1 = /*@__PURE__*/ new Vector3();
  6680. const _vC$1 = /*@__PURE__*/ new Vector3();
  6681. const _tempA = /*@__PURE__*/ new Vector3();
  6682. const _morphA = /*@__PURE__*/ new Vector3();
  6683. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6684. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6685. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6686. const _normalA = /*@__PURE__*/ new Vector3();
  6687. const _normalB = /*@__PURE__*/ new Vector3();
  6688. const _normalC = /*@__PURE__*/ new Vector3();
  6689. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6690. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6691. class Mesh extends Object3D {
  6692. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6693. super();
  6694. this.isMesh = true;
  6695. this.type = 'Mesh';
  6696. this.geometry = geometry;
  6697. this.material = material;
  6698. this.updateMorphTargets();
  6699. }
  6700. copy( source, recursive ) {
  6701. super.copy( source, recursive );
  6702. if ( source.morphTargetInfluences !== undefined ) {
  6703. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6704. }
  6705. if ( source.morphTargetDictionary !== undefined ) {
  6706. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6707. }
  6708. this.material = source.material;
  6709. this.geometry = source.geometry;
  6710. return this;
  6711. }
  6712. updateMorphTargets() {
  6713. const geometry = this.geometry;
  6714. const morphAttributes = geometry.morphAttributes;
  6715. const keys = Object.keys( morphAttributes );
  6716. if ( keys.length > 0 ) {
  6717. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6718. if ( morphAttribute !== undefined ) {
  6719. this.morphTargetInfluences = [];
  6720. this.morphTargetDictionary = {};
  6721. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6722. const name = morphAttribute[ m ].name || String( m );
  6723. this.morphTargetInfluences.push( 0 );
  6724. this.morphTargetDictionary[ name ] = m;
  6725. }
  6726. }
  6727. }
  6728. }
  6729. getVertexPosition( index, target ) {
  6730. const geometry = this.geometry;
  6731. const position = geometry.attributes.position;
  6732. const morphPosition = geometry.morphAttributes.position;
  6733. const morphTargetsRelative = geometry.morphTargetsRelative;
  6734. target.fromBufferAttribute( position, index );
  6735. const morphInfluences = this.morphTargetInfluences;
  6736. if ( morphPosition && morphInfluences ) {
  6737. _morphA.set( 0, 0, 0 );
  6738. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6739. const influence = morphInfluences[ i ];
  6740. const morphAttribute = morphPosition[ i ];
  6741. if ( influence === 0 ) continue;
  6742. _tempA.fromBufferAttribute( morphAttribute, index );
  6743. if ( morphTargetsRelative ) {
  6744. _morphA.addScaledVector( _tempA, influence );
  6745. } else {
  6746. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6747. }
  6748. }
  6749. target.add( _morphA );
  6750. }
  6751. if ( this.isSkinnedMesh ) {
  6752. this.applyBoneTransform( index, target );
  6753. }
  6754. return target;
  6755. }
  6756. raycast( raycaster, intersects ) {
  6757. const geometry = this.geometry;
  6758. const material = this.material;
  6759. const matrixWorld = this.matrixWorld;
  6760. if ( material === undefined ) return;
  6761. // Checking boundingSphere distance to ray
  6762. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6763. _sphere$4.copy( geometry.boundingSphere );
  6764. _sphere$4.applyMatrix4( matrixWorld );
  6765. _ray$2.copy( raycaster.ray ).recast( raycaster.near );
  6766. if ( _sphere$4.containsPoint( _ray$2.origin ) === false ) {
  6767. if ( _ray$2.intersectSphere( _sphere$4, _sphereHitAt ) === null ) return;
  6768. if ( _ray$2.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6769. }
  6770. //
  6771. _inverseMatrix$2.copy( matrixWorld ).invert();
  6772. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6773. // Check boundingBox before continuing
  6774. if ( geometry.boundingBox !== null ) {
  6775. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6776. }
  6777. let intersection;
  6778. const index = geometry.index;
  6779. const position = geometry.attributes.position;
  6780. const uv = geometry.attributes.uv;
  6781. const uv2 = geometry.attributes.uv2;
  6782. const normal = geometry.attributes.normal;
  6783. const groups = geometry.groups;
  6784. const drawRange = geometry.drawRange;
  6785. if ( index !== null ) {
  6786. // indexed buffer geometry
  6787. if ( Array.isArray( material ) ) {
  6788. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6789. const group = groups[ i ];
  6790. const groupMaterial = material[ group.materialIndex ];
  6791. const start = Math.max( group.start, drawRange.start );
  6792. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6793. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6794. const a = index.getX( j );
  6795. const b = index.getX( j + 1 );
  6796. const c = index.getX( j + 2 );
  6797. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, normal, a, b, c );
  6798. if ( intersection ) {
  6799. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6800. intersection.face.materialIndex = group.materialIndex;
  6801. intersects.push( intersection );
  6802. }
  6803. }
  6804. }
  6805. } else {
  6806. const start = Math.max( 0, drawRange.start );
  6807. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6808. for ( let i = start, il = end; i < il; i += 3 ) {
  6809. const a = index.getX( i );
  6810. const b = index.getX( i + 1 );
  6811. const c = index.getX( i + 2 );
  6812. intersection = checkGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, normal, a, b, c );
  6813. if ( intersection ) {
  6814. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6815. intersects.push( intersection );
  6816. }
  6817. }
  6818. }
  6819. } else if ( position !== undefined ) {
  6820. // non-indexed buffer geometry
  6821. if ( Array.isArray( material ) ) {
  6822. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6823. const group = groups[ i ];
  6824. const groupMaterial = material[ group.materialIndex ];
  6825. const start = Math.max( group.start, drawRange.start );
  6826. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6827. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6828. const a = j;
  6829. const b = j + 1;
  6830. const c = j + 2;
  6831. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, normal, a, b, c );
  6832. if ( intersection ) {
  6833. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6834. intersection.face.materialIndex = group.materialIndex;
  6835. intersects.push( intersection );
  6836. }
  6837. }
  6838. }
  6839. } else {
  6840. const start = Math.max( 0, drawRange.start );
  6841. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6842. for ( let i = start, il = end; i < il; i += 3 ) {
  6843. const a = i;
  6844. const b = i + 1;
  6845. const c = i + 2;
  6846. intersection = checkGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, normal, a, b, c );
  6847. if ( intersection ) {
  6848. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6849. intersects.push( intersection );
  6850. }
  6851. }
  6852. }
  6853. }
  6854. }
  6855. }
  6856. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6857. let intersect;
  6858. if ( material.side === BackSide ) {
  6859. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6860. } else {
  6861. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6862. }
  6863. if ( intersect === null ) return null;
  6864. _intersectionPointWorld.copy( point );
  6865. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6866. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6867. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6868. return {
  6869. distance: distance,
  6870. point: _intersectionPointWorld.clone(),
  6871. object: object
  6872. };
  6873. }
  6874. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv2, normal, a, b, c ) {
  6875. object.getVertexPosition( a, _vA$1 );
  6876. object.getVertexPosition( b, _vB$1 );
  6877. object.getVertexPosition( c, _vC$1 );
  6878. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6879. if ( intersection ) {
  6880. if ( uv ) {
  6881. _uvA$1.fromBufferAttribute( uv, a );
  6882. _uvB$1.fromBufferAttribute( uv, b );
  6883. _uvC$1.fromBufferAttribute( uv, c );
  6884. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6885. }
  6886. if ( uv2 ) {
  6887. _uvA$1.fromBufferAttribute( uv2, a );
  6888. _uvB$1.fromBufferAttribute( uv2, b );
  6889. _uvC$1.fromBufferAttribute( uv2, c );
  6890. intersection.uv2 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6891. }
  6892. if ( normal ) {
  6893. _normalA.fromBufferAttribute( normal, a );
  6894. _normalB.fromBufferAttribute( normal, b );
  6895. _normalC.fromBufferAttribute( normal, c );
  6896. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  6897. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  6898. intersection.normal.multiplyScalar( - 1 );
  6899. }
  6900. }
  6901. const face = {
  6902. a: a,
  6903. b: b,
  6904. c: c,
  6905. normal: new Vector3(),
  6906. materialIndex: 0
  6907. };
  6908. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6909. intersection.face = face;
  6910. }
  6911. return intersection;
  6912. }
  6913. class BoxGeometry extends BufferGeometry {
  6914. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6915. super();
  6916. this.type = 'BoxGeometry';
  6917. this.parameters = {
  6918. width: width,
  6919. height: height,
  6920. depth: depth,
  6921. widthSegments: widthSegments,
  6922. heightSegments: heightSegments,
  6923. depthSegments: depthSegments
  6924. };
  6925. const scope = this;
  6926. // segments
  6927. widthSegments = Math.floor( widthSegments );
  6928. heightSegments = Math.floor( heightSegments );
  6929. depthSegments = Math.floor( depthSegments );
  6930. // buffers
  6931. const indices = [];
  6932. const vertices = [];
  6933. const normals = [];
  6934. const uvs = [];
  6935. // helper variables
  6936. let numberOfVertices = 0;
  6937. let groupStart = 0;
  6938. // build each side of the box geometry
  6939. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6940. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6941. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6942. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6943. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6944. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6945. // build geometry
  6946. this.setIndex( indices );
  6947. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6948. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6949. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6950. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6951. const segmentWidth = width / gridX;
  6952. const segmentHeight = height / gridY;
  6953. const widthHalf = width / 2;
  6954. const heightHalf = height / 2;
  6955. const depthHalf = depth / 2;
  6956. const gridX1 = gridX + 1;
  6957. const gridY1 = gridY + 1;
  6958. let vertexCounter = 0;
  6959. let groupCount = 0;
  6960. const vector = new Vector3();
  6961. // generate vertices, normals and uvs
  6962. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6963. const y = iy * segmentHeight - heightHalf;
  6964. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6965. const x = ix * segmentWidth - widthHalf;
  6966. // set values to correct vector component
  6967. vector[ u ] = x * udir;
  6968. vector[ v ] = y * vdir;
  6969. vector[ w ] = depthHalf;
  6970. // now apply vector to vertex buffer
  6971. vertices.push( vector.x, vector.y, vector.z );
  6972. // set values to correct vector component
  6973. vector[ u ] = 0;
  6974. vector[ v ] = 0;
  6975. vector[ w ] = depth > 0 ? 1 : - 1;
  6976. // now apply vector to normal buffer
  6977. normals.push( vector.x, vector.y, vector.z );
  6978. // uvs
  6979. uvs.push( ix / gridX );
  6980. uvs.push( 1 - ( iy / gridY ) );
  6981. // counters
  6982. vertexCounter += 1;
  6983. }
  6984. }
  6985. // indices
  6986. // 1. you need three indices to draw a single face
  6987. // 2. a single segment consists of two faces
  6988. // 3. so we need to generate six (2*3) indices per segment
  6989. for ( let iy = 0; iy < gridY; iy ++ ) {
  6990. for ( let ix = 0; ix < gridX; ix ++ ) {
  6991. const a = numberOfVertices + ix + gridX1 * iy;
  6992. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6993. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6994. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6995. // faces
  6996. indices.push( a, b, d );
  6997. indices.push( b, c, d );
  6998. // increase counter
  6999. groupCount += 6;
  7000. }
  7001. }
  7002. // add a group to the geometry. this will ensure multi material support
  7003. scope.addGroup( groupStart, groupCount, materialIndex );
  7004. // calculate new start value for groups
  7005. groupStart += groupCount;
  7006. // update total number of vertices
  7007. numberOfVertices += vertexCounter;
  7008. }
  7009. }
  7010. copy( source ) {
  7011. super.copy( source );
  7012. this.parameters = Object.assign( {}, source.parameters );
  7013. return this;
  7014. }
  7015. static fromJSON( data ) {
  7016. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7017. }
  7018. }
  7019. /**
  7020. * Uniform Utilities
  7021. */
  7022. function cloneUniforms( src ) {
  7023. const dst = {};
  7024. for ( const u in src ) {
  7025. dst[ u ] = {};
  7026. for ( const p in src[ u ] ) {
  7027. const property = src[ u ][ p ];
  7028. if ( property && ( property.isColor ||
  7029. property.isMatrix3 || property.isMatrix4 ||
  7030. property.isVector2 || property.isVector3 || property.isVector4 ||
  7031. property.isTexture || property.isQuaternion ) ) {
  7032. if ( property.isRenderTargetTexture ) {
  7033. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7034. dst[ u ][ p ] = null;
  7035. } else {
  7036. dst[ u ][ p ] = property.clone();
  7037. }
  7038. } else if ( Array.isArray( property ) ) {
  7039. dst[ u ][ p ] = property.slice();
  7040. } else {
  7041. dst[ u ][ p ] = property;
  7042. }
  7043. }
  7044. }
  7045. return dst;
  7046. }
  7047. function mergeUniforms( uniforms ) {
  7048. const merged = {};
  7049. for ( let u = 0; u < uniforms.length; u ++ ) {
  7050. const tmp = cloneUniforms( uniforms[ u ] );
  7051. for ( const p in tmp ) {
  7052. merged[ p ] = tmp[ p ];
  7053. }
  7054. }
  7055. return merged;
  7056. }
  7057. function cloneUniformsGroups( src ) {
  7058. const dst = [];
  7059. for ( let u = 0; u < src.length; u ++ ) {
  7060. dst.push( src[ u ].clone() );
  7061. }
  7062. return dst;
  7063. }
  7064. function getUnlitUniformColorSpace( renderer ) {
  7065. if ( renderer.getRenderTarget() === null ) {
  7066. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7067. return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  7068. }
  7069. return LinearSRGBColorSpace;
  7070. }
  7071. // Legacy
  7072. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7073. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7074. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7075. class ShaderMaterial extends Material {
  7076. constructor( parameters ) {
  7077. super();
  7078. this.isShaderMaterial = true;
  7079. this.type = 'ShaderMaterial';
  7080. this.defines = {};
  7081. this.uniforms = {};
  7082. this.uniformsGroups = [];
  7083. this.vertexShader = default_vertex;
  7084. this.fragmentShader = default_fragment;
  7085. this.linewidth = 1;
  7086. this.wireframe = false;
  7087. this.wireframeLinewidth = 1;
  7088. this.fog = false; // set to use scene fog
  7089. this.lights = false; // set to use scene lights
  7090. this.clipping = false; // set to use user-defined clipping planes
  7091. this.forceSinglePass = true;
  7092. this.extensions = {
  7093. derivatives: false, // set to use derivatives
  7094. fragDepth: false, // set to use fragment depth values
  7095. drawBuffers: false, // set to use draw buffers
  7096. shaderTextureLOD: false // set to use shader texture LOD
  7097. };
  7098. // When rendered geometry doesn't include these attributes but the material does,
  7099. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7100. this.defaultAttributeValues = {
  7101. 'color': [ 1, 1, 1 ],
  7102. 'uv': [ 0, 0 ],
  7103. 'uv2': [ 0, 0 ]
  7104. };
  7105. this.index0AttributeName = undefined;
  7106. this.uniformsNeedUpdate = false;
  7107. this.glslVersion = null;
  7108. if ( parameters !== undefined ) {
  7109. this.setValues( parameters );
  7110. }
  7111. }
  7112. copy( source ) {
  7113. super.copy( source );
  7114. this.fragmentShader = source.fragmentShader;
  7115. this.vertexShader = source.vertexShader;
  7116. this.uniforms = cloneUniforms( source.uniforms );
  7117. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7118. this.defines = Object.assign( {}, source.defines );
  7119. this.wireframe = source.wireframe;
  7120. this.wireframeLinewidth = source.wireframeLinewidth;
  7121. this.fog = source.fog;
  7122. this.lights = source.lights;
  7123. this.clipping = source.clipping;
  7124. this.extensions = Object.assign( {}, source.extensions );
  7125. this.glslVersion = source.glslVersion;
  7126. return this;
  7127. }
  7128. toJSON( meta ) {
  7129. const data = super.toJSON( meta );
  7130. data.glslVersion = this.glslVersion;
  7131. data.uniforms = {};
  7132. for ( const name in this.uniforms ) {
  7133. const uniform = this.uniforms[ name ];
  7134. const value = uniform.value;
  7135. if ( value && value.isTexture ) {
  7136. data.uniforms[ name ] = {
  7137. type: 't',
  7138. value: value.toJSON( meta ).uuid
  7139. };
  7140. } else if ( value && value.isColor ) {
  7141. data.uniforms[ name ] = {
  7142. type: 'c',
  7143. value: value.getHex()
  7144. };
  7145. } else if ( value && value.isVector2 ) {
  7146. data.uniforms[ name ] = {
  7147. type: 'v2',
  7148. value: value.toArray()
  7149. };
  7150. } else if ( value && value.isVector3 ) {
  7151. data.uniforms[ name ] = {
  7152. type: 'v3',
  7153. value: value.toArray()
  7154. };
  7155. } else if ( value && value.isVector4 ) {
  7156. data.uniforms[ name ] = {
  7157. type: 'v4',
  7158. value: value.toArray()
  7159. };
  7160. } else if ( value && value.isMatrix3 ) {
  7161. data.uniforms[ name ] = {
  7162. type: 'm3',
  7163. value: value.toArray()
  7164. };
  7165. } else if ( value && value.isMatrix4 ) {
  7166. data.uniforms[ name ] = {
  7167. type: 'm4',
  7168. value: value.toArray()
  7169. };
  7170. } else {
  7171. data.uniforms[ name ] = {
  7172. value: value
  7173. };
  7174. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7175. }
  7176. }
  7177. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7178. data.vertexShader = this.vertexShader;
  7179. data.fragmentShader = this.fragmentShader;
  7180. const extensions = {};
  7181. for ( const key in this.extensions ) {
  7182. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7183. }
  7184. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7185. return data;
  7186. }
  7187. }
  7188. class Camera extends Object3D {
  7189. constructor() {
  7190. super();
  7191. this.isCamera = true;
  7192. this.type = 'Camera';
  7193. this.matrixWorldInverse = new Matrix4();
  7194. this.projectionMatrix = new Matrix4();
  7195. this.projectionMatrixInverse = new Matrix4();
  7196. }
  7197. copy( source, recursive ) {
  7198. super.copy( source, recursive );
  7199. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7200. this.projectionMatrix.copy( source.projectionMatrix );
  7201. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7202. return this;
  7203. }
  7204. getWorldDirection( target ) {
  7205. this.updateWorldMatrix( true, false );
  7206. const e = this.matrixWorld.elements;
  7207. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7208. }
  7209. updateMatrixWorld( force ) {
  7210. super.updateMatrixWorld( force );
  7211. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7212. }
  7213. updateWorldMatrix( updateParents, updateChildren ) {
  7214. super.updateWorldMatrix( updateParents, updateChildren );
  7215. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7216. }
  7217. clone() {
  7218. return new this.constructor().copy( this );
  7219. }
  7220. }
  7221. class PerspectiveCamera extends Camera {
  7222. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7223. super();
  7224. this.isPerspectiveCamera = true;
  7225. this.type = 'PerspectiveCamera';
  7226. this.fov = fov;
  7227. this.zoom = 1;
  7228. this.near = near;
  7229. this.far = far;
  7230. this.focus = 10;
  7231. this.aspect = aspect;
  7232. this.view = null;
  7233. this.filmGauge = 35; // width of the film (default in millimeters)
  7234. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7235. this.updateProjectionMatrix();
  7236. }
  7237. copy( source, recursive ) {
  7238. super.copy( source, recursive );
  7239. this.fov = source.fov;
  7240. this.zoom = source.zoom;
  7241. this.near = source.near;
  7242. this.far = source.far;
  7243. this.focus = source.focus;
  7244. this.aspect = source.aspect;
  7245. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7246. this.filmGauge = source.filmGauge;
  7247. this.filmOffset = source.filmOffset;
  7248. return this;
  7249. }
  7250. /**
  7251. * Sets the FOV by focal length in respect to the current .filmGauge.
  7252. *
  7253. * The default film gauge is 35, so that the focal length can be specified for
  7254. * a 35mm (full frame) camera.
  7255. *
  7256. * Values for focal length and film gauge must have the same unit.
  7257. */
  7258. setFocalLength( focalLength ) {
  7259. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7260. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7261. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7262. this.updateProjectionMatrix();
  7263. }
  7264. /**
  7265. * Calculates the focal length from the current .fov and .filmGauge.
  7266. */
  7267. getFocalLength() {
  7268. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7269. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7270. }
  7271. getEffectiveFOV() {
  7272. return RAD2DEG * 2 * Math.atan(
  7273. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7274. }
  7275. getFilmWidth() {
  7276. // film not completely covered in portrait format (aspect < 1)
  7277. return this.filmGauge * Math.min( this.aspect, 1 );
  7278. }
  7279. getFilmHeight() {
  7280. // film not completely covered in landscape format (aspect > 1)
  7281. return this.filmGauge / Math.max( this.aspect, 1 );
  7282. }
  7283. /**
  7284. * Sets an offset in a larger frustum. This is useful for multi-window or
  7285. * multi-monitor/multi-machine setups.
  7286. *
  7287. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7288. * the monitors are in grid like this
  7289. *
  7290. * +---+---+---+
  7291. * | A | B | C |
  7292. * +---+---+---+
  7293. * | D | E | F |
  7294. * +---+---+---+
  7295. *
  7296. * then for each monitor you would call it like this
  7297. *
  7298. * const w = 1920;
  7299. * const h = 1080;
  7300. * const fullWidth = w * 3;
  7301. * const fullHeight = h * 2;
  7302. *
  7303. * --A--
  7304. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7305. * --B--
  7306. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7307. * --C--
  7308. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7309. * --D--
  7310. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7311. * --E--
  7312. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7313. * --F--
  7314. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7315. *
  7316. * Note there is no reason monitors have to be the same size or in a grid.
  7317. */
  7318. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7319. this.aspect = fullWidth / fullHeight;
  7320. if ( this.view === null ) {
  7321. this.view = {
  7322. enabled: true,
  7323. fullWidth: 1,
  7324. fullHeight: 1,
  7325. offsetX: 0,
  7326. offsetY: 0,
  7327. width: 1,
  7328. height: 1
  7329. };
  7330. }
  7331. this.view.enabled = true;
  7332. this.view.fullWidth = fullWidth;
  7333. this.view.fullHeight = fullHeight;
  7334. this.view.offsetX = x;
  7335. this.view.offsetY = y;
  7336. this.view.width = width;
  7337. this.view.height = height;
  7338. this.updateProjectionMatrix();
  7339. }
  7340. clearViewOffset() {
  7341. if ( this.view !== null ) {
  7342. this.view.enabled = false;
  7343. }
  7344. this.updateProjectionMatrix();
  7345. }
  7346. updateProjectionMatrix() {
  7347. const near = this.near;
  7348. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7349. let height = 2 * top;
  7350. let width = this.aspect * height;
  7351. let left = - 0.5 * width;
  7352. const view = this.view;
  7353. if ( this.view !== null && this.view.enabled ) {
  7354. const fullWidth = view.fullWidth,
  7355. fullHeight = view.fullHeight;
  7356. left += view.offsetX * width / fullWidth;
  7357. top -= view.offsetY * height / fullHeight;
  7358. width *= view.width / fullWidth;
  7359. height *= view.height / fullHeight;
  7360. }
  7361. const skew = this.filmOffset;
  7362. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7363. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7364. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7365. }
  7366. toJSON( meta ) {
  7367. const data = super.toJSON( meta );
  7368. data.object.fov = this.fov;
  7369. data.object.zoom = this.zoom;
  7370. data.object.near = this.near;
  7371. data.object.far = this.far;
  7372. data.object.focus = this.focus;
  7373. data.object.aspect = this.aspect;
  7374. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7375. data.object.filmGauge = this.filmGauge;
  7376. data.object.filmOffset = this.filmOffset;
  7377. return data;
  7378. }
  7379. }
  7380. const fov = - 90; // negative fov is not an error
  7381. const aspect = 1;
  7382. class CubeCamera extends Object3D {
  7383. constructor( near, far, renderTarget ) {
  7384. super();
  7385. this.type = 'CubeCamera';
  7386. this.renderTarget = renderTarget;
  7387. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7388. cameraPX.layers = this.layers;
  7389. cameraPX.up.set( 0, 1, 0 );
  7390. cameraPX.lookAt( 1, 0, 0 );
  7391. this.add( cameraPX );
  7392. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7393. cameraNX.layers = this.layers;
  7394. cameraNX.up.set( 0, 1, 0 );
  7395. cameraNX.lookAt( - 1, 0, 0 );
  7396. this.add( cameraNX );
  7397. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7398. cameraPY.layers = this.layers;
  7399. cameraPY.up.set( 0, 0, - 1 );
  7400. cameraPY.lookAt( 0, 1, 0 );
  7401. this.add( cameraPY );
  7402. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7403. cameraNY.layers = this.layers;
  7404. cameraNY.up.set( 0, 0, 1 );
  7405. cameraNY.lookAt( 0, - 1, 0 );
  7406. this.add( cameraNY );
  7407. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7408. cameraPZ.layers = this.layers;
  7409. cameraPZ.up.set( 0, 1, 0 );
  7410. cameraPZ.lookAt( 0, 0, 1 );
  7411. this.add( cameraPZ );
  7412. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7413. cameraNZ.layers = this.layers;
  7414. cameraNZ.up.set( 0, 1, 0 );
  7415. cameraNZ.lookAt( 0, 0, - 1 );
  7416. this.add( cameraNZ );
  7417. }
  7418. update( renderer, scene ) {
  7419. if ( this.parent === null ) this.updateMatrixWorld();
  7420. const renderTarget = this.renderTarget;
  7421. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7422. const currentRenderTarget = renderer.getRenderTarget();
  7423. const currentToneMapping = renderer.toneMapping;
  7424. const currentXrEnabled = renderer.xr.enabled;
  7425. renderer.toneMapping = NoToneMapping;
  7426. renderer.xr.enabled = false;
  7427. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7428. renderTarget.texture.generateMipmaps = false;
  7429. renderer.setRenderTarget( renderTarget, 0 );
  7430. renderer.render( scene, cameraPX );
  7431. renderer.setRenderTarget( renderTarget, 1 );
  7432. renderer.render( scene, cameraNX );
  7433. renderer.setRenderTarget( renderTarget, 2 );
  7434. renderer.render( scene, cameraPY );
  7435. renderer.setRenderTarget( renderTarget, 3 );
  7436. renderer.render( scene, cameraNY );
  7437. renderer.setRenderTarget( renderTarget, 4 );
  7438. renderer.render( scene, cameraPZ );
  7439. renderTarget.texture.generateMipmaps = generateMipmaps;
  7440. renderer.setRenderTarget( renderTarget, 5 );
  7441. renderer.render( scene, cameraNZ );
  7442. renderer.setRenderTarget( currentRenderTarget );
  7443. renderer.toneMapping = currentToneMapping;
  7444. renderer.xr.enabled = currentXrEnabled;
  7445. renderTarget.texture.needsPMREMUpdate = true;
  7446. }
  7447. }
  7448. class CubeTexture extends Texture {
  7449. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7450. images = images !== undefined ? images : [];
  7451. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7452. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7453. this.isCubeTexture = true;
  7454. this.flipY = false;
  7455. }
  7456. get images() {
  7457. return this.image;
  7458. }
  7459. set images( value ) {
  7460. this.image = value;
  7461. }
  7462. }
  7463. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7464. constructor( size = 1, options = {} ) {
  7465. super( size, size, options );
  7466. this.isWebGLCubeRenderTarget = true;
  7467. const image = { width: size, height: size, depth: 1 };
  7468. const images = [ image, image, image, image, image, image ];
  7469. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7470. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7471. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7472. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7473. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7474. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7475. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7476. this.texture.isRenderTargetTexture = true;
  7477. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7478. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7479. }
  7480. fromEquirectangularTexture( renderer, texture ) {
  7481. this.texture.type = texture.type;
  7482. this.texture.encoding = texture.encoding;
  7483. this.texture.generateMipmaps = texture.generateMipmaps;
  7484. this.texture.minFilter = texture.minFilter;
  7485. this.texture.magFilter = texture.magFilter;
  7486. const shader = {
  7487. uniforms: {
  7488. tEquirect: { value: null },
  7489. },
  7490. vertexShader: /* glsl */`
  7491. varying vec3 vWorldDirection;
  7492. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7493. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7494. }
  7495. void main() {
  7496. vWorldDirection = transformDirection( position, modelMatrix );
  7497. #include <begin_vertex>
  7498. #include <project_vertex>
  7499. }
  7500. `,
  7501. fragmentShader: /* glsl */`
  7502. uniform sampler2D tEquirect;
  7503. varying vec3 vWorldDirection;
  7504. #include <common>
  7505. void main() {
  7506. vec3 direction = normalize( vWorldDirection );
  7507. vec2 sampleUV = equirectUv( direction );
  7508. gl_FragColor = texture2D( tEquirect, sampleUV );
  7509. }
  7510. `
  7511. };
  7512. const geometry = new BoxGeometry( 5, 5, 5 );
  7513. const material = new ShaderMaterial( {
  7514. name: 'CubemapFromEquirect',
  7515. uniforms: cloneUniforms( shader.uniforms ),
  7516. vertexShader: shader.vertexShader,
  7517. fragmentShader: shader.fragmentShader,
  7518. side: BackSide,
  7519. blending: NoBlending
  7520. } );
  7521. material.uniforms.tEquirect.value = texture;
  7522. const mesh = new Mesh( geometry, material );
  7523. const currentMinFilter = texture.minFilter;
  7524. // Avoid blurred poles
  7525. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7526. const camera = new CubeCamera( 1, 10, this );
  7527. camera.update( renderer, mesh );
  7528. texture.minFilter = currentMinFilter;
  7529. mesh.geometry.dispose();
  7530. mesh.material.dispose();
  7531. return this;
  7532. }
  7533. clear( renderer, color, depth, stencil ) {
  7534. const currentRenderTarget = renderer.getRenderTarget();
  7535. for ( let i = 0; i < 6; i ++ ) {
  7536. renderer.setRenderTarget( this, i );
  7537. renderer.clear( color, depth, stencil );
  7538. }
  7539. renderer.setRenderTarget( currentRenderTarget );
  7540. }
  7541. }
  7542. const _vector1 = /*@__PURE__*/ new Vector3();
  7543. const _vector2 = /*@__PURE__*/ new Vector3();
  7544. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7545. class Plane {
  7546. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7547. this.isPlane = true;
  7548. // normal is assumed to be normalized
  7549. this.normal = normal;
  7550. this.constant = constant;
  7551. }
  7552. set( normal, constant ) {
  7553. this.normal.copy( normal );
  7554. this.constant = constant;
  7555. return this;
  7556. }
  7557. setComponents( x, y, z, w ) {
  7558. this.normal.set( x, y, z );
  7559. this.constant = w;
  7560. return this;
  7561. }
  7562. setFromNormalAndCoplanarPoint( normal, point ) {
  7563. this.normal.copy( normal );
  7564. this.constant = - point.dot( this.normal );
  7565. return this;
  7566. }
  7567. setFromCoplanarPoints( a, b, c ) {
  7568. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7569. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7570. this.setFromNormalAndCoplanarPoint( normal, a );
  7571. return this;
  7572. }
  7573. copy( plane ) {
  7574. this.normal.copy( plane.normal );
  7575. this.constant = plane.constant;
  7576. return this;
  7577. }
  7578. normalize() {
  7579. // Note: will lead to a divide by zero if the plane is invalid.
  7580. const inverseNormalLength = 1.0 / this.normal.length();
  7581. this.normal.multiplyScalar( inverseNormalLength );
  7582. this.constant *= inverseNormalLength;
  7583. return this;
  7584. }
  7585. negate() {
  7586. this.constant *= - 1;
  7587. this.normal.negate();
  7588. return this;
  7589. }
  7590. distanceToPoint( point ) {
  7591. return this.normal.dot( point ) + this.constant;
  7592. }
  7593. distanceToSphere( sphere ) {
  7594. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7595. }
  7596. projectPoint( point, target ) {
  7597. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7598. }
  7599. intersectLine( line, target ) {
  7600. const direction = line.delta( _vector1 );
  7601. const denominator = this.normal.dot( direction );
  7602. if ( denominator === 0 ) {
  7603. // line is coplanar, return origin
  7604. if ( this.distanceToPoint( line.start ) === 0 ) {
  7605. return target.copy( line.start );
  7606. }
  7607. // Unsure if this is the correct method to handle this case.
  7608. return null;
  7609. }
  7610. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7611. if ( t < 0 || t > 1 ) {
  7612. return null;
  7613. }
  7614. return target.copy( line.start ).addScaledVector( direction, t );
  7615. }
  7616. intersectsLine( line ) {
  7617. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7618. const startSign = this.distanceToPoint( line.start );
  7619. const endSign = this.distanceToPoint( line.end );
  7620. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7621. }
  7622. intersectsBox( box ) {
  7623. return box.intersectsPlane( this );
  7624. }
  7625. intersectsSphere( sphere ) {
  7626. return sphere.intersectsPlane( this );
  7627. }
  7628. coplanarPoint( target ) {
  7629. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7630. }
  7631. applyMatrix4( matrix, optionalNormalMatrix ) {
  7632. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7633. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7634. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7635. this.constant = - referencePoint.dot( normal );
  7636. return this;
  7637. }
  7638. translate( offset ) {
  7639. this.constant -= offset.dot( this.normal );
  7640. return this;
  7641. }
  7642. equals( plane ) {
  7643. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7644. }
  7645. clone() {
  7646. return new this.constructor().copy( this );
  7647. }
  7648. }
  7649. const _sphere$3 = /*@__PURE__*/ new Sphere();
  7650. const _vector$6 = /*@__PURE__*/ new Vector3();
  7651. class Frustum {
  7652. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7653. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7654. }
  7655. set( p0, p1, p2, p3, p4, p5 ) {
  7656. const planes = this.planes;
  7657. planes[ 0 ].copy( p0 );
  7658. planes[ 1 ].copy( p1 );
  7659. planes[ 2 ].copy( p2 );
  7660. planes[ 3 ].copy( p3 );
  7661. planes[ 4 ].copy( p4 );
  7662. planes[ 5 ].copy( p5 );
  7663. return this;
  7664. }
  7665. copy( frustum ) {
  7666. const planes = this.planes;
  7667. for ( let i = 0; i < 6; i ++ ) {
  7668. planes[ i ].copy( frustum.planes[ i ] );
  7669. }
  7670. return this;
  7671. }
  7672. setFromProjectionMatrix( m ) {
  7673. const planes = this.planes;
  7674. const me = m.elements;
  7675. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7676. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7677. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7678. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7679. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7680. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7681. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7682. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7683. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7684. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7685. return this;
  7686. }
  7687. intersectsObject( object ) {
  7688. if ( object.boundingSphere !== undefined ) {
  7689. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7690. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7691. } else {
  7692. const geometry = object.geometry;
  7693. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7694. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7695. }
  7696. return this.intersectsSphere( _sphere$3 );
  7697. }
  7698. intersectsSprite( sprite ) {
  7699. _sphere$3.center.set( 0, 0, 0 );
  7700. _sphere$3.radius = 0.7071067811865476;
  7701. _sphere$3.applyMatrix4( sprite.matrixWorld );
  7702. return this.intersectsSphere( _sphere$3 );
  7703. }
  7704. intersectsSphere( sphere ) {
  7705. const planes = this.planes;
  7706. const center = sphere.center;
  7707. const negRadius = - sphere.radius;
  7708. for ( let i = 0; i < 6; i ++ ) {
  7709. const distance = planes[ i ].distanceToPoint( center );
  7710. if ( distance < negRadius ) {
  7711. return false;
  7712. }
  7713. }
  7714. return true;
  7715. }
  7716. intersectsBox( box ) {
  7717. const planes = this.planes;
  7718. for ( let i = 0; i < 6; i ++ ) {
  7719. const plane = planes[ i ];
  7720. // corner at max distance
  7721. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7722. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7723. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7724. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  7725. return false;
  7726. }
  7727. }
  7728. return true;
  7729. }
  7730. containsPoint( point ) {
  7731. const planes = this.planes;
  7732. for ( let i = 0; i < 6; i ++ ) {
  7733. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7734. return false;
  7735. }
  7736. }
  7737. return true;
  7738. }
  7739. clone() {
  7740. return new this.constructor().copy( this );
  7741. }
  7742. }
  7743. function WebGLAnimation() {
  7744. let context = null;
  7745. let isAnimating = false;
  7746. let animationLoop = null;
  7747. let requestId = null;
  7748. function onAnimationFrame( time, frame ) {
  7749. animationLoop( time, frame );
  7750. requestId = context.requestAnimationFrame( onAnimationFrame );
  7751. }
  7752. return {
  7753. start: function () {
  7754. if ( isAnimating === true ) return;
  7755. if ( animationLoop === null ) return;
  7756. requestId = context.requestAnimationFrame( onAnimationFrame );
  7757. isAnimating = true;
  7758. },
  7759. stop: function () {
  7760. context.cancelAnimationFrame( requestId );
  7761. isAnimating = false;
  7762. },
  7763. setAnimationLoop: function ( callback ) {
  7764. animationLoop = callback;
  7765. },
  7766. setContext: function ( value ) {
  7767. context = value;
  7768. }
  7769. };
  7770. }
  7771. function WebGLAttributes( gl, capabilities ) {
  7772. const isWebGL2 = capabilities.isWebGL2;
  7773. const buffers = new WeakMap();
  7774. function createBuffer( attribute, bufferType ) {
  7775. const array = attribute.array;
  7776. const usage = attribute.usage;
  7777. const buffer = gl.createBuffer();
  7778. gl.bindBuffer( bufferType, buffer );
  7779. gl.bufferData( bufferType, array, usage );
  7780. attribute.onUploadCallback();
  7781. let type;
  7782. if ( array instanceof Float32Array ) {
  7783. type = 5126;
  7784. } else if ( array instanceof Uint16Array ) {
  7785. if ( attribute.isFloat16BufferAttribute ) {
  7786. if ( isWebGL2 ) {
  7787. type = 5131;
  7788. } else {
  7789. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7790. }
  7791. } else {
  7792. type = 5123;
  7793. }
  7794. } else if ( array instanceof Int16Array ) {
  7795. type = 5122;
  7796. } else if ( array instanceof Uint32Array ) {
  7797. type = 5125;
  7798. } else if ( array instanceof Int32Array ) {
  7799. type = 5124;
  7800. } else if ( array instanceof Int8Array ) {
  7801. type = 5120;
  7802. } else if ( array instanceof Uint8Array ) {
  7803. type = 5121;
  7804. } else if ( array instanceof Uint8ClampedArray ) {
  7805. type = 5121;
  7806. } else {
  7807. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7808. }
  7809. return {
  7810. buffer: buffer,
  7811. type: type,
  7812. bytesPerElement: array.BYTES_PER_ELEMENT,
  7813. version: attribute.version
  7814. };
  7815. }
  7816. function updateBuffer( buffer, attribute, bufferType ) {
  7817. const array = attribute.array;
  7818. const updateRange = attribute.updateRange;
  7819. gl.bindBuffer( bufferType, buffer );
  7820. if ( updateRange.count === - 1 ) {
  7821. // Not using update ranges
  7822. gl.bufferSubData( bufferType, 0, array );
  7823. } else {
  7824. if ( isWebGL2 ) {
  7825. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7826. array, updateRange.offset, updateRange.count );
  7827. } else {
  7828. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7829. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7830. }
  7831. updateRange.count = - 1; // reset range
  7832. }
  7833. attribute.onUploadCallback();
  7834. }
  7835. //
  7836. function get( attribute ) {
  7837. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7838. return buffers.get( attribute );
  7839. }
  7840. function remove( attribute ) {
  7841. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7842. const data = buffers.get( attribute );
  7843. if ( data ) {
  7844. gl.deleteBuffer( data.buffer );
  7845. buffers.delete( attribute );
  7846. }
  7847. }
  7848. function update( attribute, bufferType ) {
  7849. if ( attribute.isGLBufferAttribute ) {
  7850. const cached = buffers.get( attribute );
  7851. if ( ! cached || cached.version < attribute.version ) {
  7852. buffers.set( attribute, {
  7853. buffer: attribute.buffer,
  7854. type: attribute.type,
  7855. bytesPerElement: attribute.elementSize,
  7856. version: attribute.version
  7857. } );
  7858. }
  7859. return;
  7860. }
  7861. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7862. const data = buffers.get( attribute );
  7863. if ( data === undefined ) {
  7864. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7865. } else if ( data.version < attribute.version ) {
  7866. updateBuffer( data.buffer, attribute, bufferType );
  7867. data.version = attribute.version;
  7868. }
  7869. }
  7870. return {
  7871. get: get,
  7872. remove: remove,
  7873. update: update
  7874. };
  7875. }
  7876. class PlaneGeometry extends BufferGeometry {
  7877. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7878. super();
  7879. this.type = 'PlaneGeometry';
  7880. this.parameters = {
  7881. width: width,
  7882. height: height,
  7883. widthSegments: widthSegments,
  7884. heightSegments: heightSegments
  7885. };
  7886. const width_half = width / 2;
  7887. const height_half = height / 2;
  7888. const gridX = Math.floor( widthSegments );
  7889. const gridY = Math.floor( heightSegments );
  7890. const gridX1 = gridX + 1;
  7891. const gridY1 = gridY + 1;
  7892. const segment_width = width / gridX;
  7893. const segment_height = height / gridY;
  7894. //
  7895. const indices = [];
  7896. const vertices = [];
  7897. const normals = [];
  7898. const uvs = [];
  7899. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7900. const y = iy * segment_height - height_half;
  7901. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7902. const x = ix * segment_width - width_half;
  7903. vertices.push( x, - y, 0 );
  7904. normals.push( 0, 0, 1 );
  7905. uvs.push( ix / gridX );
  7906. uvs.push( 1 - ( iy / gridY ) );
  7907. }
  7908. }
  7909. for ( let iy = 0; iy < gridY; iy ++ ) {
  7910. for ( let ix = 0; ix < gridX; ix ++ ) {
  7911. const a = ix + gridX1 * iy;
  7912. const b = ix + gridX1 * ( iy + 1 );
  7913. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7914. const d = ( ix + 1 ) + gridX1 * iy;
  7915. indices.push( a, b, d );
  7916. indices.push( b, c, d );
  7917. }
  7918. }
  7919. this.setIndex( indices );
  7920. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7921. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7922. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7923. }
  7924. copy( source ) {
  7925. super.copy( source );
  7926. this.parameters = Object.assign( {}, source.parameters );
  7927. return this;
  7928. }
  7929. static fromJSON( data ) {
  7930. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7931. }
  7932. }
  7933. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  7934. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7935. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7936. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7937. 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";
  7938. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7939. var begin_vertex = "vec3 transformed = vec3( position );";
  7940. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7941. 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";
  7942. 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";
  7943. 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";
  7944. 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";
  7945. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7946. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7947. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7948. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7949. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7950. 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";
  7951. 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";
  7952. 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";
  7953. 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";
  7954. 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";
  7955. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7956. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  7957. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7958. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7959. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7960. 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}";
  7961. 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";
  7962. 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";
  7963. 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";
  7964. 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";
  7965. 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";
  7966. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7967. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7968. 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";
  7969. 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";
  7970. 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}";
  7971. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7972. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7973. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7974. 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";
  7975. 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";
  7976. 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";
  7977. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7978. 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";
  7979. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7980. 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";
  7981. 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";
  7982. 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}";
  7983. 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";
  7984. 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";
  7985. 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";
  7986. 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";
  7987. 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";
  7988. 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";
  7989. 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";
  7990. 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";
  7991. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7992. 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";
  7993. 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";
  7994. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7995. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7996. 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";
  7997. 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";
  7998. 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";
  7999. 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";
  8000. 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;";
  8001. 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";
  8002. 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";
  8003. 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";
  8004. 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";
  8005. 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";
  8006. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8007. 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";
  8008. 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";
  8009. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8010. 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 );";
  8011. 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}";
  8012. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8013. 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;";
  8014. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8015. 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";
  8016. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8017. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8018. 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";
  8019. 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";
  8020. 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";
  8021. 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}";
  8022. 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";
  8023. 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";
  8024. 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";
  8025. 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";
  8026. 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";
  8027. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8028. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8029. 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; }";
  8030. 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";
  8031. 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";
  8032. 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";
  8033. 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";
  8034. 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";
  8035. 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";
  8036. 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}";
  8037. 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}";
  8038. 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}";
  8039. 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}";
  8040. 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}";
  8041. 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}";
  8042. 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}";
  8043. 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}";
  8044. 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}";
  8045. 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}";
  8046. 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}";
  8047. 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}";
  8048. 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}";
  8049. 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}";
  8050. 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}";
  8051. 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}";
  8052. 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}";
  8053. 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}";
  8054. 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}";
  8055. 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}";
  8056. 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}";
  8057. 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}";
  8058. 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}";
  8059. 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}";
  8060. 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}";
  8061. 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}";
  8062. 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}";
  8063. 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}";
  8064. 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}";
  8065. 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}";
  8066. 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}";
  8067. 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}";
  8068. 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}";
  8069. 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}";
  8070. const ShaderChunk = {
  8071. alphamap_fragment: alphamap_fragment,
  8072. alphamap_pars_fragment: alphamap_pars_fragment,
  8073. alphatest_fragment: alphatest_fragment,
  8074. alphatest_pars_fragment: alphatest_pars_fragment,
  8075. aomap_fragment: aomap_fragment,
  8076. aomap_pars_fragment: aomap_pars_fragment,
  8077. begin_vertex: begin_vertex,
  8078. beginnormal_vertex: beginnormal_vertex,
  8079. bsdfs: bsdfs,
  8080. iridescence_fragment: iridescence_fragment,
  8081. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8082. clipping_planes_fragment: clipping_planes_fragment,
  8083. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8084. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8085. clipping_planes_vertex: clipping_planes_vertex,
  8086. color_fragment: color_fragment,
  8087. color_pars_fragment: color_pars_fragment,
  8088. color_pars_vertex: color_pars_vertex,
  8089. color_vertex: color_vertex,
  8090. common: common,
  8091. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8092. defaultnormal_vertex: defaultnormal_vertex,
  8093. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8094. displacementmap_vertex: displacementmap_vertex,
  8095. emissivemap_fragment: emissivemap_fragment,
  8096. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8097. encodings_fragment: encodings_fragment,
  8098. encodings_pars_fragment: encodings_pars_fragment,
  8099. envmap_fragment: envmap_fragment,
  8100. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8101. envmap_pars_fragment: envmap_pars_fragment,
  8102. envmap_pars_vertex: envmap_pars_vertex,
  8103. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8104. envmap_vertex: envmap_vertex,
  8105. fog_vertex: fog_vertex,
  8106. fog_pars_vertex: fog_pars_vertex,
  8107. fog_fragment: fog_fragment,
  8108. fog_pars_fragment: fog_pars_fragment,
  8109. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8110. lightmap_fragment: lightmap_fragment,
  8111. lightmap_pars_fragment: lightmap_pars_fragment,
  8112. lights_lambert_fragment: lights_lambert_fragment,
  8113. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8114. lights_pars_begin: lights_pars_begin,
  8115. lights_toon_fragment: lights_toon_fragment,
  8116. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8117. lights_phong_fragment: lights_phong_fragment,
  8118. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8119. lights_physical_fragment: lights_physical_fragment,
  8120. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8121. lights_fragment_begin: lights_fragment_begin,
  8122. lights_fragment_maps: lights_fragment_maps,
  8123. lights_fragment_end: lights_fragment_end,
  8124. logdepthbuf_fragment: logdepthbuf_fragment,
  8125. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8126. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8127. logdepthbuf_vertex: logdepthbuf_vertex,
  8128. map_fragment: map_fragment,
  8129. map_pars_fragment: map_pars_fragment,
  8130. map_particle_fragment: map_particle_fragment,
  8131. map_particle_pars_fragment: map_particle_pars_fragment,
  8132. metalnessmap_fragment: metalnessmap_fragment,
  8133. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8134. morphcolor_vertex: morphcolor_vertex,
  8135. morphnormal_vertex: morphnormal_vertex,
  8136. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8137. morphtarget_vertex: morphtarget_vertex,
  8138. normal_fragment_begin: normal_fragment_begin,
  8139. normal_fragment_maps: normal_fragment_maps,
  8140. normal_pars_fragment: normal_pars_fragment,
  8141. normal_pars_vertex: normal_pars_vertex,
  8142. normal_vertex: normal_vertex,
  8143. normalmap_pars_fragment: normalmap_pars_fragment,
  8144. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8145. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8146. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8147. iridescence_pars_fragment: iridescence_pars_fragment,
  8148. output_fragment: output_fragment,
  8149. packing: packing,
  8150. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8151. project_vertex: project_vertex,
  8152. dithering_fragment: dithering_fragment,
  8153. dithering_pars_fragment: dithering_pars_fragment,
  8154. roughnessmap_fragment: roughnessmap_fragment,
  8155. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8156. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8157. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8158. shadowmap_vertex: shadowmap_vertex,
  8159. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8160. skinbase_vertex: skinbase_vertex,
  8161. skinning_pars_vertex: skinning_pars_vertex,
  8162. skinning_vertex: skinning_vertex,
  8163. skinnormal_vertex: skinnormal_vertex,
  8164. specularmap_fragment: specularmap_fragment,
  8165. specularmap_pars_fragment: specularmap_pars_fragment,
  8166. tonemapping_fragment: tonemapping_fragment,
  8167. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8168. transmission_fragment: transmission_fragment,
  8169. transmission_pars_fragment: transmission_pars_fragment,
  8170. uv_pars_fragment: uv_pars_fragment,
  8171. uv_pars_vertex: uv_pars_vertex,
  8172. uv_vertex: uv_vertex,
  8173. worldpos_vertex: worldpos_vertex,
  8174. background_vert: vertex$h,
  8175. background_frag: fragment$h,
  8176. backgroundCube_vert: vertex$g,
  8177. backgroundCube_frag: fragment$g,
  8178. cube_vert: vertex$f,
  8179. cube_frag: fragment$f,
  8180. depth_vert: vertex$e,
  8181. depth_frag: fragment$e,
  8182. distanceRGBA_vert: vertex$d,
  8183. distanceRGBA_frag: fragment$d,
  8184. equirect_vert: vertex$c,
  8185. equirect_frag: fragment$c,
  8186. linedashed_vert: vertex$b,
  8187. linedashed_frag: fragment$b,
  8188. meshbasic_vert: vertex$a,
  8189. meshbasic_frag: fragment$a,
  8190. meshlambert_vert: vertex$9,
  8191. meshlambert_frag: fragment$9,
  8192. meshmatcap_vert: vertex$8,
  8193. meshmatcap_frag: fragment$8,
  8194. meshnormal_vert: vertex$7,
  8195. meshnormal_frag: fragment$7,
  8196. meshphong_vert: vertex$6,
  8197. meshphong_frag: fragment$6,
  8198. meshphysical_vert: vertex$5,
  8199. meshphysical_frag: fragment$5,
  8200. meshtoon_vert: vertex$4,
  8201. meshtoon_frag: fragment$4,
  8202. points_vert: vertex$3,
  8203. points_frag: fragment$3,
  8204. shadow_vert: vertex$2,
  8205. shadow_frag: fragment$2,
  8206. sprite_vert: vertex$1,
  8207. sprite_frag: fragment$1
  8208. };
  8209. /**
  8210. * Uniforms library for shared webgl shaders
  8211. */
  8212. const UniformsLib = {
  8213. common: {
  8214. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8215. opacity: { value: 1.0 },
  8216. map: { value: null },
  8217. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8218. alphaMap: { value: null },
  8219. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8220. alphaTest: { value: 0 }
  8221. },
  8222. specularmap: {
  8223. specularMap: { value: null },
  8224. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8225. },
  8226. envmap: {
  8227. envMap: { value: null },
  8228. flipEnvMap: { value: - 1 },
  8229. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8230. ior: { value: 1.5 }, // physical
  8231. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8232. },
  8233. aomap: {
  8234. aoMap: { value: null },
  8235. aoMapIntensity: { value: 1 },
  8236. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8237. },
  8238. lightmap: {
  8239. lightMap: { value: null },
  8240. lightMapIntensity: { value: 1 },
  8241. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8242. },
  8243. bumpmap: {
  8244. bumpMap: { value: null },
  8245. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8246. bumpScale: { value: 1 }
  8247. },
  8248. normalmap: {
  8249. normalMap: { value: null },
  8250. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8251. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8252. },
  8253. displacementmap: {
  8254. displacementMap: { value: null },
  8255. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8256. displacementScale: { value: 1 },
  8257. displacementBias: { value: 0 }
  8258. },
  8259. emissivemap: {
  8260. emissiveMap: { value: null },
  8261. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8262. },
  8263. metalnessmap: {
  8264. metalnessMap: { value: null },
  8265. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8266. },
  8267. roughnessmap: {
  8268. roughnessMap: { value: null },
  8269. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8270. },
  8271. gradientmap: {
  8272. gradientMap: { value: null }
  8273. },
  8274. fog: {
  8275. fogDensity: { value: 0.00025 },
  8276. fogNear: { value: 1 },
  8277. fogFar: { value: 2000 },
  8278. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8279. },
  8280. lights: {
  8281. ambientLightColor: { value: [] },
  8282. lightProbe: { value: [] },
  8283. directionalLights: { value: [], properties: {
  8284. direction: {},
  8285. color: {}
  8286. } },
  8287. directionalLightShadows: { value: [], properties: {
  8288. shadowBias: {},
  8289. shadowNormalBias: {},
  8290. shadowRadius: {},
  8291. shadowMapSize: {}
  8292. } },
  8293. directionalShadowMap: { value: [] },
  8294. directionalShadowMatrix: { value: [] },
  8295. spotLights: { value: [], properties: {
  8296. color: {},
  8297. position: {},
  8298. direction: {},
  8299. distance: {},
  8300. coneCos: {},
  8301. penumbraCos: {},
  8302. decay: {}
  8303. } },
  8304. spotLightShadows: { value: [], properties: {
  8305. shadowBias: {},
  8306. shadowNormalBias: {},
  8307. shadowRadius: {},
  8308. shadowMapSize: {}
  8309. } },
  8310. spotLightMap: { value: [] },
  8311. spotShadowMap: { value: [] },
  8312. spotLightMatrix: { value: [] },
  8313. pointLights: { value: [], properties: {
  8314. color: {},
  8315. position: {},
  8316. decay: {},
  8317. distance: {}
  8318. } },
  8319. pointLightShadows: { value: [], properties: {
  8320. shadowBias: {},
  8321. shadowNormalBias: {},
  8322. shadowRadius: {},
  8323. shadowMapSize: {},
  8324. shadowCameraNear: {},
  8325. shadowCameraFar: {}
  8326. } },
  8327. pointShadowMap: { value: [] },
  8328. pointShadowMatrix: { value: [] },
  8329. hemisphereLights: { value: [], properties: {
  8330. direction: {},
  8331. skyColor: {},
  8332. groundColor: {}
  8333. } },
  8334. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8335. rectAreaLights: { value: [], properties: {
  8336. color: {},
  8337. position: {},
  8338. width: {},
  8339. height: {}
  8340. } },
  8341. ltc_1: { value: null },
  8342. ltc_2: { value: null }
  8343. },
  8344. points: {
  8345. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8346. opacity: { value: 1.0 },
  8347. size: { value: 1.0 },
  8348. scale: { value: 1.0 },
  8349. map: { value: null },
  8350. alphaMap: { value: null },
  8351. alphaTest: { value: 0 },
  8352. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8353. },
  8354. sprite: {
  8355. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8356. opacity: { value: 1.0 },
  8357. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8358. rotation: { value: 0.0 },
  8359. map: { value: null },
  8360. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8361. alphaMap: { value: null },
  8362. alphaTest: { value: 0 }
  8363. }
  8364. };
  8365. const ShaderLib = {
  8366. basic: {
  8367. uniforms: /*@__PURE__*/ mergeUniforms( [
  8368. UniformsLib.common,
  8369. UniformsLib.specularmap,
  8370. UniformsLib.envmap,
  8371. UniformsLib.aomap,
  8372. UniformsLib.lightmap,
  8373. UniformsLib.fog
  8374. ] ),
  8375. vertexShader: ShaderChunk.meshbasic_vert,
  8376. fragmentShader: ShaderChunk.meshbasic_frag
  8377. },
  8378. lambert: {
  8379. uniforms: /*@__PURE__*/ mergeUniforms( [
  8380. UniformsLib.common,
  8381. UniformsLib.specularmap,
  8382. UniformsLib.envmap,
  8383. UniformsLib.aomap,
  8384. UniformsLib.lightmap,
  8385. UniformsLib.emissivemap,
  8386. UniformsLib.bumpmap,
  8387. UniformsLib.normalmap,
  8388. UniformsLib.displacementmap,
  8389. UniformsLib.fog,
  8390. UniformsLib.lights,
  8391. {
  8392. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8393. }
  8394. ] ),
  8395. vertexShader: ShaderChunk.meshlambert_vert,
  8396. fragmentShader: ShaderChunk.meshlambert_frag
  8397. },
  8398. phong: {
  8399. uniforms: /*@__PURE__*/ mergeUniforms( [
  8400. UniformsLib.common,
  8401. UniformsLib.specularmap,
  8402. UniformsLib.envmap,
  8403. UniformsLib.aomap,
  8404. UniformsLib.lightmap,
  8405. UniformsLib.emissivemap,
  8406. UniformsLib.bumpmap,
  8407. UniformsLib.normalmap,
  8408. UniformsLib.displacementmap,
  8409. UniformsLib.fog,
  8410. UniformsLib.lights,
  8411. {
  8412. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8413. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8414. shininess: { value: 30 }
  8415. }
  8416. ] ),
  8417. vertexShader: ShaderChunk.meshphong_vert,
  8418. fragmentShader: ShaderChunk.meshphong_frag
  8419. },
  8420. standard: {
  8421. uniforms: /*@__PURE__*/ mergeUniforms( [
  8422. UniformsLib.common,
  8423. UniformsLib.envmap,
  8424. UniformsLib.aomap,
  8425. UniformsLib.lightmap,
  8426. UniformsLib.emissivemap,
  8427. UniformsLib.bumpmap,
  8428. UniformsLib.normalmap,
  8429. UniformsLib.displacementmap,
  8430. UniformsLib.roughnessmap,
  8431. UniformsLib.metalnessmap,
  8432. UniformsLib.fog,
  8433. UniformsLib.lights,
  8434. {
  8435. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8436. roughness: { value: 1.0 },
  8437. metalness: { value: 0.0 },
  8438. envMapIntensity: { value: 1 } // temporary
  8439. }
  8440. ] ),
  8441. vertexShader: ShaderChunk.meshphysical_vert,
  8442. fragmentShader: ShaderChunk.meshphysical_frag
  8443. },
  8444. toon: {
  8445. uniforms: /*@__PURE__*/ mergeUniforms( [
  8446. UniformsLib.common,
  8447. UniformsLib.aomap,
  8448. UniformsLib.lightmap,
  8449. UniformsLib.emissivemap,
  8450. UniformsLib.bumpmap,
  8451. UniformsLib.normalmap,
  8452. UniformsLib.displacementmap,
  8453. UniformsLib.gradientmap,
  8454. UniformsLib.fog,
  8455. UniformsLib.lights,
  8456. {
  8457. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8458. }
  8459. ] ),
  8460. vertexShader: ShaderChunk.meshtoon_vert,
  8461. fragmentShader: ShaderChunk.meshtoon_frag
  8462. },
  8463. matcap: {
  8464. uniforms: /*@__PURE__*/ mergeUniforms( [
  8465. UniformsLib.common,
  8466. UniformsLib.bumpmap,
  8467. UniformsLib.normalmap,
  8468. UniformsLib.displacementmap,
  8469. UniformsLib.fog,
  8470. {
  8471. matcap: { value: null }
  8472. }
  8473. ] ),
  8474. vertexShader: ShaderChunk.meshmatcap_vert,
  8475. fragmentShader: ShaderChunk.meshmatcap_frag
  8476. },
  8477. points: {
  8478. uniforms: /*@__PURE__*/ mergeUniforms( [
  8479. UniformsLib.points,
  8480. UniformsLib.fog
  8481. ] ),
  8482. vertexShader: ShaderChunk.points_vert,
  8483. fragmentShader: ShaderChunk.points_frag
  8484. },
  8485. dashed: {
  8486. uniforms: /*@__PURE__*/ mergeUniforms( [
  8487. UniformsLib.common,
  8488. UniformsLib.fog,
  8489. {
  8490. scale: { value: 1 },
  8491. dashSize: { value: 1 },
  8492. totalSize: { value: 2 }
  8493. }
  8494. ] ),
  8495. vertexShader: ShaderChunk.linedashed_vert,
  8496. fragmentShader: ShaderChunk.linedashed_frag
  8497. },
  8498. depth: {
  8499. uniforms: /*@__PURE__*/ mergeUniforms( [
  8500. UniformsLib.common,
  8501. UniformsLib.displacementmap
  8502. ] ),
  8503. vertexShader: ShaderChunk.depth_vert,
  8504. fragmentShader: ShaderChunk.depth_frag
  8505. },
  8506. normal: {
  8507. uniforms: /*@__PURE__*/ mergeUniforms( [
  8508. UniformsLib.common,
  8509. UniformsLib.bumpmap,
  8510. UniformsLib.normalmap,
  8511. UniformsLib.displacementmap,
  8512. {
  8513. opacity: { value: 1.0 }
  8514. }
  8515. ] ),
  8516. vertexShader: ShaderChunk.meshnormal_vert,
  8517. fragmentShader: ShaderChunk.meshnormal_frag
  8518. },
  8519. sprite: {
  8520. uniforms: /*@__PURE__*/ mergeUniforms( [
  8521. UniformsLib.sprite,
  8522. UniformsLib.fog
  8523. ] ),
  8524. vertexShader: ShaderChunk.sprite_vert,
  8525. fragmentShader: ShaderChunk.sprite_frag
  8526. },
  8527. background: {
  8528. uniforms: {
  8529. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8530. t2D: { value: null },
  8531. backgroundIntensity: { value: 1 }
  8532. },
  8533. vertexShader: ShaderChunk.background_vert,
  8534. fragmentShader: ShaderChunk.background_frag
  8535. },
  8536. backgroundCube: {
  8537. uniforms: {
  8538. envMap: { value: null },
  8539. flipEnvMap: { value: - 1 },
  8540. backgroundBlurriness: { value: 0 },
  8541. backgroundIntensity: { value: 1 }
  8542. },
  8543. vertexShader: ShaderChunk.backgroundCube_vert,
  8544. fragmentShader: ShaderChunk.backgroundCube_frag
  8545. },
  8546. cube: {
  8547. uniforms: {
  8548. tCube: { value: null },
  8549. tFlip: { value: - 1 },
  8550. opacity: { value: 1.0 }
  8551. },
  8552. vertexShader: ShaderChunk.cube_vert,
  8553. fragmentShader: ShaderChunk.cube_frag
  8554. },
  8555. equirect: {
  8556. uniforms: {
  8557. tEquirect: { value: null },
  8558. },
  8559. vertexShader: ShaderChunk.equirect_vert,
  8560. fragmentShader: ShaderChunk.equirect_frag
  8561. },
  8562. distanceRGBA: {
  8563. uniforms: /*@__PURE__*/ mergeUniforms( [
  8564. UniformsLib.common,
  8565. UniformsLib.displacementmap,
  8566. {
  8567. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8568. nearDistance: { value: 1 },
  8569. farDistance: { value: 1000 }
  8570. }
  8571. ] ),
  8572. vertexShader: ShaderChunk.distanceRGBA_vert,
  8573. fragmentShader: ShaderChunk.distanceRGBA_frag
  8574. },
  8575. shadow: {
  8576. uniforms: /*@__PURE__*/ mergeUniforms( [
  8577. UniformsLib.lights,
  8578. UniformsLib.fog,
  8579. {
  8580. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8581. opacity: { value: 1.0 }
  8582. },
  8583. ] ),
  8584. vertexShader: ShaderChunk.shadow_vert,
  8585. fragmentShader: ShaderChunk.shadow_frag
  8586. }
  8587. };
  8588. ShaderLib.physical = {
  8589. uniforms: /*@__PURE__*/ mergeUniforms( [
  8590. ShaderLib.standard.uniforms,
  8591. {
  8592. clearcoat: { value: 0 },
  8593. clearcoatMap: { value: null },
  8594. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8595. clearcoatNormalMap: { value: null },
  8596. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8597. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8598. clearcoatRoughness: { value: 0 },
  8599. clearcoatRoughnessMap: { value: null },
  8600. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8601. iridescence: { value: 0 },
  8602. iridescenceMap: { value: null },
  8603. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8604. iridescenceIOR: { value: 1.3 },
  8605. iridescenceThicknessMinimum: { value: 100 },
  8606. iridescenceThicknessMaximum: { value: 400 },
  8607. iridescenceThicknessMap: { value: null },
  8608. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8609. sheen: { value: 0 },
  8610. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8611. sheenColorMap: { value: null },
  8612. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8613. sheenRoughness: { value: 1 },
  8614. sheenRoughnessMap: { value: null },
  8615. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8616. transmission: { value: 0 },
  8617. transmissionMap: { value: null },
  8618. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8619. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8620. transmissionSamplerMap: { value: null },
  8621. thickness: { value: 0 },
  8622. thicknessMap: { value: null },
  8623. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8624. attenuationDistance: { value: 0 },
  8625. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8626. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8627. specularColorMap: { value: null },
  8628. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8629. specularIntensity: { value: 1 },
  8630. specularIntensityMap: { value: null },
  8631. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8632. }
  8633. ] ),
  8634. vertexShader: ShaderChunk.meshphysical_vert,
  8635. fragmentShader: ShaderChunk.meshphysical_frag
  8636. };
  8637. const _rgb = { r: 0, b: 0, g: 0 };
  8638. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8639. const clearColor = new Color( 0x000000 );
  8640. let clearAlpha = alpha === true ? 0 : 1;
  8641. let planeMesh;
  8642. let boxMesh;
  8643. let currentBackground = null;
  8644. let currentBackgroundVersion = 0;
  8645. let currentTonemapping = null;
  8646. function render( renderList, scene ) {
  8647. let forceClear = false;
  8648. let background = scene.isScene === true ? scene.background : null;
  8649. if ( background && background.isTexture ) {
  8650. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8651. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8652. }
  8653. // Ignore background in AR
  8654. // TODO: Reconsider this.
  8655. const xr = renderer.xr;
  8656. const session = xr.getSession && xr.getSession();
  8657. if ( session && session.environmentBlendMode === 'additive' ) {
  8658. background = null;
  8659. }
  8660. if ( background === null ) {
  8661. setClear( clearColor, clearAlpha );
  8662. } else if ( background && background.isColor ) {
  8663. setClear( background, 1 );
  8664. forceClear = true;
  8665. }
  8666. if ( renderer.autoClear || forceClear ) {
  8667. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8668. }
  8669. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8670. if ( boxMesh === undefined ) {
  8671. boxMesh = new Mesh(
  8672. new BoxGeometry( 1, 1, 1 ),
  8673. new ShaderMaterial( {
  8674. name: 'BackgroundCubeMaterial',
  8675. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8676. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8677. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8678. side: BackSide,
  8679. depthTest: false,
  8680. depthWrite: false,
  8681. fog: false
  8682. } )
  8683. );
  8684. boxMesh.geometry.deleteAttribute( 'normal' );
  8685. boxMesh.geometry.deleteAttribute( 'uv' );
  8686. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8687. this.matrixWorld.copyPosition( camera.matrixWorld );
  8688. };
  8689. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8690. Object.defineProperty( boxMesh.material, 'envMap', {
  8691. get: function () {
  8692. return this.uniforms.envMap.value;
  8693. }
  8694. } );
  8695. objects.update( boxMesh );
  8696. }
  8697. boxMesh.material.uniforms.envMap.value = background;
  8698. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8699. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8700. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8701. boxMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8702. if ( currentBackground !== background ||
  8703. currentBackgroundVersion !== background.version ||
  8704. currentTonemapping !== renderer.toneMapping ) {
  8705. boxMesh.material.needsUpdate = true;
  8706. currentBackground = background;
  8707. currentBackgroundVersion = background.version;
  8708. currentTonemapping = renderer.toneMapping;
  8709. }
  8710. boxMesh.layers.enableAll();
  8711. // push to the pre-sorted opaque render list
  8712. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8713. } else if ( background && background.isTexture ) {
  8714. if ( planeMesh === undefined ) {
  8715. planeMesh = new Mesh(
  8716. new PlaneGeometry( 2, 2 ),
  8717. new ShaderMaterial( {
  8718. name: 'BackgroundMaterial',
  8719. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8720. vertexShader: ShaderLib.background.vertexShader,
  8721. fragmentShader: ShaderLib.background.fragmentShader,
  8722. side: FrontSide,
  8723. depthTest: false,
  8724. depthWrite: false,
  8725. fog: false
  8726. } )
  8727. );
  8728. planeMesh.geometry.deleteAttribute( 'normal' );
  8729. // add "map" material property so the renderer can evaluate it like for built-in materials
  8730. Object.defineProperty( planeMesh.material, 'map', {
  8731. get: function () {
  8732. return this.uniforms.t2D.value;
  8733. }
  8734. } );
  8735. objects.update( planeMesh );
  8736. }
  8737. planeMesh.material.uniforms.t2D.value = background;
  8738. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8739. planeMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8740. if ( background.matrixAutoUpdate === true ) {
  8741. background.updateMatrix();
  8742. }
  8743. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8744. if ( currentBackground !== background ||
  8745. currentBackgroundVersion !== background.version ||
  8746. currentTonemapping !== renderer.toneMapping ) {
  8747. planeMesh.material.needsUpdate = true;
  8748. currentBackground = background;
  8749. currentBackgroundVersion = background.version;
  8750. currentTonemapping = renderer.toneMapping;
  8751. }
  8752. planeMesh.layers.enableAll();
  8753. // push to the pre-sorted opaque render list
  8754. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8755. }
  8756. }
  8757. function setClear( color, alpha ) {
  8758. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8759. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8760. }
  8761. return {
  8762. getClearColor: function () {
  8763. return clearColor;
  8764. },
  8765. setClearColor: function ( color, alpha = 1 ) {
  8766. clearColor.set( color );
  8767. clearAlpha = alpha;
  8768. setClear( clearColor, clearAlpha );
  8769. },
  8770. getClearAlpha: function () {
  8771. return clearAlpha;
  8772. },
  8773. setClearAlpha: function ( alpha ) {
  8774. clearAlpha = alpha;
  8775. setClear( clearColor, clearAlpha );
  8776. },
  8777. render: render
  8778. };
  8779. }
  8780. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8781. const maxVertexAttributes = gl.getParameter( 34921 );
  8782. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8783. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8784. const bindingStates = {};
  8785. const defaultState = createBindingState( null );
  8786. let currentState = defaultState;
  8787. let forceUpdate = false;
  8788. function setup( object, material, program, geometry, index ) {
  8789. let updateBuffers = false;
  8790. if ( vaoAvailable ) {
  8791. const state = getBindingState( geometry, program, material );
  8792. if ( currentState !== state ) {
  8793. currentState = state;
  8794. bindVertexArrayObject( currentState.object );
  8795. }
  8796. updateBuffers = needsUpdate( object, geometry, program, index );
  8797. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8798. } else {
  8799. const wireframe = ( material.wireframe === true );
  8800. if ( currentState.geometry !== geometry.id ||
  8801. currentState.program !== program.id ||
  8802. currentState.wireframe !== wireframe ) {
  8803. currentState.geometry = geometry.id;
  8804. currentState.program = program.id;
  8805. currentState.wireframe = wireframe;
  8806. updateBuffers = true;
  8807. }
  8808. }
  8809. if ( index !== null ) {
  8810. attributes.update( index, 34963 );
  8811. }
  8812. if ( updateBuffers || forceUpdate ) {
  8813. forceUpdate = false;
  8814. setupVertexAttributes( object, material, program, geometry );
  8815. if ( index !== null ) {
  8816. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8817. }
  8818. }
  8819. }
  8820. function createVertexArrayObject() {
  8821. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8822. return extension.createVertexArrayOES();
  8823. }
  8824. function bindVertexArrayObject( vao ) {
  8825. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8826. return extension.bindVertexArrayOES( vao );
  8827. }
  8828. function deleteVertexArrayObject( vao ) {
  8829. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8830. return extension.deleteVertexArrayOES( vao );
  8831. }
  8832. function getBindingState( geometry, program, material ) {
  8833. const wireframe = ( material.wireframe === true );
  8834. let programMap = bindingStates[ geometry.id ];
  8835. if ( programMap === undefined ) {
  8836. programMap = {};
  8837. bindingStates[ geometry.id ] = programMap;
  8838. }
  8839. let stateMap = programMap[ program.id ];
  8840. if ( stateMap === undefined ) {
  8841. stateMap = {};
  8842. programMap[ program.id ] = stateMap;
  8843. }
  8844. let state = stateMap[ wireframe ];
  8845. if ( state === undefined ) {
  8846. state = createBindingState( createVertexArrayObject() );
  8847. stateMap[ wireframe ] = state;
  8848. }
  8849. return state;
  8850. }
  8851. function createBindingState( vao ) {
  8852. const newAttributes = [];
  8853. const enabledAttributes = [];
  8854. const attributeDivisors = [];
  8855. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8856. newAttributes[ i ] = 0;
  8857. enabledAttributes[ i ] = 0;
  8858. attributeDivisors[ i ] = 0;
  8859. }
  8860. return {
  8861. // for backward compatibility on non-VAO support browser
  8862. geometry: null,
  8863. program: null,
  8864. wireframe: false,
  8865. newAttributes: newAttributes,
  8866. enabledAttributes: enabledAttributes,
  8867. attributeDivisors: attributeDivisors,
  8868. object: vao,
  8869. attributes: {},
  8870. index: null
  8871. };
  8872. }
  8873. function needsUpdate( object, geometry, program, index ) {
  8874. const cachedAttributes = currentState.attributes;
  8875. const geometryAttributes = geometry.attributes;
  8876. let attributesNum = 0;
  8877. const programAttributes = program.getAttributes();
  8878. for ( const name in programAttributes ) {
  8879. const programAttribute = programAttributes[ name ];
  8880. if ( programAttribute.location >= 0 ) {
  8881. const cachedAttribute = cachedAttributes[ name ];
  8882. let geometryAttribute = geometryAttributes[ name ];
  8883. if ( geometryAttribute === undefined ) {
  8884. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8885. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8886. }
  8887. if ( cachedAttribute === undefined ) return true;
  8888. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8889. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8890. attributesNum ++;
  8891. }
  8892. }
  8893. if ( currentState.attributesNum !== attributesNum ) return true;
  8894. if ( currentState.index !== index ) return true;
  8895. return false;
  8896. }
  8897. function saveCache( object, geometry, program, index ) {
  8898. const cache = {};
  8899. const attributes = geometry.attributes;
  8900. let attributesNum = 0;
  8901. const programAttributes = program.getAttributes();
  8902. for ( const name in programAttributes ) {
  8903. const programAttribute = programAttributes[ name ];
  8904. if ( programAttribute.location >= 0 ) {
  8905. let attribute = attributes[ name ];
  8906. if ( attribute === undefined ) {
  8907. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8908. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8909. }
  8910. const data = {};
  8911. data.attribute = attribute;
  8912. if ( attribute && attribute.data ) {
  8913. data.data = attribute.data;
  8914. }
  8915. cache[ name ] = data;
  8916. attributesNum ++;
  8917. }
  8918. }
  8919. currentState.attributes = cache;
  8920. currentState.attributesNum = attributesNum;
  8921. currentState.index = index;
  8922. }
  8923. function initAttributes() {
  8924. const newAttributes = currentState.newAttributes;
  8925. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8926. newAttributes[ i ] = 0;
  8927. }
  8928. }
  8929. function enableAttribute( attribute ) {
  8930. enableAttributeAndDivisor( attribute, 0 );
  8931. }
  8932. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8933. const newAttributes = currentState.newAttributes;
  8934. const enabledAttributes = currentState.enabledAttributes;
  8935. const attributeDivisors = currentState.attributeDivisors;
  8936. newAttributes[ attribute ] = 1;
  8937. if ( enabledAttributes[ attribute ] === 0 ) {
  8938. gl.enableVertexAttribArray( attribute );
  8939. enabledAttributes[ attribute ] = 1;
  8940. }
  8941. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8942. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8943. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8944. attributeDivisors[ attribute ] = meshPerAttribute;
  8945. }
  8946. }
  8947. function disableUnusedAttributes() {
  8948. const newAttributes = currentState.newAttributes;
  8949. const enabledAttributes = currentState.enabledAttributes;
  8950. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8951. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8952. gl.disableVertexAttribArray( i );
  8953. enabledAttributes[ i ] = 0;
  8954. }
  8955. }
  8956. }
  8957. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8958. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8959. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8960. } else {
  8961. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8962. }
  8963. }
  8964. function setupVertexAttributes( object, material, program, geometry ) {
  8965. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8966. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8967. }
  8968. initAttributes();
  8969. const geometryAttributes = geometry.attributes;
  8970. const programAttributes = program.getAttributes();
  8971. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8972. for ( const name in programAttributes ) {
  8973. const programAttribute = programAttributes[ name ];
  8974. if ( programAttribute.location >= 0 ) {
  8975. let geometryAttribute = geometryAttributes[ name ];
  8976. if ( geometryAttribute === undefined ) {
  8977. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8978. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8979. }
  8980. if ( geometryAttribute !== undefined ) {
  8981. const normalized = geometryAttribute.normalized;
  8982. const size = geometryAttribute.itemSize;
  8983. const attribute = attributes.get( geometryAttribute );
  8984. // TODO Attribute may not be available on context restore
  8985. if ( attribute === undefined ) continue;
  8986. const buffer = attribute.buffer;
  8987. const type = attribute.type;
  8988. const bytesPerElement = attribute.bytesPerElement;
  8989. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8990. const data = geometryAttribute.data;
  8991. const stride = data.stride;
  8992. const offset = geometryAttribute.offset;
  8993. if ( data.isInstancedInterleavedBuffer ) {
  8994. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8995. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8996. }
  8997. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8998. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8999. }
  9000. } else {
  9001. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9002. enableAttribute( programAttribute.location + i );
  9003. }
  9004. }
  9005. gl.bindBuffer( 34962, buffer );
  9006. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9007. vertexAttribPointer(
  9008. programAttribute.location + i,
  9009. size / programAttribute.locationSize,
  9010. type,
  9011. normalized,
  9012. stride * bytesPerElement,
  9013. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  9014. );
  9015. }
  9016. } else {
  9017. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9018. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9019. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9020. }
  9021. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9022. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9023. }
  9024. } else {
  9025. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9026. enableAttribute( programAttribute.location + i );
  9027. }
  9028. }
  9029. gl.bindBuffer( 34962, buffer );
  9030. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9031. vertexAttribPointer(
  9032. programAttribute.location + i,
  9033. size / programAttribute.locationSize,
  9034. type,
  9035. normalized,
  9036. size * bytesPerElement,
  9037. ( size / programAttribute.locationSize ) * i * bytesPerElement
  9038. );
  9039. }
  9040. }
  9041. } else if ( materialDefaultAttributeValues !== undefined ) {
  9042. const value = materialDefaultAttributeValues[ name ];
  9043. if ( value !== undefined ) {
  9044. switch ( value.length ) {
  9045. case 2:
  9046. gl.vertexAttrib2fv( programAttribute.location, value );
  9047. break;
  9048. case 3:
  9049. gl.vertexAttrib3fv( programAttribute.location, value );
  9050. break;
  9051. case 4:
  9052. gl.vertexAttrib4fv( programAttribute.location, value );
  9053. break;
  9054. default:
  9055. gl.vertexAttrib1fv( programAttribute.location, value );
  9056. }
  9057. }
  9058. }
  9059. }
  9060. }
  9061. disableUnusedAttributes();
  9062. }
  9063. function dispose() {
  9064. reset();
  9065. for ( const geometryId in bindingStates ) {
  9066. const programMap = bindingStates[ geometryId ];
  9067. for ( const programId in programMap ) {
  9068. const stateMap = programMap[ programId ];
  9069. for ( const wireframe in stateMap ) {
  9070. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9071. delete stateMap[ wireframe ];
  9072. }
  9073. delete programMap[ programId ];
  9074. }
  9075. delete bindingStates[ geometryId ];
  9076. }
  9077. }
  9078. function releaseStatesOfGeometry( geometry ) {
  9079. if ( bindingStates[ geometry.id ] === undefined ) return;
  9080. const programMap = bindingStates[ geometry.id ];
  9081. for ( const programId in programMap ) {
  9082. const stateMap = programMap[ programId ];
  9083. for ( const wireframe in stateMap ) {
  9084. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9085. delete stateMap[ wireframe ];
  9086. }
  9087. delete programMap[ programId ];
  9088. }
  9089. delete bindingStates[ geometry.id ];
  9090. }
  9091. function releaseStatesOfProgram( program ) {
  9092. for ( const geometryId in bindingStates ) {
  9093. const programMap = bindingStates[ geometryId ];
  9094. if ( programMap[ program.id ] === undefined ) continue;
  9095. const stateMap = programMap[ program.id ];
  9096. for ( const wireframe in stateMap ) {
  9097. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9098. delete stateMap[ wireframe ];
  9099. }
  9100. delete programMap[ program.id ];
  9101. }
  9102. }
  9103. function reset() {
  9104. resetDefaultState();
  9105. forceUpdate = true;
  9106. if ( currentState === defaultState ) return;
  9107. currentState = defaultState;
  9108. bindVertexArrayObject( currentState.object );
  9109. }
  9110. // for backward-compatibility
  9111. function resetDefaultState() {
  9112. defaultState.geometry = null;
  9113. defaultState.program = null;
  9114. defaultState.wireframe = false;
  9115. }
  9116. return {
  9117. setup: setup,
  9118. reset: reset,
  9119. resetDefaultState: resetDefaultState,
  9120. dispose: dispose,
  9121. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9122. releaseStatesOfProgram: releaseStatesOfProgram,
  9123. initAttributes: initAttributes,
  9124. enableAttribute: enableAttribute,
  9125. disableUnusedAttributes: disableUnusedAttributes
  9126. };
  9127. }
  9128. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9129. const isWebGL2 = capabilities.isWebGL2;
  9130. let mode;
  9131. function setMode( value ) {
  9132. mode = value;
  9133. }
  9134. function render( start, count ) {
  9135. gl.drawArrays( mode, start, count );
  9136. info.update( count, mode, 1 );
  9137. }
  9138. function renderInstances( start, count, primcount ) {
  9139. if ( primcount === 0 ) return;
  9140. let extension, methodName;
  9141. if ( isWebGL2 ) {
  9142. extension = gl;
  9143. methodName = 'drawArraysInstanced';
  9144. } else {
  9145. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9146. methodName = 'drawArraysInstancedANGLE';
  9147. if ( extension === null ) {
  9148. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9149. return;
  9150. }
  9151. }
  9152. extension[ methodName ]( mode, start, count, primcount );
  9153. info.update( count, mode, primcount );
  9154. }
  9155. //
  9156. this.setMode = setMode;
  9157. this.render = render;
  9158. this.renderInstances = renderInstances;
  9159. }
  9160. function WebGLCapabilities( gl, extensions, parameters ) {
  9161. let maxAnisotropy;
  9162. function getMaxAnisotropy() {
  9163. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9164. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9165. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9166. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9167. } else {
  9168. maxAnisotropy = 0;
  9169. }
  9170. return maxAnisotropy;
  9171. }
  9172. function getMaxPrecision( precision ) {
  9173. if ( precision === 'highp' ) {
  9174. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  9175. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  9176. return 'highp';
  9177. }
  9178. precision = 'mediump';
  9179. }
  9180. if ( precision === 'mediump' ) {
  9181. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  9182. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  9183. return 'mediump';
  9184. }
  9185. }
  9186. return 'lowp';
  9187. }
  9188. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext';
  9189. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9190. const maxPrecision = getMaxPrecision( precision );
  9191. if ( maxPrecision !== precision ) {
  9192. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9193. precision = maxPrecision;
  9194. }
  9195. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  9196. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9197. const maxTextures = gl.getParameter( 34930 );
  9198. const maxVertexTextures = gl.getParameter( 35660 );
  9199. const maxTextureSize = gl.getParameter( 3379 );
  9200. const maxCubemapSize = gl.getParameter( 34076 );
  9201. const maxAttributes = gl.getParameter( 34921 );
  9202. const maxVertexUniforms = gl.getParameter( 36347 );
  9203. const maxVaryings = gl.getParameter( 36348 );
  9204. const maxFragmentUniforms = gl.getParameter( 36349 );
  9205. const vertexTextures = maxVertexTextures > 0;
  9206. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  9207. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9208. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  9209. return {
  9210. isWebGL2: isWebGL2,
  9211. drawBuffers: drawBuffers,
  9212. getMaxAnisotropy: getMaxAnisotropy,
  9213. getMaxPrecision: getMaxPrecision,
  9214. precision: precision,
  9215. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9216. maxTextures: maxTextures,
  9217. maxVertexTextures: maxVertexTextures,
  9218. maxTextureSize: maxTextureSize,
  9219. maxCubemapSize: maxCubemapSize,
  9220. maxAttributes: maxAttributes,
  9221. maxVertexUniforms: maxVertexUniforms,
  9222. maxVaryings: maxVaryings,
  9223. maxFragmentUniforms: maxFragmentUniforms,
  9224. vertexTextures: vertexTextures,
  9225. floatFragmentTextures: floatFragmentTextures,
  9226. floatVertexTextures: floatVertexTextures,
  9227. maxSamples: maxSamples
  9228. };
  9229. }
  9230. function WebGLClipping( properties ) {
  9231. const scope = this;
  9232. let globalState = null,
  9233. numGlobalPlanes = 0,
  9234. localClippingEnabled = false,
  9235. renderingShadows = false;
  9236. const plane = new Plane(),
  9237. viewNormalMatrix = new Matrix3(),
  9238. uniform = { value: null, needsUpdate: false };
  9239. this.uniform = uniform;
  9240. this.numPlanes = 0;
  9241. this.numIntersection = 0;
  9242. this.init = function ( planes, enableLocalClipping ) {
  9243. const enabled =
  9244. planes.length !== 0 ||
  9245. enableLocalClipping ||
  9246. // enable state of previous frame - the clipping code has to
  9247. // run another frame in order to reset the state:
  9248. numGlobalPlanes !== 0 ||
  9249. localClippingEnabled;
  9250. localClippingEnabled = enableLocalClipping;
  9251. numGlobalPlanes = planes.length;
  9252. return enabled;
  9253. };
  9254. this.beginShadows = function () {
  9255. renderingShadows = true;
  9256. projectPlanes( null );
  9257. };
  9258. this.endShadows = function () {
  9259. renderingShadows = false;
  9260. };
  9261. this.setGlobalState = function ( planes, camera ) {
  9262. globalState = projectPlanes( planes, camera, 0 );
  9263. };
  9264. this.setState = function ( material, camera, useCache ) {
  9265. const planes = material.clippingPlanes,
  9266. clipIntersection = material.clipIntersection,
  9267. clipShadows = material.clipShadows;
  9268. const materialProperties = properties.get( material );
  9269. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9270. // there's no local clipping
  9271. if ( renderingShadows ) {
  9272. // there's no global clipping
  9273. projectPlanes( null );
  9274. } else {
  9275. resetGlobalState();
  9276. }
  9277. } else {
  9278. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9279. lGlobal = nGlobal * 4;
  9280. let dstArray = materialProperties.clippingState || null;
  9281. uniform.value = dstArray; // ensure unique state
  9282. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9283. for ( let i = 0; i !== lGlobal; ++ i ) {
  9284. dstArray[ i ] = globalState[ i ];
  9285. }
  9286. materialProperties.clippingState = dstArray;
  9287. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9288. this.numPlanes += nGlobal;
  9289. }
  9290. };
  9291. function resetGlobalState() {
  9292. if ( uniform.value !== globalState ) {
  9293. uniform.value = globalState;
  9294. uniform.needsUpdate = numGlobalPlanes > 0;
  9295. }
  9296. scope.numPlanes = numGlobalPlanes;
  9297. scope.numIntersection = 0;
  9298. }
  9299. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9300. const nPlanes = planes !== null ? planes.length : 0;
  9301. let dstArray = null;
  9302. if ( nPlanes !== 0 ) {
  9303. dstArray = uniform.value;
  9304. if ( skipTransform !== true || dstArray === null ) {
  9305. const flatSize = dstOffset + nPlanes * 4,
  9306. viewMatrix = camera.matrixWorldInverse;
  9307. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9308. if ( dstArray === null || dstArray.length < flatSize ) {
  9309. dstArray = new Float32Array( flatSize );
  9310. }
  9311. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9312. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9313. plane.normal.toArray( dstArray, i4 );
  9314. dstArray[ i4 + 3 ] = plane.constant;
  9315. }
  9316. }
  9317. uniform.value = dstArray;
  9318. uniform.needsUpdate = true;
  9319. }
  9320. scope.numPlanes = nPlanes;
  9321. scope.numIntersection = 0;
  9322. return dstArray;
  9323. }
  9324. }
  9325. function WebGLCubeMaps( renderer ) {
  9326. let cubemaps = new WeakMap();
  9327. function mapTextureMapping( texture, mapping ) {
  9328. if ( mapping === EquirectangularReflectionMapping ) {
  9329. texture.mapping = CubeReflectionMapping;
  9330. } else if ( mapping === EquirectangularRefractionMapping ) {
  9331. texture.mapping = CubeRefractionMapping;
  9332. }
  9333. return texture;
  9334. }
  9335. function get( texture ) {
  9336. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9337. const mapping = texture.mapping;
  9338. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9339. if ( cubemaps.has( texture ) ) {
  9340. const cubemap = cubemaps.get( texture ).texture;
  9341. return mapTextureMapping( cubemap, texture.mapping );
  9342. } else {
  9343. const image = texture.image;
  9344. if ( image && image.height > 0 ) {
  9345. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9346. renderTarget.fromEquirectangularTexture( renderer, texture );
  9347. cubemaps.set( texture, renderTarget );
  9348. texture.addEventListener( 'dispose', onTextureDispose );
  9349. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9350. } else {
  9351. // image not yet ready. try the conversion next frame
  9352. return null;
  9353. }
  9354. }
  9355. }
  9356. }
  9357. return texture;
  9358. }
  9359. function onTextureDispose( event ) {
  9360. const texture = event.target;
  9361. texture.removeEventListener( 'dispose', onTextureDispose );
  9362. const cubemap = cubemaps.get( texture );
  9363. if ( cubemap !== undefined ) {
  9364. cubemaps.delete( texture );
  9365. cubemap.dispose();
  9366. }
  9367. }
  9368. function dispose() {
  9369. cubemaps = new WeakMap();
  9370. }
  9371. return {
  9372. get: get,
  9373. dispose: dispose
  9374. };
  9375. }
  9376. class OrthographicCamera extends Camera {
  9377. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9378. super();
  9379. this.isOrthographicCamera = true;
  9380. this.type = 'OrthographicCamera';
  9381. this.zoom = 1;
  9382. this.view = null;
  9383. this.left = left;
  9384. this.right = right;
  9385. this.top = top;
  9386. this.bottom = bottom;
  9387. this.near = near;
  9388. this.far = far;
  9389. this.updateProjectionMatrix();
  9390. }
  9391. copy( source, recursive ) {
  9392. super.copy( source, recursive );
  9393. this.left = source.left;
  9394. this.right = source.right;
  9395. this.top = source.top;
  9396. this.bottom = source.bottom;
  9397. this.near = source.near;
  9398. this.far = source.far;
  9399. this.zoom = source.zoom;
  9400. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9401. return this;
  9402. }
  9403. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9404. if ( this.view === null ) {
  9405. this.view = {
  9406. enabled: true,
  9407. fullWidth: 1,
  9408. fullHeight: 1,
  9409. offsetX: 0,
  9410. offsetY: 0,
  9411. width: 1,
  9412. height: 1
  9413. };
  9414. }
  9415. this.view.enabled = true;
  9416. this.view.fullWidth = fullWidth;
  9417. this.view.fullHeight = fullHeight;
  9418. this.view.offsetX = x;
  9419. this.view.offsetY = y;
  9420. this.view.width = width;
  9421. this.view.height = height;
  9422. this.updateProjectionMatrix();
  9423. }
  9424. clearViewOffset() {
  9425. if ( this.view !== null ) {
  9426. this.view.enabled = false;
  9427. }
  9428. this.updateProjectionMatrix();
  9429. }
  9430. updateProjectionMatrix() {
  9431. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9432. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9433. const cx = ( this.right + this.left ) / 2;
  9434. const cy = ( this.top + this.bottom ) / 2;
  9435. let left = cx - dx;
  9436. let right = cx + dx;
  9437. let top = cy + dy;
  9438. let bottom = cy - dy;
  9439. if ( this.view !== null && this.view.enabled ) {
  9440. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9441. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9442. left += scaleW * this.view.offsetX;
  9443. right = left + scaleW * this.view.width;
  9444. top -= scaleH * this.view.offsetY;
  9445. bottom = top - scaleH * this.view.height;
  9446. }
  9447. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9448. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9449. }
  9450. toJSON( meta ) {
  9451. const data = super.toJSON( meta );
  9452. data.object.zoom = this.zoom;
  9453. data.object.left = this.left;
  9454. data.object.right = this.right;
  9455. data.object.top = this.top;
  9456. data.object.bottom = this.bottom;
  9457. data.object.near = this.near;
  9458. data.object.far = this.far;
  9459. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9460. return data;
  9461. }
  9462. }
  9463. const LOD_MIN = 4;
  9464. // The standard deviations (radians) associated with the extra mips. These are
  9465. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9466. // geometric shadowing function. These sigma values squared must match the
  9467. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9468. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9469. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9470. // samples and exit early, but not recompile the shader.
  9471. const MAX_SAMPLES = 20;
  9472. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9473. const _clearColor = /*@__PURE__*/ new Color();
  9474. let _oldTarget = null;
  9475. // Golden Ratio
  9476. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9477. const INV_PHI = 1 / PHI;
  9478. // Vertices of a dodecahedron (except the opposites, which represent the
  9479. // same axis), used as axis directions evenly spread on a sphere.
  9480. const _axisDirections = [
  9481. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9482. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9483. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9484. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9485. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9486. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9487. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9488. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9489. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9490. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9491. /**
  9492. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9493. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9494. * blur to be quickly accessed based on material roughness. It is packed into a
  9495. * special CubeUV format that allows us to perform custom interpolation so that
  9496. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9497. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9498. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9499. * higher roughness levels. In this way we maintain resolution to smoothly
  9500. * interpolate diffuse lighting while limiting sampling computation.
  9501. *
  9502. * Paper: Fast, Accurate Image-Based Lighting
  9503. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9504. */
  9505. class PMREMGenerator {
  9506. constructor( renderer ) {
  9507. this._renderer = renderer;
  9508. this._pingPongRenderTarget = null;
  9509. this._lodMax = 0;
  9510. this._cubeSize = 0;
  9511. this._lodPlanes = [];
  9512. this._sizeLods = [];
  9513. this._sigmas = [];
  9514. this._blurMaterial = null;
  9515. this._cubemapMaterial = null;
  9516. this._equirectMaterial = null;
  9517. this._compileMaterial( this._blurMaterial );
  9518. }
  9519. /**
  9520. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9521. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9522. * in radians to be applied to the scene before PMREM generation. Optional near
  9523. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9524. * is placed at the origin).
  9525. */
  9526. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9527. _oldTarget = this._renderer.getRenderTarget();
  9528. this._setSize( 256 );
  9529. const cubeUVRenderTarget = this._allocateTargets();
  9530. cubeUVRenderTarget.depthBuffer = true;
  9531. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9532. if ( sigma > 0 ) {
  9533. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9534. }
  9535. this._applyPMREM( cubeUVRenderTarget );
  9536. this._cleanup( cubeUVRenderTarget );
  9537. return cubeUVRenderTarget;
  9538. }
  9539. /**
  9540. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9541. * or HDR. The ideal input image size is 1k (1024 x 512),
  9542. * as this matches best with the 256 x 256 cubemap output.
  9543. */
  9544. fromEquirectangular( equirectangular, renderTarget = null ) {
  9545. return this._fromTexture( equirectangular, renderTarget );
  9546. }
  9547. /**
  9548. * Generates a PMREM from an cubemap texture, which can be either LDR
  9549. * or HDR. The ideal input cube size is 256 x 256,
  9550. * as this matches best with the 256 x 256 cubemap output.
  9551. */
  9552. fromCubemap( cubemap, renderTarget = null ) {
  9553. return this._fromTexture( cubemap, renderTarget );
  9554. }
  9555. /**
  9556. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9557. * your texture's network fetch for increased concurrency.
  9558. */
  9559. compileCubemapShader() {
  9560. if ( this._cubemapMaterial === null ) {
  9561. this._cubemapMaterial = _getCubemapMaterial();
  9562. this._compileMaterial( this._cubemapMaterial );
  9563. }
  9564. }
  9565. /**
  9566. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9567. * your texture's network fetch for increased concurrency.
  9568. */
  9569. compileEquirectangularShader() {
  9570. if ( this._equirectMaterial === null ) {
  9571. this._equirectMaterial = _getEquirectMaterial();
  9572. this._compileMaterial( this._equirectMaterial );
  9573. }
  9574. }
  9575. /**
  9576. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9577. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9578. * one of them will cause any others to also become unusable.
  9579. */
  9580. dispose() {
  9581. this._dispose();
  9582. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9583. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9584. }
  9585. // private interface
  9586. _setSize( cubeSize ) {
  9587. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9588. this._cubeSize = Math.pow( 2, this._lodMax );
  9589. }
  9590. _dispose() {
  9591. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9592. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9593. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9594. this._lodPlanes[ i ].dispose();
  9595. }
  9596. }
  9597. _cleanup( outputTarget ) {
  9598. this._renderer.setRenderTarget( _oldTarget );
  9599. outputTarget.scissorTest = false;
  9600. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9601. }
  9602. _fromTexture( texture, renderTarget ) {
  9603. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9604. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9605. } else { // Equirectangular
  9606. this._setSize( texture.image.width / 4 );
  9607. }
  9608. _oldTarget = this._renderer.getRenderTarget();
  9609. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9610. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9611. this._applyPMREM( cubeUVRenderTarget );
  9612. this._cleanup( cubeUVRenderTarget );
  9613. return cubeUVRenderTarget;
  9614. }
  9615. _allocateTargets() {
  9616. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9617. const height = 4 * this._cubeSize;
  9618. const params = {
  9619. magFilter: LinearFilter,
  9620. minFilter: LinearFilter,
  9621. generateMipmaps: false,
  9622. type: HalfFloatType,
  9623. format: RGBAFormat,
  9624. encoding: LinearEncoding,
  9625. depthBuffer: false
  9626. };
  9627. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9628. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9629. if ( this._pingPongRenderTarget !== null ) {
  9630. this._dispose();
  9631. }
  9632. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9633. const { _lodMax } = this;
  9634. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9635. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9636. }
  9637. return cubeUVRenderTarget;
  9638. }
  9639. _compileMaterial( material ) {
  9640. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9641. this._renderer.compile( tmpMesh, _flatCamera );
  9642. }
  9643. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9644. const fov = 90;
  9645. const aspect = 1;
  9646. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9647. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9648. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9649. const renderer = this._renderer;
  9650. const originalAutoClear = renderer.autoClear;
  9651. const toneMapping = renderer.toneMapping;
  9652. renderer.getClearColor( _clearColor );
  9653. renderer.toneMapping = NoToneMapping;
  9654. renderer.autoClear = false;
  9655. const backgroundMaterial = new MeshBasicMaterial( {
  9656. name: 'PMREM.Background',
  9657. side: BackSide,
  9658. depthWrite: false,
  9659. depthTest: false,
  9660. } );
  9661. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9662. let useSolidColor = false;
  9663. const background = scene.background;
  9664. if ( background ) {
  9665. if ( background.isColor ) {
  9666. backgroundMaterial.color.copy( background );
  9667. scene.background = null;
  9668. useSolidColor = true;
  9669. }
  9670. } else {
  9671. backgroundMaterial.color.copy( _clearColor );
  9672. useSolidColor = true;
  9673. }
  9674. for ( let i = 0; i < 6; i ++ ) {
  9675. const col = i % 3;
  9676. if ( col === 0 ) {
  9677. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9678. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9679. } else if ( col === 1 ) {
  9680. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9681. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9682. } else {
  9683. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9684. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9685. }
  9686. const size = this._cubeSize;
  9687. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9688. renderer.setRenderTarget( cubeUVRenderTarget );
  9689. if ( useSolidColor ) {
  9690. renderer.render( backgroundBox, cubeCamera );
  9691. }
  9692. renderer.render( scene, cubeCamera );
  9693. }
  9694. backgroundBox.geometry.dispose();
  9695. backgroundBox.material.dispose();
  9696. renderer.toneMapping = toneMapping;
  9697. renderer.autoClear = originalAutoClear;
  9698. scene.background = background;
  9699. }
  9700. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9701. const renderer = this._renderer;
  9702. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9703. if ( isCubeTexture ) {
  9704. if ( this._cubemapMaterial === null ) {
  9705. this._cubemapMaterial = _getCubemapMaterial();
  9706. }
  9707. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9708. } else {
  9709. if ( this._equirectMaterial === null ) {
  9710. this._equirectMaterial = _getEquirectMaterial();
  9711. }
  9712. }
  9713. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9714. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9715. const uniforms = material.uniforms;
  9716. uniforms[ 'envMap' ].value = texture;
  9717. const size = this._cubeSize;
  9718. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9719. renderer.setRenderTarget( cubeUVRenderTarget );
  9720. renderer.render( mesh, _flatCamera );
  9721. }
  9722. _applyPMREM( cubeUVRenderTarget ) {
  9723. const renderer = this._renderer;
  9724. const autoClear = renderer.autoClear;
  9725. renderer.autoClear = false;
  9726. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9727. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9728. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9729. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9730. }
  9731. renderer.autoClear = autoClear;
  9732. }
  9733. /**
  9734. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9735. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9736. * the blur latitudinally (around the poles), and then longitudinally (towards
  9737. * the poles) to approximate the orthogonally-separable blur. It is least
  9738. * accurate at the poles, but still does a decent job.
  9739. */
  9740. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9741. const pingPongRenderTarget = this._pingPongRenderTarget;
  9742. this._halfBlur(
  9743. cubeUVRenderTarget,
  9744. pingPongRenderTarget,
  9745. lodIn,
  9746. lodOut,
  9747. sigma,
  9748. 'latitudinal',
  9749. poleAxis );
  9750. this._halfBlur(
  9751. pingPongRenderTarget,
  9752. cubeUVRenderTarget,
  9753. lodOut,
  9754. lodOut,
  9755. sigma,
  9756. 'longitudinal',
  9757. poleAxis );
  9758. }
  9759. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9760. const renderer = this._renderer;
  9761. const blurMaterial = this._blurMaterial;
  9762. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9763. console.error(
  9764. 'blur direction must be either latitudinal or longitudinal!' );
  9765. }
  9766. // Number of standard deviations at which to cut off the discrete approximation.
  9767. const STANDARD_DEVIATIONS = 3;
  9768. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9769. const blurUniforms = blurMaterial.uniforms;
  9770. const pixels = this._sizeLods[ lodIn ] - 1;
  9771. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9772. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9773. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9774. if ( samples > MAX_SAMPLES ) {
  9775. console.warn( `sigmaRadians, ${
  9776. sigmaRadians}, is too large and will clip, as it requested ${
  9777. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9778. }
  9779. const weights = [];
  9780. let sum = 0;
  9781. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9782. const x = i / sigmaPixels;
  9783. const weight = Math.exp( - x * x / 2 );
  9784. weights.push( weight );
  9785. if ( i === 0 ) {
  9786. sum += weight;
  9787. } else if ( i < samples ) {
  9788. sum += 2 * weight;
  9789. }
  9790. }
  9791. for ( let i = 0; i < weights.length; i ++ ) {
  9792. weights[ i ] = weights[ i ] / sum;
  9793. }
  9794. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9795. blurUniforms[ 'samples' ].value = samples;
  9796. blurUniforms[ 'weights' ].value = weights;
  9797. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9798. if ( poleAxis ) {
  9799. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9800. }
  9801. const { _lodMax } = this;
  9802. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9803. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9804. const outputSize = this._sizeLods[ lodOut ];
  9805. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9806. const y = 4 * ( this._cubeSize - outputSize );
  9807. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9808. renderer.setRenderTarget( targetOut );
  9809. renderer.render( blurMesh, _flatCamera );
  9810. }
  9811. }
  9812. function _createPlanes( lodMax ) {
  9813. const lodPlanes = [];
  9814. const sizeLods = [];
  9815. const sigmas = [];
  9816. let lod = lodMax;
  9817. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9818. for ( let i = 0; i < totalLods; i ++ ) {
  9819. const sizeLod = Math.pow( 2, lod );
  9820. sizeLods.push( sizeLod );
  9821. let sigma = 1.0 / sizeLod;
  9822. if ( i > lodMax - LOD_MIN ) {
  9823. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9824. } else if ( i === 0 ) {
  9825. sigma = 0;
  9826. }
  9827. sigmas.push( sigma );
  9828. const texelSize = 1.0 / ( sizeLod - 2 );
  9829. const min = - texelSize;
  9830. const max = 1 + texelSize;
  9831. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9832. const cubeFaces = 6;
  9833. const vertices = 6;
  9834. const positionSize = 3;
  9835. const uvSize = 2;
  9836. const faceIndexSize = 1;
  9837. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9838. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9839. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9840. for ( let face = 0; face < cubeFaces; face ++ ) {
  9841. const x = ( face % 3 ) * 2 / 3 - 1;
  9842. const y = face > 2 ? 0 : - 1;
  9843. const coordinates = [
  9844. x, y, 0,
  9845. x + 2 / 3, y, 0,
  9846. x + 2 / 3, y + 1, 0,
  9847. x, y, 0,
  9848. x + 2 / 3, y + 1, 0,
  9849. x, y + 1, 0
  9850. ];
  9851. position.set( coordinates, positionSize * vertices * face );
  9852. uv.set( uv1, uvSize * vertices * face );
  9853. const fill = [ face, face, face, face, face, face ];
  9854. faceIndex.set( fill, faceIndexSize * vertices * face );
  9855. }
  9856. const planes = new BufferGeometry();
  9857. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9858. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9859. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9860. lodPlanes.push( planes );
  9861. if ( lod > LOD_MIN ) {
  9862. lod --;
  9863. }
  9864. }
  9865. return { lodPlanes, sizeLods, sigmas };
  9866. }
  9867. function _createRenderTarget( width, height, params ) {
  9868. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9869. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9870. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9871. cubeUVRenderTarget.scissorTest = true;
  9872. return cubeUVRenderTarget;
  9873. }
  9874. function _setViewport( target, x, y, width, height ) {
  9875. target.viewport.set( x, y, width, height );
  9876. target.scissor.set( x, y, width, height );
  9877. }
  9878. function _getBlurShader( lodMax, width, height ) {
  9879. const weights = new Float32Array( MAX_SAMPLES );
  9880. const poleAxis = new Vector3( 0, 1, 0 );
  9881. const shaderMaterial = new ShaderMaterial( {
  9882. name: 'SphericalGaussianBlur',
  9883. defines: {
  9884. 'n': MAX_SAMPLES,
  9885. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9886. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9887. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9888. },
  9889. uniforms: {
  9890. 'envMap': { value: null },
  9891. 'samples': { value: 1 },
  9892. 'weights': { value: weights },
  9893. 'latitudinal': { value: false },
  9894. 'dTheta': { value: 0 },
  9895. 'mipInt': { value: 0 },
  9896. 'poleAxis': { value: poleAxis }
  9897. },
  9898. vertexShader: _getCommonVertexShader(),
  9899. fragmentShader: /* glsl */`
  9900. precision mediump float;
  9901. precision mediump int;
  9902. varying vec3 vOutputDirection;
  9903. uniform sampler2D envMap;
  9904. uniform int samples;
  9905. uniform float weights[ n ];
  9906. uniform bool latitudinal;
  9907. uniform float dTheta;
  9908. uniform float mipInt;
  9909. uniform vec3 poleAxis;
  9910. #define ENVMAP_TYPE_CUBE_UV
  9911. #include <cube_uv_reflection_fragment>
  9912. vec3 getSample( float theta, vec3 axis ) {
  9913. float cosTheta = cos( theta );
  9914. // Rodrigues' axis-angle rotation
  9915. vec3 sampleDirection = vOutputDirection * cosTheta
  9916. + cross( axis, vOutputDirection ) * sin( theta )
  9917. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9918. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9919. }
  9920. void main() {
  9921. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9922. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9923. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9924. }
  9925. axis = normalize( axis );
  9926. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9927. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9928. for ( int i = 1; i < n; i++ ) {
  9929. if ( i >= samples ) {
  9930. break;
  9931. }
  9932. float theta = dTheta * float( i );
  9933. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9934. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9935. }
  9936. }
  9937. `,
  9938. blending: NoBlending,
  9939. depthTest: false,
  9940. depthWrite: false
  9941. } );
  9942. return shaderMaterial;
  9943. }
  9944. function _getEquirectMaterial() {
  9945. return new ShaderMaterial( {
  9946. name: 'EquirectangularToCubeUV',
  9947. uniforms: {
  9948. 'envMap': { value: null }
  9949. },
  9950. vertexShader: _getCommonVertexShader(),
  9951. fragmentShader: /* glsl */`
  9952. precision mediump float;
  9953. precision mediump int;
  9954. varying vec3 vOutputDirection;
  9955. uniform sampler2D envMap;
  9956. #include <common>
  9957. void main() {
  9958. vec3 outputDirection = normalize( vOutputDirection );
  9959. vec2 uv = equirectUv( outputDirection );
  9960. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9961. }
  9962. `,
  9963. blending: NoBlending,
  9964. depthTest: false,
  9965. depthWrite: false
  9966. } );
  9967. }
  9968. function _getCubemapMaterial() {
  9969. return new ShaderMaterial( {
  9970. name: 'CubemapToCubeUV',
  9971. uniforms: {
  9972. 'envMap': { value: null },
  9973. 'flipEnvMap': { value: - 1 }
  9974. },
  9975. vertexShader: _getCommonVertexShader(),
  9976. fragmentShader: /* glsl */`
  9977. precision mediump float;
  9978. precision mediump int;
  9979. uniform float flipEnvMap;
  9980. varying vec3 vOutputDirection;
  9981. uniform samplerCube envMap;
  9982. void main() {
  9983. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9984. }
  9985. `,
  9986. blending: NoBlending,
  9987. depthTest: false,
  9988. depthWrite: false
  9989. } );
  9990. }
  9991. function _getCommonVertexShader() {
  9992. return /* glsl */`
  9993. precision mediump float;
  9994. precision mediump int;
  9995. attribute float faceIndex;
  9996. varying vec3 vOutputDirection;
  9997. // RH coordinate system; PMREM face-indexing convention
  9998. vec3 getDirection( vec2 uv, float face ) {
  9999. uv = 2.0 * uv - 1.0;
  10000. vec3 direction = vec3( uv, 1.0 );
  10001. if ( face == 0.0 ) {
  10002. direction = direction.zyx; // ( 1, v, u ) pos x
  10003. } else if ( face == 1.0 ) {
  10004. direction = direction.xzy;
  10005. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10006. } else if ( face == 2.0 ) {
  10007. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10008. } else if ( face == 3.0 ) {
  10009. direction = direction.zyx;
  10010. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10011. } else if ( face == 4.0 ) {
  10012. direction = direction.xzy;
  10013. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10014. } else if ( face == 5.0 ) {
  10015. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10016. }
  10017. return direction;
  10018. }
  10019. void main() {
  10020. vOutputDirection = getDirection( uv, faceIndex );
  10021. gl_Position = vec4( position, 1.0 );
  10022. }
  10023. `;
  10024. }
  10025. function WebGLCubeUVMaps( renderer ) {
  10026. let cubeUVmaps = new WeakMap();
  10027. let pmremGenerator = null;
  10028. function get( texture ) {
  10029. if ( texture && texture.isTexture ) {
  10030. const mapping = texture.mapping;
  10031. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10032. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10033. // equirect/cube map to cubeUV conversion
  10034. if ( isEquirectMap || isCubeMap ) {
  10035. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  10036. texture.needsPMREMUpdate = false;
  10037. let renderTarget = cubeUVmaps.get( texture );
  10038. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10039. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10040. cubeUVmaps.set( texture, renderTarget );
  10041. return renderTarget.texture;
  10042. } else {
  10043. if ( cubeUVmaps.has( texture ) ) {
  10044. return cubeUVmaps.get( texture ).texture;
  10045. } else {
  10046. const image = texture.image;
  10047. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10048. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10049. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10050. cubeUVmaps.set( texture, renderTarget );
  10051. texture.addEventListener( 'dispose', onTextureDispose );
  10052. return renderTarget.texture;
  10053. } else {
  10054. // image not yet ready. try the conversion next frame
  10055. return null;
  10056. }
  10057. }
  10058. }
  10059. }
  10060. }
  10061. return texture;
  10062. }
  10063. function isCubeTextureComplete( image ) {
  10064. let count = 0;
  10065. const length = 6;
  10066. for ( let i = 0; i < length; i ++ ) {
  10067. if ( image[ i ] !== undefined ) count ++;
  10068. }
  10069. return count === length;
  10070. }
  10071. function onTextureDispose( event ) {
  10072. const texture = event.target;
  10073. texture.removeEventListener( 'dispose', onTextureDispose );
  10074. const cubemapUV = cubeUVmaps.get( texture );
  10075. if ( cubemapUV !== undefined ) {
  10076. cubeUVmaps.delete( texture );
  10077. cubemapUV.dispose();
  10078. }
  10079. }
  10080. function dispose() {
  10081. cubeUVmaps = new WeakMap();
  10082. if ( pmremGenerator !== null ) {
  10083. pmremGenerator.dispose();
  10084. pmremGenerator = null;
  10085. }
  10086. }
  10087. return {
  10088. get: get,
  10089. dispose: dispose
  10090. };
  10091. }
  10092. function WebGLExtensions( gl ) {
  10093. const extensions = {};
  10094. function getExtension( name ) {
  10095. if ( extensions[ name ] !== undefined ) {
  10096. return extensions[ name ];
  10097. }
  10098. let extension;
  10099. switch ( name ) {
  10100. case 'WEBGL_depth_texture':
  10101. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10102. break;
  10103. case 'EXT_texture_filter_anisotropic':
  10104. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10105. break;
  10106. case 'WEBGL_compressed_texture_s3tc':
  10107. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10108. break;
  10109. case 'WEBGL_compressed_texture_pvrtc':
  10110. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10111. break;
  10112. default:
  10113. extension = gl.getExtension( name );
  10114. }
  10115. extensions[ name ] = extension;
  10116. return extension;
  10117. }
  10118. return {
  10119. has: function ( name ) {
  10120. return getExtension( name ) !== null;
  10121. },
  10122. init: function ( capabilities ) {
  10123. if ( capabilities.isWebGL2 ) {
  10124. getExtension( 'EXT_color_buffer_float' );
  10125. } else {
  10126. getExtension( 'WEBGL_depth_texture' );
  10127. getExtension( 'OES_texture_float' );
  10128. getExtension( 'OES_texture_half_float' );
  10129. getExtension( 'OES_texture_half_float_linear' );
  10130. getExtension( 'OES_standard_derivatives' );
  10131. getExtension( 'OES_element_index_uint' );
  10132. getExtension( 'OES_vertex_array_object' );
  10133. getExtension( 'ANGLE_instanced_arrays' );
  10134. }
  10135. getExtension( 'OES_texture_float_linear' );
  10136. getExtension( 'EXT_color_buffer_half_float' );
  10137. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10138. },
  10139. get: function ( name ) {
  10140. const extension = getExtension( name );
  10141. if ( extension === null ) {
  10142. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10143. }
  10144. return extension;
  10145. }
  10146. };
  10147. }
  10148. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10149. const geometries = {};
  10150. const wireframeAttributes = new WeakMap();
  10151. function onGeometryDispose( event ) {
  10152. const geometry = event.target;
  10153. if ( geometry.index !== null ) {
  10154. attributes.remove( geometry.index );
  10155. }
  10156. for ( const name in geometry.attributes ) {
  10157. attributes.remove( geometry.attributes[ name ] );
  10158. }
  10159. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10160. delete geometries[ geometry.id ];
  10161. const attribute = wireframeAttributes.get( geometry );
  10162. if ( attribute ) {
  10163. attributes.remove( attribute );
  10164. wireframeAttributes.delete( geometry );
  10165. }
  10166. bindingStates.releaseStatesOfGeometry( geometry );
  10167. if ( geometry.isInstancedBufferGeometry === true ) {
  10168. delete geometry._maxInstanceCount;
  10169. }
  10170. //
  10171. info.memory.geometries --;
  10172. }
  10173. function get( object, geometry ) {
  10174. if ( geometries[ geometry.id ] === true ) return geometry;
  10175. geometry.addEventListener( 'dispose', onGeometryDispose );
  10176. geometries[ geometry.id ] = true;
  10177. info.memory.geometries ++;
  10178. return geometry;
  10179. }
  10180. function update( geometry ) {
  10181. const geometryAttributes = geometry.attributes;
  10182. // Updating index buffer in VAO now. See WebGLBindingStates.
  10183. for ( const name in geometryAttributes ) {
  10184. attributes.update( geometryAttributes[ name ], 34962 );
  10185. }
  10186. // morph targets
  10187. const morphAttributes = geometry.morphAttributes;
  10188. for ( const name in morphAttributes ) {
  10189. const array = morphAttributes[ name ];
  10190. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10191. attributes.update( array[ i ], 34962 );
  10192. }
  10193. }
  10194. }
  10195. function updateWireframeAttribute( geometry ) {
  10196. const indices = [];
  10197. const geometryIndex = geometry.index;
  10198. const geometryPosition = geometry.attributes.position;
  10199. let version = 0;
  10200. if ( geometryIndex !== null ) {
  10201. const array = geometryIndex.array;
  10202. version = geometryIndex.version;
  10203. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10204. const a = array[ i + 0 ];
  10205. const b = array[ i + 1 ];
  10206. const c = array[ i + 2 ];
  10207. indices.push( a, b, b, c, c, a );
  10208. }
  10209. } else {
  10210. const array = geometryPosition.array;
  10211. version = geometryPosition.version;
  10212. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10213. const a = i + 0;
  10214. const b = i + 1;
  10215. const c = i + 2;
  10216. indices.push( a, b, b, c, c, a );
  10217. }
  10218. }
  10219. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10220. attribute.version = version;
  10221. // Updating index buffer in VAO now. See WebGLBindingStates
  10222. //
  10223. const previousAttribute = wireframeAttributes.get( geometry );
  10224. if ( previousAttribute ) attributes.remove( previousAttribute );
  10225. //
  10226. wireframeAttributes.set( geometry, attribute );
  10227. }
  10228. function getWireframeAttribute( geometry ) {
  10229. const currentAttribute = wireframeAttributes.get( geometry );
  10230. if ( currentAttribute ) {
  10231. const geometryIndex = geometry.index;
  10232. if ( geometryIndex !== null ) {
  10233. // if the attribute is obsolete, create a new one
  10234. if ( currentAttribute.version < geometryIndex.version ) {
  10235. updateWireframeAttribute( geometry );
  10236. }
  10237. }
  10238. } else {
  10239. updateWireframeAttribute( geometry );
  10240. }
  10241. return wireframeAttributes.get( geometry );
  10242. }
  10243. return {
  10244. get: get,
  10245. update: update,
  10246. getWireframeAttribute: getWireframeAttribute
  10247. };
  10248. }
  10249. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10250. const isWebGL2 = capabilities.isWebGL2;
  10251. let mode;
  10252. function setMode( value ) {
  10253. mode = value;
  10254. }
  10255. let type, bytesPerElement;
  10256. function setIndex( value ) {
  10257. type = value.type;
  10258. bytesPerElement = value.bytesPerElement;
  10259. }
  10260. function render( start, count ) {
  10261. gl.drawElements( mode, count, type, start * bytesPerElement );
  10262. info.update( count, mode, 1 );
  10263. }
  10264. function renderInstances( start, count, primcount ) {
  10265. if ( primcount === 0 ) return;
  10266. let extension, methodName;
  10267. if ( isWebGL2 ) {
  10268. extension = gl;
  10269. methodName = 'drawElementsInstanced';
  10270. } else {
  10271. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10272. methodName = 'drawElementsInstancedANGLE';
  10273. if ( extension === null ) {
  10274. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10275. return;
  10276. }
  10277. }
  10278. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10279. info.update( count, mode, primcount );
  10280. }
  10281. //
  10282. this.setMode = setMode;
  10283. this.setIndex = setIndex;
  10284. this.render = render;
  10285. this.renderInstances = renderInstances;
  10286. }
  10287. function WebGLInfo( gl ) {
  10288. const memory = {
  10289. geometries: 0,
  10290. textures: 0
  10291. };
  10292. const render = {
  10293. frame: 0,
  10294. calls: 0,
  10295. triangles: 0,
  10296. points: 0,
  10297. lines: 0
  10298. };
  10299. function update( count, mode, instanceCount ) {
  10300. render.calls ++;
  10301. switch ( mode ) {
  10302. case 4:
  10303. render.triangles += instanceCount * ( count / 3 );
  10304. break;
  10305. case 1:
  10306. render.lines += instanceCount * ( count / 2 );
  10307. break;
  10308. case 3:
  10309. render.lines += instanceCount * ( count - 1 );
  10310. break;
  10311. case 2:
  10312. render.lines += instanceCount * count;
  10313. break;
  10314. case 0:
  10315. render.points += instanceCount * count;
  10316. break;
  10317. default:
  10318. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10319. break;
  10320. }
  10321. }
  10322. function reset() {
  10323. render.frame ++;
  10324. render.calls = 0;
  10325. render.triangles = 0;
  10326. render.points = 0;
  10327. render.lines = 0;
  10328. }
  10329. return {
  10330. memory: memory,
  10331. render: render,
  10332. programs: null,
  10333. autoReset: true,
  10334. reset: reset,
  10335. update: update
  10336. };
  10337. }
  10338. function numericalSort( a, b ) {
  10339. return a[ 0 ] - b[ 0 ];
  10340. }
  10341. function absNumericalSort( a, b ) {
  10342. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10343. }
  10344. function WebGLMorphtargets( gl, capabilities, textures ) {
  10345. const influencesList = {};
  10346. const morphInfluences = new Float32Array( 8 );
  10347. const morphTextures = new WeakMap();
  10348. const morph = new Vector4();
  10349. const workInfluences = [];
  10350. for ( let i = 0; i < 8; i ++ ) {
  10351. workInfluences[ i ] = [ i, 0 ];
  10352. }
  10353. function update( object, geometry, program ) {
  10354. const objectInfluences = object.morphTargetInfluences;
  10355. if ( capabilities.isWebGL2 === true ) {
  10356. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10357. // into an array of data textures. Each layer represents a single morph target.
  10358. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10359. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10360. let entry = morphTextures.get( geometry );
  10361. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10362. if ( entry !== undefined ) entry.texture.dispose();
  10363. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10364. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10365. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10366. const morphTargets = geometry.morphAttributes.position || [];
  10367. const morphNormals = geometry.morphAttributes.normal || [];
  10368. const morphColors = geometry.morphAttributes.color || [];
  10369. let vertexDataCount = 0;
  10370. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10371. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10372. if ( hasMorphColors === true ) vertexDataCount = 3;
  10373. let width = geometry.attributes.position.count * vertexDataCount;
  10374. let height = 1;
  10375. if ( width > capabilities.maxTextureSize ) {
  10376. height = Math.ceil( width / capabilities.maxTextureSize );
  10377. width = capabilities.maxTextureSize;
  10378. }
  10379. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10380. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10381. texture.type = FloatType;
  10382. texture.needsUpdate = true;
  10383. // fill buffer
  10384. const vertexDataStride = vertexDataCount * 4;
  10385. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10386. const morphTarget = morphTargets[ i ];
  10387. const morphNormal = morphNormals[ i ];
  10388. const morphColor = morphColors[ i ];
  10389. const offset = width * height * 4 * i;
  10390. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10391. const stride = j * vertexDataStride;
  10392. if ( hasMorphPosition === true ) {
  10393. morph.fromBufferAttribute( morphTarget, j );
  10394. buffer[ offset + stride + 0 ] = morph.x;
  10395. buffer[ offset + stride + 1 ] = morph.y;
  10396. buffer[ offset + stride + 2 ] = morph.z;
  10397. buffer[ offset + stride + 3 ] = 0;
  10398. }
  10399. if ( hasMorphNormals === true ) {
  10400. morph.fromBufferAttribute( morphNormal, j );
  10401. buffer[ offset + stride + 4 ] = morph.x;
  10402. buffer[ offset + stride + 5 ] = morph.y;
  10403. buffer[ offset + stride + 6 ] = morph.z;
  10404. buffer[ offset + stride + 7 ] = 0;
  10405. }
  10406. if ( hasMorphColors === true ) {
  10407. morph.fromBufferAttribute( morphColor, j );
  10408. buffer[ offset + stride + 8 ] = morph.x;
  10409. buffer[ offset + stride + 9 ] = morph.y;
  10410. buffer[ offset + stride + 10 ] = morph.z;
  10411. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10412. }
  10413. }
  10414. }
  10415. entry = {
  10416. count: morphTargetsCount,
  10417. texture: texture,
  10418. size: new Vector2( width, height )
  10419. };
  10420. morphTextures.set( geometry, entry );
  10421. function disposeTexture() {
  10422. texture.dispose();
  10423. morphTextures.delete( geometry );
  10424. geometry.removeEventListener( 'dispose', disposeTexture );
  10425. }
  10426. geometry.addEventListener( 'dispose', disposeTexture );
  10427. }
  10428. //
  10429. let morphInfluencesSum = 0;
  10430. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10431. morphInfluencesSum += objectInfluences[ i ];
  10432. }
  10433. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10434. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10435. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10436. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10437. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10438. } else {
  10439. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10440. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10441. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10442. let influences = influencesList[ geometry.id ];
  10443. if ( influences === undefined || influences.length !== length ) {
  10444. // initialise list
  10445. influences = [];
  10446. for ( let i = 0; i < length; i ++ ) {
  10447. influences[ i ] = [ i, 0 ];
  10448. }
  10449. influencesList[ geometry.id ] = influences;
  10450. }
  10451. // Collect influences
  10452. for ( let i = 0; i < length; i ++ ) {
  10453. const influence = influences[ i ];
  10454. influence[ 0 ] = i;
  10455. influence[ 1 ] = objectInfluences[ i ];
  10456. }
  10457. influences.sort( absNumericalSort );
  10458. for ( let i = 0; i < 8; i ++ ) {
  10459. if ( i < length && influences[ i ][ 1 ] ) {
  10460. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10461. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10462. } else {
  10463. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10464. workInfluences[ i ][ 1 ] = 0;
  10465. }
  10466. }
  10467. workInfluences.sort( numericalSort );
  10468. const morphTargets = geometry.morphAttributes.position;
  10469. const morphNormals = geometry.morphAttributes.normal;
  10470. let morphInfluencesSum = 0;
  10471. for ( let i = 0; i < 8; i ++ ) {
  10472. const influence = workInfluences[ i ];
  10473. const index = influence[ 0 ];
  10474. const value = influence[ 1 ];
  10475. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10476. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10477. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10478. }
  10479. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10480. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10481. }
  10482. morphInfluences[ i ] = value;
  10483. morphInfluencesSum += value;
  10484. } else {
  10485. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10486. geometry.deleteAttribute( 'morphTarget' + i );
  10487. }
  10488. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10489. geometry.deleteAttribute( 'morphNormal' + i );
  10490. }
  10491. morphInfluences[ i ] = 0;
  10492. }
  10493. }
  10494. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10495. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10496. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10497. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10498. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10499. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10500. }
  10501. }
  10502. return {
  10503. update: update
  10504. };
  10505. }
  10506. function WebGLObjects( gl, geometries, attributes, info ) {
  10507. let updateMap = new WeakMap();
  10508. function update( object ) {
  10509. const frame = info.render.frame;
  10510. const geometry = object.geometry;
  10511. const buffergeometry = geometries.get( object, geometry );
  10512. // Update once per frame
  10513. if ( updateMap.get( buffergeometry ) !== frame ) {
  10514. geometries.update( buffergeometry );
  10515. updateMap.set( buffergeometry, frame );
  10516. }
  10517. if ( object.isInstancedMesh ) {
  10518. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10519. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10520. }
  10521. attributes.update( object.instanceMatrix, 34962 );
  10522. if ( object.instanceColor !== null ) {
  10523. attributes.update( object.instanceColor, 34962 );
  10524. }
  10525. }
  10526. return buffergeometry;
  10527. }
  10528. function dispose() {
  10529. updateMap = new WeakMap();
  10530. }
  10531. function onInstancedMeshDispose( event ) {
  10532. const instancedMesh = event.target;
  10533. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10534. attributes.remove( instancedMesh.instanceMatrix );
  10535. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10536. }
  10537. return {
  10538. update: update,
  10539. dispose: dispose
  10540. };
  10541. }
  10542. /**
  10543. * Uniforms of a program.
  10544. * Those form a tree structure with a special top-level container for the root,
  10545. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10546. *
  10547. *
  10548. * Properties of inner nodes including the top-level container:
  10549. *
  10550. * .seq - array of nested uniforms
  10551. * .map - nested uniforms by name
  10552. *
  10553. *
  10554. * Methods of all nodes except the top-level container:
  10555. *
  10556. * .setValue( gl, value, [textures] )
  10557. *
  10558. * uploads a uniform value(s)
  10559. * the 'textures' parameter is needed for sampler uniforms
  10560. *
  10561. *
  10562. * Static methods of the top-level container (textures factorizations):
  10563. *
  10564. * .upload( gl, seq, values, textures )
  10565. *
  10566. * sets uniforms in 'seq' to 'values[id].value'
  10567. *
  10568. * .seqWithValue( seq, values ) : filteredSeq
  10569. *
  10570. * filters 'seq' entries with corresponding entry in values
  10571. *
  10572. *
  10573. * Methods of the top-level container (textures factorizations):
  10574. *
  10575. * .setValue( gl, name, value, textures )
  10576. *
  10577. * sets uniform with name 'name' to 'value'
  10578. *
  10579. * .setOptional( gl, obj, prop )
  10580. *
  10581. * like .set for an optional property of the object
  10582. *
  10583. */
  10584. const emptyTexture = /*@__PURE__*/ new Texture();
  10585. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10586. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10587. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10588. // --- Utilities ---
  10589. // Array Caches (provide typed arrays for temporary by size)
  10590. const arrayCacheF32 = [];
  10591. const arrayCacheI32 = [];
  10592. // Float32Array caches used for uploading Matrix uniforms
  10593. const mat4array = new Float32Array( 16 );
  10594. const mat3array = new Float32Array( 9 );
  10595. const mat2array = new Float32Array( 4 );
  10596. // Flattening for arrays of vectors and matrices
  10597. function flatten( array, nBlocks, blockSize ) {
  10598. const firstElem = array[ 0 ];
  10599. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10600. // unoptimized: ! isNaN( firstElem )
  10601. // see http://jacksondunstan.com/articles/983
  10602. const n = nBlocks * blockSize;
  10603. let r = arrayCacheF32[ n ];
  10604. if ( r === undefined ) {
  10605. r = new Float32Array( n );
  10606. arrayCacheF32[ n ] = r;
  10607. }
  10608. if ( nBlocks !== 0 ) {
  10609. firstElem.toArray( r, 0 );
  10610. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10611. offset += blockSize;
  10612. array[ i ].toArray( r, offset );
  10613. }
  10614. }
  10615. return r;
  10616. }
  10617. function arraysEqual( a, b ) {
  10618. if ( a.length !== b.length ) return false;
  10619. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10620. if ( a[ i ] !== b[ i ] ) return false;
  10621. }
  10622. return true;
  10623. }
  10624. function copyArray( a, b ) {
  10625. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10626. a[ i ] = b[ i ];
  10627. }
  10628. }
  10629. // Texture unit allocation
  10630. function allocTexUnits( textures, n ) {
  10631. let r = arrayCacheI32[ n ];
  10632. if ( r === undefined ) {
  10633. r = new Int32Array( n );
  10634. arrayCacheI32[ n ] = r;
  10635. }
  10636. for ( let i = 0; i !== n; ++ i ) {
  10637. r[ i ] = textures.allocateTextureUnit();
  10638. }
  10639. return r;
  10640. }
  10641. // --- Setters ---
  10642. // Note: Defining these methods externally, because they come in a bunch
  10643. // and this way their names minify.
  10644. // Single scalar
  10645. function setValueV1f( gl, v ) {
  10646. const cache = this.cache;
  10647. if ( cache[ 0 ] === v ) return;
  10648. gl.uniform1f( this.addr, v );
  10649. cache[ 0 ] = v;
  10650. }
  10651. // Single float vector (from flat array or THREE.VectorN)
  10652. function setValueV2f( gl, v ) {
  10653. const cache = this.cache;
  10654. if ( v.x !== undefined ) {
  10655. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10656. gl.uniform2f( this.addr, v.x, v.y );
  10657. cache[ 0 ] = v.x;
  10658. cache[ 1 ] = v.y;
  10659. }
  10660. } else {
  10661. if ( arraysEqual( cache, v ) ) return;
  10662. gl.uniform2fv( this.addr, v );
  10663. copyArray( cache, v );
  10664. }
  10665. }
  10666. function setValueV3f( gl, v ) {
  10667. const cache = this.cache;
  10668. if ( v.x !== undefined ) {
  10669. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10670. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10671. cache[ 0 ] = v.x;
  10672. cache[ 1 ] = v.y;
  10673. cache[ 2 ] = v.z;
  10674. }
  10675. } else if ( v.r !== undefined ) {
  10676. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10677. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10678. cache[ 0 ] = v.r;
  10679. cache[ 1 ] = v.g;
  10680. cache[ 2 ] = v.b;
  10681. }
  10682. } else {
  10683. if ( arraysEqual( cache, v ) ) return;
  10684. gl.uniform3fv( this.addr, v );
  10685. copyArray( cache, v );
  10686. }
  10687. }
  10688. function setValueV4f( gl, v ) {
  10689. const cache = this.cache;
  10690. if ( v.x !== undefined ) {
  10691. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10692. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10693. cache[ 0 ] = v.x;
  10694. cache[ 1 ] = v.y;
  10695. cache[ 2 ] = v.z;
  10696. cache[ 3 ] = v.w;
  10697. }
  10698. } else {
  10699. if ( arraysEqual( cache, v ) ) return;
  10700. gl.uniform4fv( this.addr, v );
  10701. copyArray( cache, v );
  10702. }
  10703. }
  10704. // Single matrix (from flat array or THREE.MatrixN)
  10705. function setValueM2( gl, v ) {
  10706. const cache = this.cache;
  10707. const elements = v.elements;
  10708. if ( elements === undefined ) {
  10709. if ( arraysEqual( cache, v ) ) return;
  10710. gl.uniformMatrix2fv( this.addr, false, v );
  10711. copyArray( cache, v );
  10712. } else {
  10713. if ( arraysEqual( cache, elements ) ) return;
  10714. mat2array.set( elements );
  10715. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10716. copyArray( cache, elements );
  10717. }
  10718. }
  10719. function setValueM3( gl, v ) {
  10720. const cache = this.cache;
  10721. const elements = v.elements;
  10722. if ( elements === undefined ) {
  10723. if ( arraysEqual( cache, v ) ) return;
  10724. gl.uniformMatrix3fv( this.addr, false, v );
  10725. copyArray( cache, v );
  10726. } else {
  10727. if ( arraysEqual( cache, elements ) ) return;
  10728. mat3array.set( elements );
  10729. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10730. copyArray( cache, elements );
  10731. }
  10732. }
  10733. function setValueM4( gl, v ) {
  10734. const cache = this.cache;
  10735. const elements = v.elements;
  10736. if ( elements === undefined ) {
  10737. if ( arraysEqual( cache, v ) ) return;
  10738. gl.uniformMatrix4fv( this.addr, false, v );
  10739. copyArray( cache, v );
  10740. } else {
  10741. if ( arraysEqual( cache, elements ) ) return;
  10742. mat4array.set( elements );
  10743. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10744. copyArray( cache, elements );
  10745. }
  10746. }
  10747. // Single integer / boolean
  10748. function setValueV1i( gl, v ) {
  10749. const cache = this.cache;
  10750. if ( cache[ 0 ] === v ) return;
  10751. gl.uniform1i( this.addr, v );
  10752. cache[ 0 ] = v;
  10753. }
  10754. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10755. function setValueV2i( gl, v ) {
  10756. const cache = this.cache;
  10757. if ( v.x !== undefined ) {
  10758. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10759. gl.uniform2i( this.addr, v.x, v.y );
  10760. cache[ 0 ] = v.x;
  10761. cache[ 1 ] = v.y;
  10762. }
  10763. } else {
  10764. if ( arraysEqual( cache, v ) ) return;
  10765. gl.uniform2iv( this.addr, v );
  10766. copyArray( cache, v );
  10767. }
  10768. }
  10769. function setValueV3i( gl, v ) {
  10770. const cache = this.cache;
  10771. if ( v.x !== undefined ) {
  10772. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10773. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10774. cache[ 0 ] = v.x;
  10775. cache[ 1 ] = v.y;
  10776. cache[ 2 ] = v.z;
  10777. }
  10778. } else {
  10779. if ( arraysEqual( cache, v ) ) return;
  10780. gl.uniform3iv( this.addr, v );
  10781. copyArray( cache, v );
  10782. }
  10783. }
  10784. function setValueV4i( gl, v ) {
  10785. const cache = this.cache;
  10786. if ( v.x !== undefined ) {
  10787. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10788. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  10789. cache[ 0 ] = v.x;
  10790. cache[ 1 ] = v.y;
  10791. cache[ 2 ] = v.z;
  10792. cache[ 3 ] = v.w;
  10793. }
  10794. } else {
  10795. if ( arraysEqual( cache, v ) ) return;
  10796. gl.uniform4iv( this.addr, v );
  10797. copyArray( cache, v );
  10798. }
  10799. }
  10800. // Single unsigned integer
  10801. function setValueV1ui( gl, v ) {
  10802. const cache = this.cache;
  10803. if ( cache[ 0 ] === v ) return;
  10804. gl.uniform1ui( this.addr, v );
  10805. cache[ 0 ] = v;
  10806. }
  10807. // Single unsigned integer vector (from flat array or THREE.VectorN)
  10808. function setValueV2ui( gl, v ) {
  10809. const cache = this.cache;
  10810. if ( v.x !== undefined ) {
  10811. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10812. gl.uniform2ui( this.addr, v.x, v.y );
  10813. cache[ 0 ] = v.x;
  10814. cache[ 1 ] = v.y;
  10815. }
  10816. } else {
  10817. if ( arraysEqual( cache, v ) ) return;
  10818. gl.uniform2uiv( this.addr, v );
  10819. copyArray( cache, v );
  10820. }
  10821. }
  10822. function setValueV3ui( gl, v ) {
  10823. const cache = this.cache;
  10824. if ( v.x !== undefined ) {
  10825. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10826. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  10827. cache[ 0 ] = v.x;
  10828. cache[ 1 ] = v.y;
  10829. cache[ 2 ] = v.z;
  10830. }
  10831. } else {
  10832. if ( arraysEqual( cache, v ) ) return;
  10833. gl.uniform3uiv( this.addr, v );
  10834. copyArray( cache, v );
  10835. }
  10836. }
  10837. function setValueV4ui( gl, v ) {
  10838. const cache = this.cache;
  10839. if ( v.x !== undefined ) {
  10840. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10841. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  10842. cache[ 0 ] = v.x;
  10843. cache[ 1 ] = v.y;
  10844. cache[ 2 ] = v.z;
  10845. cache[ 3 ] = v.w;
  10846. }
  10847. } else {
  10848. if ( arraysEqual( cache, v ) ) return;
  10849. gl.uniform4uiv( this.addr, v );
  10850. copyArray( cache, v );
  10851. }
  10852. }
  10853. // Single texture (2D / Cube)
  10854. function setValueT1( gl, v, textures ) {
  10855. const cache = this.cache;
  10856. const unit = textures.allocateTextureUnit();
  10857. if ( cache[ 0 ] !== unit ) {
  10858. gl.uniform1i( this.addr, unit );
  10859. cache[ 0 ] = unit;
  10860. }
  10861. textures.setTexture2D( v || emptyTexture, unit );
  10862. }
  10863. function setValueT3D1( gl, v, textures ) {
  10864. const cache = this.cache;
  10865. const unit = textures.allocateTextureUnit();
  10866. if ( cache[ 0 ] !== unit ) {
  10867. gl.uniform1i( this.addr, unit );
  10868. cache[ 0 ] = unit;
  10869. }
  10870. textures.setTexture3D( v || empty3dTexture, unit );
  10871. }
  10872. function setValueT6( gl, v, textures ) {
  10873. const cache = this.cache;
  10874. const unit = textures.allocateTextureUnit();
  10875. if ( cache[ 0 ] !== unit ) {
  10876. gl.uniform1i( this.addr, unit );
  10877. cache[ 0 ] = unit;
  10878. }
  10879. textures.setTextureCube( v || emptyCubeTexture, unit );
  10880. }
  10881. function setValueT2DArray1( gl, v, textures ) {
  10882. const cache = this.cache;
  10883. const unit = textures.allocateTextureUnit();
  10884. if ( cache[ 0 ] !== unit ) {
  10885. gl.uniform1i( this.addr, unit );
  10886. cache[ 0 ] = unit;
  10887. }
  10888. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10889. }
  10890. // Helper to pick the right setter for the singular case
  10891. function getSingularSetter( type ) {
  10892. switch ( type ) {
  10893. case 0x1406: return setValueV1f; // FLOAT
  10894. case 0x8b50: return setValueV2f; // _VEC2
  10895. case 0x8b51: return setValueV3f; // _VEC3
  10896. case 0x8b52: return setValueV4f; // _VEC4
  10897. case 0x8b5a: return setValueM2; // _MAT2
  10898. case 0x8b5b: return setValueM3; // _MAT3
  10899. case 0x8b5c: return setValueM4; // _MAT4
  10900. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10901. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10902. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10903. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10904. case 0x1405: return setValueV1ui; // UINT
  10905. case 0x8dc6: return setValueV2ui; // _VEC2
  10906. case 0x8dc7: return setValueV3ui; // _VEC3
  10907. case 0x8dc8: return setValueV4ui; // _VEC4
  10908. case 0x8b5e: // SAMPLER_2D
  10909. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10910. case 0x8dca: // INT_SAMPLER_2D
  10911. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10912. case 0x8b62: // SAMPLER_2D_SHADOW
  10913. return setValueT1;
  10914. case 0x8b5f: // SAMPLER_3D
  10915. case 0x8dcb: // INT_SAMPLER_3D
  10916. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10917. return setValueT3D1;
  10918. case 0x8b60: // SAMPLER_CUBE
  10919. case 0x8dcc: // INT_SAMPLER_CUBE
  10920. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10921. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10922. return setValueT6;
  10923. case 0x8dc1: // SAMPLER_2D_ARRAY
  10924. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10925. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10926. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10927. return setValueT2DArray1;
  10928. }
  10929. }
  10930. // Array of scalars
  10931. function setValueV1fArray( gl, v ) {
  10932. gl.uniform1fv( this.addr, v );
  10933. }
  10934. // Array of vectors (from flat array or array of THREE.VectorN)
  10935. function setValueV2fArray( gl, v ) {
  10936. const data = flatten( v, this.size, 2 );
  10937. gl.uniform2fv( this.addr, data );
  10938. }
  10939. function setValueV3fArray( gl, v ) {
  10940. const data = flatten( v, this.size, 3 );
  10941. gl.uniform3fv( this.addr, data );
  10942. }
  10943. function setValueV4fArray( gl, v ) {
  10944. const data = flatten( v, this.size, 4 );
  10945. gl.uniform4fv( this.addr, data );
  10946. }
  10947. // Array of matrices (from flat array or array of THREE.MatrixN)
  10948. function setValueM2Array( gl, v ) {
  10949. const data = flatten( v, this.size, 4 );
  10950. gl.uniformMatrix2fv( this.addr, false, data );
  10951. }
  10952. function setValueM3Array( gl, v ) {
  10953. const data = flatten( v, this.size, 9 );
  10954. gl.uniformMatrix3fv( this.addr, false, data );
  10955. }
  10956. function setValueM4Array( gl, v ) {
  10957. const data = flatten( v, this.size, 16 );
  10958. gl.uniformMatrix4fv( this.addr, false, data );
  10959. }
  10960. // Array of integer / boolean
  10961. function setValueV1iArray( gl, v ) {
  10962. gl.uniform1iv( this.addr, v );
  10963. }
  10964. // Array of integer / boolean vectors (from flat array)
  10965. function setValueV2iArray( gl, v ) {
  10966. gl.uniform2iv( this.addr, v );
  10967. }
  10968. function setValueV3iArray( gl, v ) {
  10969. gl.uniform3iv( this.addr, v );
  10970. }
  10971. function setValueV4iArray( gl, v ) {
  10972. gl.uniform4iv( this.addr, v );
  10973. }
  10974. // Array of unsigned integer
  10975. function setValueV1uiArray( gl, v ) {
  10976. gl.uniform1uiv( this.addr, v );
  10977. }
  10978. // Array of unsigned integer vectors (from flat array)
  10979. function setValueV2uiArray( gl, v ) {
  10980. gl.uniform2uiv( this.addr, v );
  10981. }
  10982. function setValueV3uiArray( gl, v ) {
  10983. gl.uniform3uiv( this.addr, v );
  10984. }
  10985. function setValueV4uiArray( gl, v ) {
  10986. gl.uniform4uiv( this.addr, v );
  10987. }
  10988. // Array of textures (2D / 3D / Cube / 2DArray)
  10989. function setValueT1Array( gl, v, textures ) {
  10990. const cache = this.cache;
  10991. const n = v.length;
  10992. const units = allocTexUnits( textures, n );
  10993. if ( ! arraysEqual( cache, units ) ) {
  10994. gl.uniform1iv( this.addr, units );
  10995. copyArray( cache, units );
  10996. }
  10997. for ( let i = 0; i !== n; ++ i ) {
  10998. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10999. }
  11000. }
  11001. function setValueT3DArray( gl, v, textures ) {
  11002. const cache = this.cache;
  11003. const n = v.length;
  11004. const units = allocTexUnits( textures, n );
  11005. if ( ! arraysEqual( cache, units ) ) {
  11006. gl.uniform1iv( this.addr, units );
  11007. copyArray( cache, units );
  11008. }
  11009. for ( let i = 0; i !== n; ++ i ) {
  11010. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11011. }
  11012. }
  11013. function setValueT6Array( gl, v, textures ) {
  11014. const cache = this.cache;
  11015. const n = v.length;
  11016. const units = allocTexUnits( textures, n );
  11017. if ( ! arraysEqual( cache, units ) ) {
  11018. gl.uniform1iv( this.addr, units );
  11019. copyArray( cache, units );
  11020. }
  11021. for ( let i = 0; i !== n; ++ i ) {
  11022. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11023. }
  11024. }
  11025. function setValueT2DArrayArray( gl, v, textures ) {
  11026. const cache = this.cache;
  11027. const n = v.length;
  11028. const units = allocTexUnits( textures, n );
  11029. if ( ! arraysEqual( cache, units ) ) {
  11030. gl.uniform1iv( this.addr, units );
  11031. copyArray( cache, units );
  11032. }
  11033. for ( let i = 0; i !== n; ++ i ) {
  11034. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11035. }
  11036. }
  11037. // Helper to pick the right setter for a pure (bottom-level) array
  11038. function getPureArraySetter( type ) {
  11039. switch ( type ) {
  11040. case 0x1406: return setValueV1fArray; // FLOAT
  11041. case 0x8b50: return setValueV2fArray; // _VEC2
  11042. case 0x8b51: return setValueV3fArray; // _VEC3
  11043. case 0x8b52: return setValueV4fArray; // _VEC4
  11044. case 0x8b5a: return setValueM2Array; // _MAT2
  11045. case 0x8b5b: return setValueM3Array; // _MAT3
  11046. case 0x8b5c: return setValueM4Array; // _MAT4
  11047. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11048. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11049. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11050. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11051. case 0x1405: return setValueV1uiArray; // UINT
  11052. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11053. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11054. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11055. case 0x8b5e: // SAMPLER_2D
  11056. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11057. case 0x8dca: // INT_SAMPLER_2D
  11058. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11059. case 0x8b62: // SAMPLER_2D_SHADOW
  11060. return setValueT1Array;
  11061. case 0x8b5f: // SAMPLER_3D
  11062. case 0x8dcb: // INT_SAMPLER_3D
  11063. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11064. return setValueT3DArray;
  11065. case 0x8b60: // SAMPLER_CUBE
  11066. case 0x8dcc: // INT_SAMPLER_CUBE
  11067. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11068. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11069. return setValueT6Array;
  11070. case 0x8dc1: // SAMPLER_2D_ARRAY
  11071. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11072. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11073. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11074. return setValueT2DArrayArray;
  11075. }
  11076. }
  11077. // --- Uniform Classes ---
  11078. class SingleUniform {
  11079. constructor( id, activeInfo, addr ) {
  11080. this.id = id;
  11081. this.addr = addr;
  11082. this.cache = [];
  11083. this.setValue = getSingularSetter( activeInfo.type );
  11084. // this.path = activeInfo.name; // DEBUG
  11085. }
  11086. }
  11087. class PureArrayUniform {
  11088. constructor( id, activeInfo, addr ) {
  11089. this.id = id;
  11090. this.addr = addr;
  11091. this.cache = [];
  11092. this.size = activeInfo.size;
  11093. this.setValue = getPureArraySetter( activeInfo.type );
  11094. // this.path = activeInfo.name; // DEBUG
  11095. }
  11096. }
  11097. class StructuredUniform {
  11098. constructor( id ) {
  11099. this.id = id;
  11100. this.seq = [];
  11101. this.map = {};
  11102. }
  11103. setValue( gl, value, textures ) {
  11104. const seq = this.seq;
  11105. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11106. const u = seq[ i ];
  11107. u.setValue( gl, value[ u.id ], textures );
  11108. }
  11109. }
  11110. }
  11111. // --- Top-level ---
  11112. // Parser - builds up the property tree from the path strings
  11113. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11114. // extracts
  11115. // - the identifier (member name or array index)
  11116. // - followed by an optional right bracket (found when array index)
  11117. // - followed by an optional left bracket or dot (type of subscript)
  11118. //
  11119. // Note: These portions can be read in a non-overlapping fashion and
  11120. // allow straightforward parsing of the hierarchy that WebGL encodes
  11121. // in the uniform names.
  11122. function addUniform( container, uniformObject ) {
  11123. container.seq.push( uniformObject );
  11124. container.map[ uniformObject.id ] = uniformObject;
  11125. }
  11126. function parseUniform( activeInfo, addr, container ) {
  11127. const path = activeInfo.name,
  11128. pathLength = path.length;
  11129. // reset RegExp object, because of the early exit of a previous run
  11130. RePathPart.lastIndex = 0;
  11131. while ( true ) {
  11132. const match = RePathPart.exec( path ),
  11133. matchEnd = RePathPart.lastIndex;
  11134. let id = match[ 1 ];
  11135. const idIsIndex = match[ 2 ] === ']',
  11136. subscript = match[ 3 ];
  11137. if ( idIsIndex ) id = id | 0; // convert to integer
  11138. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11139. // bare name or "pure" bottom-level array "[0]" suffix
  11140. addUniform( container, subscript === undefined ?
  11141. new SingleUniform( id, activeInfo, addr ) :
  11142. new PureArrayUniform( id, activeInfo, addr ) );
  11143. break;
  11144. } else {
  11145. // step into inner node / create it in case it doesn't exist
  11146. const map = container.map;
  11147. let next = map[ id ];
  11148. if ( next === undefined ) {
  11149. next = new StructuredUniform( id );
  11150. addUniform( container, next );
  11151. }
  11152. container = next;
  11153. }
  11154. }
  11155. }
  11156. // Root Container
  11157. class WebGLUniforms {
  11158. constructor( gl, program ) {
  11159. this.seq = [];
  11160. this.map = {};
  11161. const n = gl.getProgramParameter( program, 35718 );
  11162. for ( let i = 0; i < n; ++ i ) {
  11163. const info = gl.getActiveUniform( program, i ),
  11164. addr = gl.getUniformLocation( program, info.name );
  11165. parseUniform( info, addr, this );
  11166. }
  11167. }
  11168. setValue( gl, name, value, textures ) {
  11169. const u = this.map[ name ];
  11170. if ( u !== undefined ) u.setValue( gl, value, textures );
  11171. }
  11172. setOptional( gl, object, name ) {
  11173. const v = object[ name ];
  11174. if ( v !== undefined ) this.setValue( gl, name, v );
  11175. }
  11176. static upload( gl, seq, values, textures ) {
  11177. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11178. const u = seq[ i ],
  11179. v = values[ u.id ];
  11180. if ( v.needsUpdate !== false ) {
  11181. // note: always updating when .needsUpdate is undefined
  11182. u.setValue( gl, v.value, textures );
  11183. }
  11184. }
  11185. }
  11186. static seqWithValue( seq, values ) {
  11187. const r = [];
  11188. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11189. const u = seq[ i ];
  11190. if ( u.id in values ) r.push( u );
  11191. }
  11192. return r;
  11193. }
  11194. }
  11195. function WebGLShader( gl, type, string ) {
  11196. const shader = gl.createShader( type );
  11197. gl.shaderSource( shader, string );
  11198. gl.compileShader( shader );
  11199. return shader;
  11200. }
  11201. let programIdCount = 0;
  11202. function handleSource( string, errorLine ) {
  11203. const lines = string.split( '\n' );
  11204. const lines2 = [];
  11205. const from = Math.max( errorLine - 6, 0 );
  11206. const to = Math.min( errorLine + 6, lines.length );
  11207. for ( let i = from; i < to; i ++ ) {
  11208. const line = i + 1;
  11209. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11210. }
  11211. return lines2.join( '\n' );
  11212. }
  11213. function getEncodingComponents( encoding ) {
  11214. switch ( encoding ) {
  11215. case LinearEncoding:
  11216. return [ 'Linear', '( value )' ];
  11217. case sRGBEncoding:
  11218. return [ 'sRGB', '( value )' ];
  11219. default:
  11220. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  11221. return [ 'Linear', '( value )' ];
  11222. }
  11223. }
  11224. function getShaderErrors( gl, shader, type ) {
  11225. const status = gl.getShaderParameter( shader, 35713 );
  11226. const errors = gl.getShaderInfoLog( shader ).trim();
  11227. if ( status && errors === '' ) return '';
  11228. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11229. if ( errorMatches ) {
  11230. // --enable-privileged-webgl-extension
  11231. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11232. const errorLine = parseInt( errorMatches[ 1 ] );
  11233. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11234. } else {
  11235. return errors;
  11236. }
  11237. }
  11238. function getTexelEncodingFunction( functionName, encoding ) {
  11239. const components = getEncodingComponents( encoding );
  11240. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  11241. }
  11242. function getToneMappingFunction( functionName, toneMapping ) {
  11243. let toneMappingName;
  11244. switch ( toneMapping ) {
  11245. case LinearToneMapping:
  11246. toneMappingName = 'Linear';
  11247. break;
  11248. case ReinhardToneMapping:
  11249. toneMappingName = 'Reinhard';
  11250. break;
  11251. case CineonToneMapping:
  11252. toneMappingName = 'OptimizedCineon';
  11253. break;
  11254. case ACESFilmicToneMapping:
  11255. toneMappingName = 'ACESFilmic';
  11256. break;
  11257. case CustomToneMapping:
  11258. toneMappingName = 'Custom';
  11259. break;
  11260. default:
  11261. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11262. toneMappingName = 'Linear';
  11263. }
  11264. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11265. }
  11266. function generateExtensions( parameters ) {
  11267. const chunks = [
  11268. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11269. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11270. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11271. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11272. ];
  11273. return chunks.filter( filterEmptyLine ).join( '\n' );
  11274. }
  11275. function generateDefines( defines ) {
  11276. const chunks = [];
  11277. for ( const name in defines ) {
  11278. const value = defines[ name ];
  11279. if ( value === false ) continue;
  11280. chunks.push( '#define ' + name + ' ' + value );
  11281. }
  11282. return chunks.join( '\n' );
  11283. }
  11284. function fetchAttributeLocations( gl, program ) {
  11285. const attributes = {};
  11286. const n = gl.getProgramParameter( program, 35721 );
  11287. for ( let i = 0; i < n; i ++ ) {
  11288. const info = gl.getActiveAttrib( program, i );
  11289. const name = info.name;
  11290. let locationSize = 1;
  11291. if ( info.type === 35674 ) locationSize = 2;
  11292. if ( info.type === 35675 ) locationSize = 3;
  11293. if ( info.type === 35676 ) locationSize = 4;
  11294. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11295. attributes[ name ] = {
  11296. type: info.type,
  11297. location: gl.getAttribLocation( program, name ),
  11298. locationSize: locationSize
  11299. };
  11300. }
  11301. return attributes;
  11302. }
  11303. function filterEmptyLine( string ) {
  11304. return string !== '';
  11305. }
  11306. function replaceLightNums( string, parameters ) {
  11307. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11308. return string
  11309. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11310. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11311. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11312. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11313. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11314. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11315. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11316. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11317. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11318. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11319. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11320. }
  11321. function replaceClippingPlaneNums( string, parameters ) {
  11322. return string
  11323. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11324. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11325. }
  11326. // Resolve Includes
  11327. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11328. function resolveIncludes( string ) {
  11329. return string.replace( includePattern, includeReplacer );
  11330. }
  11331. function includeReplacer( match, include ) {
  11332. const string = ShaderChunk[ include ];
  11333. if ( string === undefined ) {
  11334. throw new Error( 'Can not resolve #include <' + include + '>' );
  11335. }
  11336. return resolveIncludes( string );
  11337. }
  11338. // Unroll Loops
  11339. 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;
  11340. function unrollLoops( string ) {
  11341. return string.replace( unrollLoopPattern, loopReplacer );
  11342. }
  11343. function loopReplacer( match, start, end, snippet ) {
  11344. let string = '';
  11345. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11346. string += snippet
  11347. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11348. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11349. }
  11350. return string;
  11351. }
  11352. //
  11353. function generatePrecision( parameters ) {
  11354. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11355. if ( parameters.precision === 'highp' ) {
  11356. precisionstring += '\n#define HIGH_PRECISION';
  11357. } else if ( parameters.precision === 'mediump' ) {
  11358. precisionstring += '\n#define MEDIUM_PRECISION';
  11359. } else if ( parameters.precision === 'lowp' ) {
  11360. precisionstring += '\n#define LOW_PRECISION';
  11361. }
  11362. return precisionstring;
  11363. }
  11364. function generateShadowMapTypeDefine( parameters ) {
  11365. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11366. if ( parameters.shadowMapType === PCFShadowMap ) {
  11367. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11368. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11369. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11370. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11371. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11372. }
  11373. return shadowMapTypeDefine;
  11374. }
  11375. function generateEnvMapTypeDefine( parameters ) {
  11376. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11377. if ( parameters.envMap ) {
  11378. switch ( parameters.envMapMode ) {
  11379. case CubeReflectionMapping:
  11380. case CubeRefractionMapping:
  11381. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11382. break;
  11383. case CubeUVReflectionMapping:
  11384. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11385. break;
  11386. }
  11387. }
  11388. return envMapTypeDefine;
  11389. }
  11390. function generateEnvMapModeDefine( parameters ) {
  11391. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11392. if ( parameters.envMap ) {
  11393. switch ( parameters.envMapMode ) {
  11394. case CubeRefractionMapping:
  11395. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11396. break;
  11397. }
  11398. }
  11399. return envMapModeDefine;
  11400. }
  11401. function generateEnvMapBlendingDefine( parameters ) {
  11402. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11403. if ( parameters.envMap ) {
  11404. switch ( parameters.combine ) {
  11405. case MultiplyOperation:
  11406. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11407. break;
  11408. case MixOperation:
  11409. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11410. break;
  11411. case AddOperation:
  11412. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11413. break;
  11414. }
  11415. }
  11416. return envMapBlendingDefine;
  11417. }
  11418. function generateCubeUVSize( parameters ) {
  11419. const imageHeight = parameters.envMapCubeUVHeight;
  11420. if ( imageHeight === null ) return null;
  11421. const maxMip = Math.log2( imageHeight ) - 2;
  11422. const texelHeight = 1.0 / imageHeight;
  11423. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11424. return { texelWidth, texelHeight, maxMip };
  11425. }
  11426. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11427. // TODO Send this event to Three.js DevTools
  11428. // console.log( 'WebGLProgram', cacheKey );
  11429. const gl = renderer.getContext();
  11430. const defines = parameters.defines;
  11431. let vertexShader = parameters.vertexShader;
  11432. let fragmentShader = parameters.fragmentShader;
  11433. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11434. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11435. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11436. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11437. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11438. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11439. const customDefines = generateDefines( defines );
  11440. const program = gl.createProgram();
  11441. let prefixVertex, prefixFragment;
  11442. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11443. if ( parameters.isRawShaderMaterial ) {
  11444. prefixVertex = [
  11445. customDefines
  11446. ].filter( filterEmptyLine ).join( '\n' );
  11447. if ( prefixVertex.length > 0 ) {
  11448. prefixVertex += '\n';
  11449. }
  11450. prefixFragment = [
  11451. customExtensions,
  11452. customDefines
  11453. ].filter( filterEmptyLine ).join( '\n' );
  11454. if ( prefixFragment.length > 0 ) {
  11455. prefixFragment += '\n';
  11456. }
  11457. } else {
  11458. prefixVertex = [
  11459. generatePrecision( parameters ),
  11460. '#define SHADER_NAME ' + parameters.shaderName,
  11461. customDefines,
  11462. parameters.instancing ? '#define USE_INSTANCING' : '',
  11463. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11464. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11465. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11466. parameters.map ? '#define USE_MAP' : '',
  11467. parameters.envMap ? '#define USE_ENVMAP' : '',
  11468. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11469. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11470. parameters.aoMap ? '#define USE_AOMAP' : '',
  11471. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11472. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11473. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11474. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11475. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11476. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11477. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11478. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11479. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11480. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11481. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11482. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11483. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11484. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11485. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11486. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11487. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11488. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11489. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11490. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11491. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11492. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11493. //
  11494. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11495. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11496. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11497. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11498. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11499. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11500. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11501. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11502. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11503. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11504. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11505. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11506. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11507. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11508. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11509. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11510. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11511. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11512. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11513. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11514. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11515. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11516. //
  11517. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11518. parameters.vertexColors ? '#define USE_COLOR' : '',
  11519. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11520. parameters.vertexUvs2 ? '#define USE_UV2' : '',
  11521. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11522. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11523. parameters.skinning ? '#define USE_SKINNING' : '',
  11524. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11525. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11526. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11527. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11528. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11529. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11530. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11531. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11532. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11533. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11534. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11535. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11536. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11537. 'uniform mat4 modelMatrix;',
  11538. 'uniform mat4 modelViewMatrix;',
  11539. 'uniform mat4 projectionMatrix;',
  11540. 'uniform mat4 viewMatrix;',
  11541. 'uniform mat3 normalMatrix;',
  11542. 'uniform vec3 cameraPosition;',
  11543. 'uniform bool isOrthographic;',
  11544. '#ifdef USE_INSTANCING',
  11545. ' attribute mat4 instanceMatrix;',
  11546. '#endif',
  11547. '#ifdef USE_INSTANCING_COLOR',
  11548. ' attribute vec3 instanceColor;',
  11549. '#endif',
  11550. 'attribute vec3 position;',
  11551. 'attribute vec3 normal;',
  11552. 'attribute vec2 uv;',
  11553. '#ifdef USE_TANGENT',
  11554. ' attribute vec4 tangent;',
  11555. '#endif',
  11556. '#if defined( USE_COLOR_ALPHA )',
  11557. ' attribute vec4 color;',
  11558. '#elif defined( USE_COLOR )',
  11559. ' attribute vec3 color;',
  11560. '#endif',
  11561. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11562. ' attribute vec3 morphTarget0;',
  11563. ' attribute vec3 morphTarget1;',
  11564. ' attribute vec3 morphTarget2;',
  11565. ' attribute vec3 morphTarget3;',
  11566. ' #ifdef USE_MORPHNORMALS',
  11567. ' attribute vec3 morphNormal0;',
  11568. ' attribute vec3 morphNormal1;',
  11569. ' attribute vec3 morphNormal2;',
  11570. ' attribute vec3 morphNormal3;',
  11571. ' #else',
  11572. ' attribute vec3 morphTarget4;',
  11573. ' attribute vec3 morphTarget5;',
  11574. ' attribute vec3 morphTarget6;',
  11575. ' attribute vec3 morphTarget7;',
  11576. ' #endif',
  11577. '#endif',
  11578. '#ifdef USE_SKINNING',
  11579. ' attribute vec4 skinIndex;',
  11580. ' attribute vec4 skinWeight;',
  11581. '#endif',
  11582. '\n'
  11583. ].filter( filterEmptyLine ).join( '\n' );
  11584. prefixFragment = [
  11585. customExtensions,
  11586. generatePrecision( parameters ),
  11587. '#define SHADER_NAME ' + parameters.shaderName,
  11588. customDefines,
  11589. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11590. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11591. parameters.map ? '#define USE_MAP' : '',
  11592. parameters.matcap ? '#define USE_MATCAP' : '',
  11593. parameters.envMap ? '#define USE_ENVMAP' : '',
  11594. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11595. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11596. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11597. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11598. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11599. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11600. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11601. parameters.aoMap ? '#define USE_AOMAP' : '',
  11602. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11603. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11604. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11605. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11606. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11607. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11608. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11609. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11610. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11611. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11612. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11613. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11614. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11615. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11616. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11617. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11618. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11619. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11620. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11621. parameters.sheen ? '#define USE_SHEEN' : '',
  11622. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11623. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11624. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11625. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11626. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11627. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11628. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11629. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11630. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11631. parameters.vertexUvs2 ? '#define USE_UV2' : '',
  11632. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11633. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11634. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11635. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11636. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11637. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11638. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11639. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11640. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11641. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11642. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11643. 'uniform mat4 viewMatrix;',
  11644. 'uniform vec3 cameraPosition;',
  11645. 'uniform bool isOrthographic;',
  11646. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11647. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11648. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11649. parameters.dithering ? '#define DITHERING' : '',
  11650. parameters.opaque ? '#define OPAQUE' : '',
  11651. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11652. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11653. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11654. '\n'
  11655. ].filter( filterEmptyLine ).join( '\n' );
  11656. }
  11657. vertexShader = resolveIncludes( vertexShader );
  11658. vertexShader = replaceLightNums( vertexShader, parameters );
  11659. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11660. fragmentShader = resolveIncludes( fragmentShader );
  11661. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11662. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11663. vertexShader = unrollLoops( vertexShader );
  11664. fragmentShader = unrollLoops( fragmentShader );
  11665. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11666. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11667. versionString = '#version 300 es\n';
  11668. prefixVertex = [
  11669. 'precision mediump sampler2DArray;',
  11670. '#define attribute in',
  11671. '#define varying out',
  11672. '#define texture2D texture'
  11673. ].join( '\n' ) + '\n' + prefixVertex;
  11674. prefixFragment = [
  11675. '#define varying in',
  11676. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11677. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11678. '#define gl_FragDepthEXT gl_FragDepth',
  11679. '#define texture2D texture',
  11680. '#define textureCube texture',
  11681. '#define texture2DProj textureProj',
  11682. '#define texture2DLodEXT textureLod',
  11683. '#define texture2DProjLodEXT textureProjLod',
  11684. '#define textureCubeLodEXT textureLod',
  11685. '#define texture2DGradEXT textureGrad',
  11686. '#define texture2DProjGradEXT textureProjGrad',
  11687. '#define textureCubeGradEXT textureGrad'
  11688. ].join( '\n' ) + '\n' + prefixFragment;
  11689. }
  11690. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11691. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11692. // console.log( '*VERTEX*', vertexGlsl );
  11693. // console.log( '*FRAGMENT*', fragmentGlsl );
  11694. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11695. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11696. gl.attachShader( program, glVertexShader );
  11697. gl.attachShader( program, glFragmentShader );
  11698. // Force a particular attribute to index 0.
  11699. if ( parameters.index0AttributeName !== undefined ) {
  11700. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11701. } else if ( parameters.morphTargets === true ) {
  11702. // programs with morphTargets displace position out of attribute 0
  11703. gl.bindAttribLocation( program, 0, 'position' );
  11704. }
  11705. gl.linkProgram( program );
  11706. // check for link errors
  11707. if ( renderer.debug.checkShaderErrors ) {
  11708. const programLog = gl.getProgramInfoLog( program ).trim();
  11709. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11710. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11711. let runnable = true;
  11712. let haveDiagnostics = true;
  11713. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11714. runnable = false;
  11715. if ( typeof renderer.debug.onShaderError === 'function' ) {
  11716. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  11717. } else {
  11718. // default error reporting
  11719. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11720. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11721. console.error(
  11722. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11723. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11724. 'Program Info Log: ' + programLog + '\n' +
  11725. vertexErrors + '\n' +
  11726. fragmentErrors
  11727. );
  11728. }
  11729. } else if ( programLog !== '' ) {
  11730. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11731. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11732. haveDiagnostics = false;
  11733. }
  11734. if ( haveDiagnostics ) {
  11735. this.diagnostics = {
  11736. runnable: runnable,
  11737. programLog: programLog,
  11738. vertexShader: {
  11739. log: vertexLog,
  11740. prefix: prefixVertex
  11741. },
  11742. fragmentShader: {
  11743. log: fragmentLog,
  11744. prefix: prefixFragment
  11745. }
  11746. };
  11747. }
  11748. }
  11749. // Clean up
  11750. // Crashes in iOS9 and iOS10. #18402
  11751. // gl.detachShader( program, glVertexShader );
  11752. // gl.detachShader( program, glFragmentShader );
  11753. gl.deleteShader( glVertexShader );
  11754. gl.deleteShader( glFragmentShader );
  11755. // set up caching for uniform locations
  11756. let cachedUniforms;
  11757. this.getUniforms = function () {
  11758. if ( cachedUniforms === undefined ) {
  11759. cachedUniforms = new WebGLUniforms( gl, program );
  11760. }
  11761. return cachedUniforms;
  11762. };
  11763. // set up caching for attribute locations
  11764. let cachedAttributes;
  11765. this.getAttributes = function () {
  11766. if ( cachedAttributes === undefined ) {
  11767. cachedAttributes = fetchAttributeLocations( gl, program );
  11768. }
  11769. return cachedAttributes;
  11770. };
  11771. // free resource
  11772. this.destroy = function () {
  11773. bindingStates.releaseStatesOfProgram( this );
  11774. gl.deleteProgram( program );
  11775. this.program = undefined;
  11776. };
  11777. //
  11778. this.name = parameters.shaderName;
  11779. this.id = programIdCount ++;
  11780. this.cacheKey = cacheKey;
  11781. this.usedTimes = 1;
  11782. this.program = program;
  11783. this.vertexShader = glVertexShader;
  11784. this.fragmentShader = glFragmentShader;
  11785. return this;
  11786. }
  11787. let _id = 0;
  11788. class WebGLShaderCache {
  11789. constructor() {
  11790. this.shaderCache = new Map();
  11791. this.materialCache = new Map();
  11792. }
  11793. update( material ) {
  11794. const vertexShader = material.vertexShader;
  11795. const fragmentShader = material.fragmentShader;
  11796. const vertexShaderStage = this._getShaderStage( vertexShader );
  11797. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11798. const materialShaders = this._getShaderCacheForMaterial( material );
  11799. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11800. materialShaders.add( vertexShaderStage );
  11801. vertexShaderStage.usedTimes ++;
  11802. }
  11803. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11804. materialShaders.add( fragmentShaderStage );
  11805. fragmentShaderStage.usedTimes ++;
  11806. }
  11807. return this;
  11808. }
  11809. remove( material ) {
  11810. const materialShaders = this.materialCache.get( material );
  11811. for ( const shaderStage of materialShaders ) {
  11812. shaderStage.usedTimes --;
  11813. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11814. }
  11815. this.materialCache.delete( material );
  11816. return this;
  11817. }
  11818. getVertexShaderID( material ) {
  11819. return this._getShaderStage( material.vertexShader ).id;
  11820. }
  11821. getFragmentShaderID( material ) {
  11822. return this._getShaderStage( material.fragmentShader ).id;
  11823. }
  11824. dispose() {
  11825. this.shaderCache.clear();
  11826. this.materialCache.clear();
  11827. }
  11828. _getShaderCacheForMaterial( material ) {
  11829. const cache = this.materialCache;
  11830. let set = cache.get( material );
  11831. if ( set === undefined ) {
  11832. set = new Set();
  11833. cache.set( material, set );
  11834. }
  11835. return set;
  11836. }
  11837. _getShaderStage( code ) {
  11838. const cache = this.shaderCache;
  11839. let stage = cache.get( code );
  11840. if ( stage === undefined ) {
  11841. stage = new WebGLShaderStage( code );
  11842. cache.set( code, stage );
  11843. }
  11844. return stage;
  11845. }
  11846. }
  11847. class WebGLShaderStage {
  11848. constructor( code ) {
  11849. this.id = _id ++;
  11850. this.code = code;
  11851. this.usedTimes = 0;
  11852. }
  11853. }
  11854. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11855. const _programLayers = new Layers();
  11856. const _customShaders = new WebGLShaderCache();
  11857. const programs = [];
  11858. const IS_WEBGL2 = capabilities.isWebGL2;
  11859. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11860. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  11861. let precision = capabilities.precision;
  11862. const shaderIDs = {
  11863. MeshDepthMaterial: 'depth',
  11864. MeshDistanceMaterial: 'distanceRGBA',
  11865. MeshNormalMaterial: 'normal',
  11866. MeshBasicMaterial: 'basic',
  11867. MeshLambertMaterial: 'lambert',
  11868. MeshPhongMaterial: 'phong',
  11869. MeshToonMaterial: 'toon',
  11870. MeshStandardMaterial: 'physical',
  11871. MeshPhysicalMaterial: 'physical',
  11872. MeshMatcapMaterial: 'matcap',
  11873. LineBasicMaterial: 'basic',
  11874. LineDashedMaterial: 'dashed',
  11875. PointsMaterial: 'points',
  11876. ShadowMaterial: 'shadow',
  11877. SpriteMaterial: 'sprite'
  11878. };
  11879. function getChannel( value ) {
  11880. if ( value === 1 ) return 'uv2';
  11881. return 'uv';
  11882. }
  11883. function getParameters( material, lights, shadows, scene, object ) {
  11884. const fog = scene.fog;
  11885. const geometry = object.geometry;
  11886. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11887. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11888. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11889. const shaderID = shaderIDs[ material.type ];
  11890. // heuristics to create shader parameters according to lights in the scene
  11891. // (not to blow over maxLights budget)
  11892. if ( material.precision !== null ) {
  11893. precision = capabilities.getMaxPrecision( material.precision );
  11894. if ( precision !== material.precision ) {
  11895. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11896. }
  11897. }
  11898. //
  11899. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11900. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11901. let morphTextureStride = 0;
  11902. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11903. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11904. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11905. //
  11906. let vertexShader, fragmentShader;
  11907. let customVertexShaderID, customFragmentShaderID;
  11908. if ( shaderID ) {
  11909. const shader = ShaderLib[ shaderID ];
  11910. vertexShader = shader.vertexShader;
  11911. fragmentShader = shader.fragmentShader;
  11912. } else {
  11913. vertexShader = material.vertexShader;
  11914. fragmentShader = material.fragmentShader;
  11915. _customShaders.update( material );
  11916. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11917. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11918. }
  11919. const currentRenderTarget = renderer.getRenderTarget();
  11920. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  11921. const HAS_MAP = !! material.map;
  11922. const HAS_MATCAP = !! material.matcap;
  11923. const HAS_ENVMAP = !! envMap;
  11924. const HAS_AOMAP = !! material.aoMap;
  11925. const HAS_LIGHTMAP = !! material.lightMap;
  11926. const HAS_BUMPMAP = !! material.bumpMap;
  11927. const HAS_NORMALMAP = !! material.normalMap;
  11928. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  11929. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  11930. const HAS_METALNESSMAP = !! material.metalnessMap;
  11931. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  11932. const HAS_CLEARCOAT = material.clearcoat > 0;
  11933. const HAS_IRIDESCENCE = material.iridescence > 0;
  11934. const HAS_SHEEN = material.sheen > 0;
  11935. const HAS_TRANSMISSION = material.transmission > 0;
  11936. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  11937. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  11938. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  11939. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  11940. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  11941. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  11942. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  11943. const HAS_SPECULARMAP = !! material.specularMap;
  11944. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  11945. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  11946. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  11947. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  11948. const HAS_GRADIENTMAP = !! material.gradientMap;
  11949. const HAS_ALPHAMAP = !! material.alphaMap;
  11950. const HAS_ALPHATEST = material.alphaTest > 0;
  11951. const HAS_EXTENSIONS = !! material.extensions;
  11952. const HAS_ATTRIBUTE_UV2 = !! geometry.attributes.uv2;
  11953. const parameters = {
  11954. isWebGL2: IS_WEBGL2,
  11955. shaderID: shaderID,
  11956. shaderName: material.type,
  11957. vertexShader: vertexShader,
  11958. fragmentShader: fragmentShader,
  11959. defines: material.defines,
  11960. customVertexShaderID: customVertexShaderID,
  11961. customFragmentShaderID: customFragmentShaderID,
  11962. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11963. glslVersion: material.glslVersion,
  11964. precision: precision,
  11965. instancing: IS_INSTANCEDMESH,
  11966. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  11967. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  11968. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11969. map: HAS_MAP,
  11970. matcap: HAS_MATCAP,
  11971. envMap: HAS_ENVMAP,
  11972. envMapMode: HAS_ENVMAP && envMap.mapping,
  11973. envMapCubeUVHeight: envMapCubeUVHeight,
  11974. aoMap: HAS_AOMAP,
  11975. lightMap: HAS_LIGHTMAP,
  11976. bumpMap: HAS_BUMPMAP,
  11977. normalMap: HAS_NORMALMAP,
  11978. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  11979. emissiveMap: HAS_EMISSIVEMAP,
  11980. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  11981. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  11982. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11983. metalnessMap: HAS_METALNESSMAP,
  11984. roughnessMap: HAS_ROUGHNESSMAP,
  11985. clearcoat: HAS_CLEARCOAT,
  11986. clearcoatMap: HAS_CLEARCOATMAP,
  11987. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  11988. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  11989. iridescence: HAS_IRIDESCENCE,
  11990. iridescenceMap: HAS_IRIDESCENCEMAP,
  11991. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  11992. sheen: HAS_SHEEN,
  11993. sheenColorMap: HAS_SHEEN_COLORMAP,
  11994. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  11995. specularMap: HAS_SPECULARMAP,
  11996. specularColorMap: HAS_SPECULAR_COLORMAP,
  11997. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  11998. transmission: HAS_TRANSMISSION,
  11999. transmissionMap: HAS_TRANSMISSIONMAP,
  12000. thicknessMap: HAS_THICKNESSMAP,
  12001. gradientMap: HAS_GRADIENTMAP,
  12002. opaque: material.transparent === false && material.blending === NormalBlending,
  12003. alphaMap: HAS_ALPHAMAP,
  12004. alphaTest: HAS_ALPHATEST,
  12005. combine: material.combine,
  12006. //
  12007. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12008. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12009. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12010. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12011. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12012. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12013. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12014. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12015. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12016. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12017. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12018. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12019. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12020. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12021. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12022. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12023. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12024. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12025. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12026. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12027. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12028. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12029. //
  12030. vertexTangents: HAS_NORMALMAP && !! geometry.attributes.tangent,
  12031. vertexColors: material.vertexColors,
  12032. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12033. vertexUvs2: HAS_ATTRIBUTE_UV2,
  12034. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12035. fog: !! fog,
  12036. useFog: material.fog === true,
  12037. fogExp2: ( fog && fog.isFogExp2 ),
  12038. flatShading: material.flatShading === true,
  12039. sizeAttenuation: material.sizeAttenuation === true,
  12040. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12041. skinning: object.isSkinnedMesh === true,
  12042. morphTargets: geometry.morphAttributes.position !== undefined,
  12043. morphNormals: geometry.morphAttributes.normal !== undefined,
  12044. morphColors: geometry.morphAttributes.color !== undefined,
  12045. morphTargetsCount: morphTargetsCount,
  12046. morphTextureStride: morphTextureStride,
  12047. numDirLights: lights.directional.length,
  12048. numPointLights: lights.point.length,
  12049. numSpotLights: lights.spot.length,
  12050. numSpotLightMaps: lights.spotLightMap.length,
  12051. numRectAreaLights: lights.rectArea.length,
  12052. numHemiLights: lights.hemi.length,
  12053. numDirLightShadows: lights.directionalShadowMap.length,
  12054. numPointLightShadows: lights.pointShadowMap.length,
  12055. numSpotLightShadows: lights.spotShadowMap.length,
  12056. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12057. numClippingPlanes: clipping.numPlanes,
  12058. numClipIntersection: clipping.numIntersection,
  12059. dithering: material.dithering,
  12060. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12061. shadowMapType: renderer.shadowMap.type,
  12062. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12063. useLegacyLights: renderer.useLegacyLights,
  12064. premultipliedAlpha: material.premultipliedAlpha,
  12065. doubleSided: material.side === DoubleSide,
  12066. flipSided: material.side === BackSide,
  12067. useDepthPacking: material.depthPacking >= 0,
  12068. depthPacking: material.depthPacking || 0,
  12069. index0AttributeName: material.index0AttributeName,
  12070. extensionDerivatives: HAS_EXTENSIONS && material.extensions.derivatives === true,
  12071. extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true,
  12072. extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true,
  12073. extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true,
  12074. rendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ),
  12075. rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  12076. rendererExtensionShaderTextureLod: IS_WEBGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  12077. customProgramCacheKey: material.customProgramCacheKey()
  12078. };
  12079. return parameters;
  12080. }
  12081. function getProgramCacheKey( parameters ) {
  12082. const array = [];
  12083. if ( parameters.shaderID ) {
  12084. array.push( parameters.shaderID );
  12085. } else {
  12086. array.push( parameters.customVertexShaderID );
  12087. array.push( parameters.customFragmentShaderID );
  12088. }
  12089. if ( parameters.defines !== undefined ) {
  12090. for ( const name in parameters.defines ) {
  12091. array.push( name );
  12092. array.push( parameters.defines[ name ] );
  12093. }
  12094. }
  12095. if ( parameters.isRawShaderMaterial === false ) {
  12096. getProgramCacheKeyParameters( array, parameters );
  12097. getProgramCacheKeyBooleans( array, parameters );
  12098. array.push( renderer.outputEncoding );
  12099. }
  12100. array.push( parameters.customProgramCacheKey );
  12101. return array.join();
  12102. }
  12103. function getProgramCacheKeyParameters( array, parameters ) {
  12104. array.push( parameters.precision );
  12105. array.push( parameters.outputEncoding );
  12106. array.push( parameters.envMapMode );
  12107. array.push( parameters.envMapCubeUVHeight );
  12108. array.push( parameters.mapUv );
  12109. array.push( parameters.alphaMapUv );
  12110. array.push( parameters.lightMapUv );
  12111. array.push( parameters.aoMapUv );
  12112. array.push( parameters.bumpMapUv );
  12113. array.push( parameters.normalMapUv );
  12114. array.push( parameters.displacementMapUv );
  12115. array.push( parameters.emissiveMapUv );
  12116. array.push( parameters.metalnessMapUv );
  12117. array.push( parameters.roughnessMapUv );
  12118. array.push( parameters.clearcoatMapUv );
  12119. array.push( parameters.clearcoatNormalMapUv );
  12120. array.push( parameters.clearcoatRoughnessMapUv );
  12121. array.push( parameters.iridescenceMapUv );
  12122. array.push( parameters.iridescenceThicknessMapUv );
  12123. array.push( parameters.sheenColorMapUv );
  12124. array.push( parameters.sheenRoughnessMapUv );
  12125. array.push( parameters.specularMapUv );
  12126. array.push( parameters.specularColorMapUv );
  12127. array.push( parameters.specularIntensityMapUv );
  12128. array.push( parameters.transmissionMapUv );
  12129. array.push( parameters.thicknessMapUv );
  12130. array.push( parameters.combine );
  12131. array.push( parameters.fogExp2 );
  12132. array.push( parameters.sizeAttenuation );
  12133. array.push( parameters.morphTargetsCount );
  12134. array.push( parameters.morphAttributeCount );
  12135. array.push( parameters.numDirLights );
  12136. array.push( parameters.numPointLights );
  12137. array.push( parameters.numSpotLights );
  12138. array.push( parameters.numSpotLightMaps );
  12139. array.push( parameters.numHemiLights );
  12140. array.push( parameters.numRectAreaLights );
  12141. array.push( parameters.numDirLightShadows );
  12142. array.push( parameters.numPointLightShadows );
  12143. array.push( parameters.numSpotLightShadows );
  12144. array.push( parameters.numSpotLightShadowsWithMaps );
  12145. array.push( parameters.shadowMapType );
  12146. array.push( parameters.toneMapping );
  12147. array.push( parameters.numClippingPlanes );
  12148. array.push( parameters.numClipIntersection );
  12149. array.push( parameters.depthPacking );
  12150. }
  12151. function getProgramCacheKeyBooleans( array, parameters ) {
  12152. _programLayers.disableAll();
  12153. if ( parameters.isWebGL2 )
  12154. _programLayers.enable( 0 );
  12155. if ( parameters.supportsVertexTextures )
  12156. _programLayers.enable( 1 );
  12157. if ( parameters.instancing )
  12158. _programLayers.enable( 2 );
  12159. if ( parameters.instancingColor )
  12160. _programLayers.enable( 3 );
  12161. if ( parameters.matcap )
  12162. _programLayers.enable( 4 );
  12163. if ( parameters.envMap )
  12164. _programLayers.enable( 5 );
  12165. if ( parameters.normalMapObjectSpace )
  12166. _programLayers.enable( 6 );
  12167. if ( parameters.normalMapTangentSpace )
  12168. _programLayers.enable( 7 );
  12169. if ( parameters.clearcoat )
  12170. _programLayers.enable( 8 );
  12171. if ( parameters.iridescence )
  12172. _programLayers.enable( 9 );
  12173. if ( parameters.alphaTest )
  12174. _programLayers.enable( 10 );
  12175. if ( parameters.vertexColors )
  12176. _programLayers.enable( 11 );
  12177. if ( parameters.vertexAlphas )
  12178. _programLayers.enable( 12 );
  12179. if ( parameters.vertexUvs2 )
  12180. _programLayers.enable( 13 );
  12181. if ( parameters.vertexTangents )
  12182. _programLayers.enable( 14 );
  12183. array.push( _programLayers.mask );
  12184. _programLayers.disableAll();
  12185. if ( parameters.fog )
  12186. _programLayers.enable( 0 );
  12187. if ( parameters.useFog )
  12188. _programLayers.enable( 1 );
  12189. if ( parameters.flatShading )
  12190. _programLayers.enable( 2 );
  12191. if ( parameters.logarithmicDepthBuffer )
  12192. _programLayers.enable( 3 );
  12193. if ( parameters.skinning )
  12194. _programLayers.enable( 4 );
  12195. if ( parameters.morphTargets )
  12196. _programLayers.enable( 5 );
  12197. if ( parameters.morphNormals )
  12198. _programLayers.enable( 6 );
  12199. if ( parameters.morphColors )
  12200. _programLayers.enable( 7 );
  12201. if ( parameters.premultipliedAlpha )
  12202. _programLayers.enable( 8 );
  12203. if ( parameters.shadowMapEnabled )
  12204. _programLayers.enable( 9 );
  12205. if ( parameters.useLegacyLights )
  12206. _programLayers.enable( 10 );
  12207. if ( parameters.doubleSided )
  12208. _programLayers.enable( 11 );
  12209. if ( parameters.flipSided )
  12210. _programLayers.enable( 12 );
  12211. if ( parameters.useDepthPacking )
  12212. _programLayers.enable( 13 );
  12213. if ( parameters.dithering )
  12214. _programLayers.enable( 14 );
  12215. if ( parameters.transmission )
  12216. _programLayers.enable( 15 );
  12217. if ( parameters.sheen )
  12218. _programLayers.enable( 16 );
  12219. if ( parameters.decodeVideoTexture )
  12220. _programLayers.enable( 17 );
  12221. if ( parameters.opaque )
  12222. _programLayers.enable( 18 );
  12223. if ( parameters.pointsUvs )
  12224. _programLayers.enable( 19 );
  12225. array.push( _programLayers.mask );
  12226. }
  12227. function getUniforms( material ) {
  12228. const shaderID = shaderIDs[ material.type ];
  12229. let uniforms;
  12230. if ( shaderID ) {
  12231. const shader = ShaderLib[ shaderID ];
  12232. uniforms = UniformsUtils.clone( shader.uniforms );
  12233. } else {
  12234. uniforms = material.uniforms;
  12235. }
  12236. return uniforms;
  12237. }
  12238. function acquireProgram( parameters, cacheKey ) {
  12239. let program;
  12240. // Check if code has been already compiled
  12241. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12242. const preexistingProgram = programs[ p ];
  12243. if ( preexistingProgram.cacheKey === cacheKey ) {
  12244. program = preexistingProgram;
  12245. ++ program.usedTimes;
  12246. break;
  12247. }
  12248. }
  12249. if ( program === undefined ) {
  12250. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12251. programs.push( program );
  12252. }
  12253. return program;
  12254. }
  12255. function releaseProgram( program ) {
  12256. if ( -- program.usedTimes === 0 ) {
  12257. // Remove from unordered set
  12258. const i = programs.indexOf( program );
  12259. programs[ i ] = programs[ programs.length - 1 ];
  12260. programs.pop();
  12261. // Free WebGL resources
  12262. program.destroy();
  12263. }
  12264. }
  12265. function releaseShaderCache( material ) {
  12266. _customShaders.remove( material );
  12267. }
  12268. function dispose() {
  12269. _customShaders.dispose();
  12270. }
  12271. return {
  12272. getParameters: getParameters,
  12273. getProgramCacheKey: getProgramCacheKey,
  12274. getUniforms: getUniforms,
  12275. acquireProgram: acquireProgram,
  12276. releaseProgram: releaseProgram,
  12277. releaseShaderCache: releaseShaderCache,
  12278. // Exposed for resource monitoring & error feedback via renderer.info:
  12279. programs: programs,
  12280. dispose: dispose
  12281. };
  12282. }
  12283. function WebGLProperties() {
  12284. let properties = new WeakMap();
  12285. function get( object ) {
  12286. let map = properties.get( object );
  12287. if ( map === undefined ) {
  12288. map = {};
  12289. properties.set( object, map );
  12290. }
  12291. return map;
  12292. }
  12293. function remove( object ) {
  12294. properties.delete( object );
  12295. }
  12296. function update( object, key, value ) {
  12297. properties.get( object )[ key ] = value;
  12298. }
  12299. function dispose() {
  12300. properties = new WeakMap();
  12301. }
  12302. return {
  12303. get: get,
  12304. remove: remove,
  12305. update: update,
  12306. dispose: dispose
  12307. };
  12308. }
  12309. function painterSortStable( a, b ) {
  12310. if ( a.groupOrder !== b.groupOrder ) {
  12311. return a.groupOrder - b.groupOrder;
  12312. } else if ( a.renderOrder !== b.renderOrder ) {
  12313. return a.renderOrder - b.renderOrder;
  12314. } else if ( a.material.id !== b.material.id ) {
  12315. return a.material.id - b.material.id;
  12316. } else if ( a.z !== b.z ) {
  12317. return a.z - b.z;
  12318. } else {
  12319. return a.id - b.id;
  12320. }
  12321. }
  12322. function reversePainterSortStable( a, b ) {
  12323. if ( a.groupOrder !== b.groupOrder ) {
  12324. return a.groupOrder - b.groupOrder;
  12325. } else if ( a.renderOrder !== b.renderOrder ) {
  12326. return a.renderOrder - b.renderOrder;
  12327. } else if ( a.z !== b.z ) {
  12328. return b.z - a.z;
  12329. } else {
  12330. return a.id - b.id;
  12331. }
  12332. }
  12333. function WebGLRenderList() {
  12334. const renderItems = [];
  12335. let renderItemsIndex = 0;
  12336. const opaque = [];
  12337. const transmissive = [];
  12338. const transparent = [];
  12339. function init() {
  12340. renderItemsIndex = 0;
  12341. opaque.length = 0;
  12342. transmissive.length = 0;
  12343. transparent.length = 0;
  12344. }
  12345. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12346. let renderItem = renderItems[ renderItemsIndex ];
  12347. if ( renderItem === undefined ) {
  12348. renderItem = {
  12349. id: object.id,
  12350. object: object,
  12351. geometry: geometry,
  12352. material: material,
  12353. groupOrder: groupOrder,
  12354. renderOrder: object.renderOrder,
  12355. z: z,
  12356. group: group
  12357. };
  12358. renderItems[ renderItemsIndex ] = renderItem;
  12359. } else {
  12360. renderItem.id = object.id;
  12361. renderItem.object = object;
  12362. renderItem.geometry = geometry;
  12363. renderItem.material = material;
  12364. renderItem.groupOrder = groupOrder;
  12365. renderItem.renderOrder = object.renderOrder;
  12366. renderItem.z = z;
  12367. renderItem.group = group;
  12368. }
  12369. renderItemsIndex ++;
  12370. return renderItem;
  12371. }
  12372. function push( object, geometry, material, groupOrder, z, group ) {
  12373. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12374. if ( material.transmission > 0.0 ) {
  12375. transmissive.push( renderItem );
  12376. } else if ( material.transparent === true ) {
  12377. transparent.push( renderItem );
  12378. } else {
  12379. opaque.push( renderItem );
  12380. }
  12381. }
  12382. function unshift( object, geometry, material, groupOrder, z, group ) {
  12383. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12384. if ( material.transmission > 0.0 ) {
  12385. transmissive.unshift( renderItem );
  12386. } else if ( material.transparent === true ) {
  12387. transparent.unshift( renderItem );
  12388. } else {
  12389. opaque.unshift( renderItem );
  12390. }
  12391. }
  12392. function sort( customOpaqueSort, customTransparentSort ) {
  12393. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12394. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12395. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12396. }
  12397. function finish() {
  12398. // Clear references from inactive renderItems in the list
  12399. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12400. const renderItem = renderItems[ i ];
  12401. if ( renderItem.id === null ) break;
  12402. renderItem.id = null;
  12403. renderItem.object = null;
  12404. renderItem.geometry = null;
  12405. renderItem.material = null;
  12406. renderItem.group = null;
  12407. }
  12408. }
  12409. return {
  12410. opaque: opaque,
  12411. transmissive: transmissive,
  12412. transparent: transparent,
  12413. init: init,
  12414. push: push,
  12415. unshift: unshift,
  12416. finish: finish,
  12417. sort: sort
  12418. };
  12419. }
  12420. function WebGLRenderLists() {
  12421. let lists = new WeakMap();
  12422. function get( scene, renderCallDepth ) {
  12423. const listArray = lists.get( scene );
  12424. let list;
  12425. if ( listArray === undefined ) {
  12426. list = new WebGLRenderList();
  12427. lists.set( scene, [ list ] );
  12428. } else {
  12429. if ( renderCallDepth >= listArray.length ) {
  12430. list = new WebGLRenderList();
  12431. listArray.push( list );
  12432. } else {
  12433. list = listArray[ renderCallDepth ];
  12434. }
  12435. }
  12436. return list;
  12437. }
  12438. function dispose() {
  12439. lists = new WeakMap();
  12440. }
  12441. return {
  12442. get: get,
  12443. dispose: dispose
  12444. };
  12445. }
  12446. function UniformsCache() {
  12447. const lights = {};
  12448. return {
  12449. get: function ( light ) {
  12450. if ( lights[ light.id ] !== undefined ) {
  12451. return lights[ light.id ];
  12452. }
  12453. let uniforms;
  12454. switch ( light.type ) {
  12455. case 'DirectionalLight':
  12456. uniforms = {
  12457. direction: new Vector3(),
  12458. color: new Color()
  12459. };
  12460. break;
  12461. case 'SpotLight':
  12462. uniforms = {
  12463. position: new Vector3(),
  12464. direction: new Vector3(),
  12465. color: new Color(),
  12466. distance: 0,
  12467. coneCos: 0,
  12468. penumbraCos: 0,
  12469. decay: 0
  12470. };
  12471. break;
  12472. case 'PointLight':
  12473. uniforms = {
  12474. position: new Vector3(),
  12475. color: new Color(),
  12476. distance: 0,
  12477. decay: 0
  12478. };
  12479. break;
  12480. case 'HemisphereLight':
  12481. uniforms = {
  12482. direction: new Vector3(),
  12483. skyColor: new Color(),
  12484. groundColor: new Color()
  12485. };
  12486. break;
  12487. case 'RectAreaLight':
  12488. uniforms = {
  12489. color: new Color(),
  12490. position: new Vector3(),
  12491. halfWidth: new Vector3(),
  12492. halfHeight: new Vector3()
  12493. };
  12494. break;
  12495. }
  12496. lights[ light.id ] = uniforms;
  12497. return uniforms;
  12498. }
  12499. };
  12500. }
  12501. function ShadowUniformsCache() {
  12502. const lights = {};
  12503. return {
  12504. get: function ( light ) {
  12505. if ( lights[ light.id ] !== undefined ) {
  12506. return lights[ light.id ];
  12507. }
  12508. let uniforms;
  12509. switch ( light.type ) {
  12510. case 'DirectionalLight':
  12511. uniforms = {
  12512. shadowBias: 0,
  12513. shadowNormalBias: 0,
  12514. shadowRadius: 1,
  12515. shadowMapSize: new Vector2()
  12516. };
  12517. break;
  12518. case 'SpotLight':
  12519. uniforms = {
  12520. shadowBias: 0,
  12521. shadowNormalBias: 0,
  12522. shadowRadius: 1,
  12523. shadowMapSize: new Vector2()
  12524. };
  12525. break;
  12526. case 'PointLight':
  12527. uniforms = {
  12528. shadowBias: 0,
  12529. shadowNormalBias: 0,
  12530. shadowRadius: 1,
  12531. shadowMapSize: new Vector2(),
  12532. shadowCameraNear: 1,
  12533. shadowCameraFar: 1000
  12534. };
  12535. break;
  12536. // TODO (abelnation): set RectAreaLight shadow uniforms
  12537. }
  12538. lights[ light.id ] = uniforms;
  12539. return uniforms;
  12540. }
  12541. };
  12542. }
  12543. let nextVersion = 0;
  12544. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12545. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12546. }
  12547. function WebGLLights( extensions, capabilities ) {
  12548. const cache = new UniformsCache();
  12549. const shadowCache = ShadowUniformsCache();
  12550. const state = {
  12551. version: 0,
  12552. hash: {
  12553. directionalLength: - 1,
  12554. pointLength: - 1,
  12555. spotLength: - 1,
  12556. rectAreaLength: - 1,
  12557. hemiLength: - 1,
  12558. numDirectionalShadows: - 1,
  12559. numPointShadows: - 1,
  12560. numSpotShadows: - 1,
  12561. numSpotMaps: - 1
  12562. },
  12563. ambient: [ 0, 0, 0 ],
  12564. probe: [],
  12565. directional: [],
  12566. directionalShadow: [],
  12567. directionalShadowMap: [],
  12568. directionalShadowMatrix: [],
  12569. spot: [],
  12570. spotLightMap: [],
  12571. spotShadow: [],
  12572. spotShadowMap: [],
  12573. spotLightMatrix: [],
  12574. rectArea: [],
  12575. rectAreaLTC1: null,
  12576. rectAreaLTC2: null,
  12577. point: [],
  12578. pointShadow: [],
  12579. pointShadowMap: [],
  12580. pointShadowMatrix: [],
  12581. hemi: [],
  12582. numSpotLightShadowsWithMaps: 0
  12583. };
  12584. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12585. const vector3 = new Vector3();
  12586. const matrix4 = new Matrix4();
  12587. const matrix42 = new Matrix4();
  12588. function setup( lights, useLegacyLights ) {
  12589. let r = 0, g = 0, b = 0;
  12590. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12591. let directionalLength = 0;
  12592. let pointLength = 0;
  12593. let spotLength = 0;
  12594. let rectAreaLength = 0;
  12595. let hemiLength = 0;
  12596. let numDirectionalShadows = 0;
  12597. let numPointShadows = 0;
  12598. let numSpotShadows = 0;
  12599. let numSpotMaps = 0;
  12600. let numSpotShadowsWithMaps = 0;
  12601. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12602. lights.sort( shadowCastingAndTexturingLightsFirst );
  12603. // artist-friendly light intensity scaling factor
  12604. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  12605. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12606. const light = lights[ i ];
  12607. const color = light.color;
  12608. const intensity = light.intensity;
  12609. const distance = light.distance;
  12610. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12611. if ( light.isAmbientLight ) {
  12612. r += color.r * intensity * scaleFactor;
  12613. g += color.g * intensity * scaleFactor;
  12614. b += color.b * intensity * scaleFactor;
  12615. } else if ( light.isLightProbe ) {
  12616. for ( let j = 0; j < 9; j ++ ) {
  12617. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12618. }
  12619. } else if ( light.isDirectionalLight ) {
  12620. const uniforms = cache.get( light );
  12621. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12622. if ( light.castShadow ) {
  12623. const shadow = light.shadow;
  12624. const shadowUniforms = shadowCache.get( light );
  12625. shadowUniforms.shadowBias = shadow.bias;
  12626. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12627. shadowUniforms.shadowRadius = shadow.radius;
  12628. shadowUniforms.shadowMapSize = shadow.mapSize;
  12629. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12630. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12631. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12632. numDirectionalShadows ++;
  12633. }
  12634. state.directional[ directionalLength ] = uniforms;
  12635. directionalLength ++;
  12636. } else if ( light.isSpotLight ) {
  12637. const uniforms = cache.get( light );
  12638. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12639. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12640. uniforms.distance = distance;
  12641. uniforms.coneCos = Math.cos( light.angle );
  12642. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12643. uniforms.decay = light.decay;
  12644. state.spot[ spotLength ] = uniforms;
  12645. const shadow = light.shadow;
  12646. if ( light.map ) {
  12647. state.spotLightMap[ numSpotMaps ] = light.map;
  12648. numSpotMaps ++;
  12649. // make sure the lightMatrix is up to date
  12650. // TODO : do it if required only
  12651. shadow.updateMatrices( light );
  12652. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12653. }
  12654. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12655. if ( light.castShadow ) {
  12656. const shadowUniforms = shadowCache.get( light );
  12657. shadowUniforms.shadowBias = shadow.bias;
  12658. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12659. shadowUniforms.shadowRadius = shadow.radius;
  12660. shadowUniforms.shadowMapSize = shadow.mapSize;
  12661. state.spotShadow[ spotLength ] = shadowUniforms;
  12662. state.spotShadowMap[ spotLength ] = shadowMap;
  12663. numSpotShadows ++;
  12664. }
  12665. spotLength ++;
  12666. } else if ( light.isRectAreaLight ) {
  12667. const uniforms = cache.get( light );
  12668. uniforms.color.copy( color ).multiplyScalar( intensity );
  12669. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12670. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12671. state.rectArea[ rectAreaLength ] = uniforms;
  12672. rectAreaLength ++;
  12673. } else if ( light.isPointLight ) {
  12674. const uniforms = cache.get( light );
  12675. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12676. uniforms.distance = light.distance;
  12677. uniforms.decay = light.decay;
  12678. if ( light.castShadow ) {
  12679. const shadow = light.shadow;
  12680. const shadowUniforms = shadowCache.get( light );
  12681. shadowUniforms.shadowBias = shadow.bias;
  12682. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12683. shadowUniforms.shadowRadius = shadow.radius;
  12684. shadowUniforms.shadowMapSize = shadow.mapSize;
  12685. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12686. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12687. state.pointShadow[ pointLength ] = shadowUniforms;
  12688. state.pointShadowMap[ pointLength ] = shadowMap;
  12689. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12690. numPointShadows ++;
  12691. }
  12692. state.point[ pointLength ] = uniforms;
  12693. pointLength ++;
  12694. } else if ( light.isHemisphereLight ) {
  12695. const uniforms = cache.get( light );
  12696. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12697. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12698. state.hemi[ hemiLength ] = uniforms;
  12699. hemiLength ++;
  12700. }
  12701. }
  12702. if ( rectAreaLength > 0 ) {
  12703. if ( capabilities.isWebGL2 ) {
  12704. // WebGL 2
  12705. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12706. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12707. } else {
  12708. // WebGL 1
  12709. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12710. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12711. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12712. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12713. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12714. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12715. } else {
  12716. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12717. }
  12718. }
  12719. }
  12720. state.ambient[ 0 ] = r;
  12721. state.ambient[ 1 ] = g;
  12722. state.ambient[ 2 ] = b;
  12723. const hash = state.hash;
  12724. if ( hash.directionalLength !== directionalLength ||
  12725. hash.pointLength !== pointLength ||
  12726. hash.spotLength !== spotLength ||
  12727. hash.rectAreaLength !== rectAreaLength ||
  12728. hash.hemiLength !== hemiLength ||
  12729. hash.numDirectionalShadows !== numDirectionalShadows ||
  12730. hash.numPointShadows !== numPointShadows ||
  12731. hash.numSpotShadows !== numSpotShadows ||
  12732. hash.numSpotMaps !== numSpotMaps ) {
  12733. state.directional.length = directionalLength;
  12734. state.spot.length = spotLength;
  12735. state.rectArea.length = rectAreaLength;
  12736. state.point.length = pointLength;
  12737. state.hemi.length = hemiLength;
  12738. state.directionalShadow.length = numDirectionalShadows;
  12739. state.directionalShadowMap.length = numDirectionalShadows;
  12740. state.pointShadow.length = numPointShadows;
  12741. state.pointShadowMap.length = numPointShadows;
  12742. state.spotShadow.length = numSpotShadows;
  12743. state.spotShadowMap.length = numSpotShadows;
  12744. state.directionalShadowMatrix.length = numDirectionalShadows;
  12745. state.pointShadowMatrix.length = numPointShadows;
  12746. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12747. state.spotLightMap.length = numSpotMaps;
  12748. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12749. hash.directionalLength = directionalLength;
  12750. hash.pointLength = pointLength;
  12751. hash.spotLength = spotLength;
  12752. hash.rectAreaLength = rectAreaLength;
  12753. hash.hemiLength = hemiLength;
  12754. hash.numDirectionalShadows = numDirectionalShadows;
  12755. hash.numPointShadows = numPointShadows;
  12756. hash.numSpotShadows = numSpotShadows;
  12757. hash.numSpotMaps = numSpotMaps;
  12758. state.version = nextVersion ++;
  12759. }
  12760. }
  12761. function setupView( lights, camera ) {
  12762. let directionalLength = 0;
  12763. let pointLength = 0;
  12764. let spotLength = 0;
  12765. let rectAreaLength = 0;
  12766. let hemiLength = 0;
  12767. const viewMatrix = camera.matrixWorldInverse;
  12768. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12769. const light = lights[ i ];
  12770. if ( light.isDirectionalLight ) {
  12771. const uniforms = state.directional[ directionalLength ];
  12772. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12773. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12774. uniforms.direction.sub( vector3 );
  12775. uniforms.direction.transformDirection( viewMatrix );
  12776. directionalLength ++;
  12777. } else if ( light.isSpotLight ) {
  12778. const uniforms = state.spot[ spotLength ];
  12779. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12780. uniforms.position.applyMatrix4( viewMatrix );
  12781. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12782. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12783. uniforms.direction.sub( vector3 );
  12784. uniforms.direction.transformDirection( viewMatrix );
  12785. spotLength ++;
  12786. } else if ( light.isRectAreaLight ) {
  12787. const uniforms = state.rectArea[ rectAreaLength ];
  12788. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12789. uniforms.position.applyMatrix4( viewMatrix );
  12790. // extract local rotation of light to derive width/height half vectors
  12791. matrix42.identity();
  12792. matrix4.copy( light.matrixWorld );
  12793. matrix4.premultiply( viewMatrix );
  12794. matrix42.extractRotation( matrix4 );
  12795. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12796. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12797. uniforms.halfWidth.applyMatrix4( matrix42 );
  12798. uniforms.halfHeight.applyMatrix4( matrix42 );
  12799. rectAreaLength ++;
  12800. } else if ( light.isPointLight ) {
  12801. const uniforms = state.point[ pointLength ];
  12802. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12803. uniforms.position.applyMatrix4( viewMatrix );
  12804. pointLength ++;
  12805. } else if ( light.isHemisphereLight ) {
  12806. const uniforms = state.hemi[ hemiLength ];
  12807. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12808. uniforms.direction.transformDirection( viewMatrix );
  12809. hemiLength ++;
  12810. }
  12811. }
  12812. }
  12813. return {
  12814. setup: setup,
  12815. setupView: setupView,
  12816. state: state
  12817. };
  12818. }
  12819. function WebGLRenderState( extensions, capabilities ) {
  12820. const lights = new WebGLLights( extensions, capabilities );
  12821. const lightsArray = [];
  12822. const shadowsArray = [];
  12823. function init() {
  12824. lightsArray.length = 0;
  12825. shadowsArray.length = 0;
  12826. }
  12827. function pushLight( light ) {
  12828. lightsArray.push( light );
  12829. }
  12830. function pushShadow( shadowLight ) {
  12831. shadowsArray.push( shadowLight );
  12832. }
  12833. function setupLights( useLegacyLights ) {
  12834. lights.setup( lightsArray, useLegacyLights );
  12835. }
  12836. function setupLightsView( camera ) {
  12837. lights.setupView( lightsArray, camera );
  12838. }
  12839. const state = {
  12840. lightsArray: lightsArray,
  12841. shadowsArray: shadowsArray,
  12842. lights: lights
  12843. };
  12844. return {
  12845. init: init,
  12846. state: state,
  12847. setupLights: setupLights,
  12848. setupLightsView: setupLightsView,
  12849. pushLight: pushLight,
  12850. pushShadow: pushShadow
  12851. };
  12852. }
  12853. function WebGLRenderStates( extensions, capabilities ) {
  12854. let renderStates = new WeakMap();
  12855. function get( scene, renderCallDepth = 0 ) {
  12856. const renderStateArray = renderStates.get( scene );
  12857. let renderState;
  12858. if ( renderStateArray === undefined ) {
  12859. renderState = new WebGLRenderState( extensions, capabilities );
  12860. renderStates.set( scene, [ renderState ] );
  12861. } else {
  12862. if ( renderCallDepth >= renderStateArray.length ) {
  12863. renderState = new WebGLRenderState( extensions, capabilities );
  12864. renderStateArray.push( renderState );
  12865. } else {
  12866. renderState = renderStateArray[ renderCallDepth ];
  12867. }
  12868. }
  12869. return renderState;
  12870. }
  12871. function dispose() {
  12872. renderStates = new WeakMap();
  12873. }
  12874. return {
  12875. get: get,
  12876. dispose: dispose
  12877. };
  12878. }
  12879. class MeshDepthMaterial extends Material {
  12880. constructor( parameters ) {
  12881. super();
  12882. this.isMeshDepthMaterial = true;
  12883. this.type = 'MeshDepthMaterial';
  12884. this.depthPacking = BasicDepthPacking;
  12885. this.map = null;
  12886. this.alphaMap = null;
  12887. this.displacementMap = null;
  12888. this.displacementScale = 1;
  12889. this.displacementBias = 0;
  12890. this.wireframe = false;
  12891. this.wireframeLinewidth = 1;
  12892. this.setValues( parameters );
  12893. }
  12894. copy( source ) {
  12895. super.copy( source );
  12896. this.depthPacking = source.depthPacking;
  12897. this.map = source.map;
  12898. this.alphaMap = source.alphaMap;
  12899. this.displacementMap = source.displacementMap;
  12900. this.displacementScale = source.displacementScale;
  12901. this.displacementBias = source.displacementBias;
  12902. this.wireframe = source.wireframe;
  12903. this.wireframeLinewidth = source.wireframeLinewidth;
  12904. return this;
  12905. }
  12906. }
  12907. class MeshDistanceMaterial extends Material {
  12908. constructor( parameters ) {
  12909. super();
  12910. this.isMeshDistanceMaterial = true;
  12911. this.type = 'MeshDistanceMaterial';
  12912. this.map = null;
  12913. this.alphaMap = null;
  12914. this.displacementMap = null;
  12915. this.displacementScale = 1;
  12916. this.displacementBias = 0;
  12917. this.setValues( parameters );
  12918. }
  12919. copy( source ) {
  12920. super.copy( source );
  12921. this.map = source.map;
  12922. this.alphaMap = source.alphaMap;
  12923. this.displacementMap = source.displacementMap;
  12924. this.displacementScale = source.displacementScale;
  12925. this.displacementBias = source.displacementBias;
  12926. return this;
  12927. }
  12928. }
  12929. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12930. 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}";
  12931. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12932. let _frustum = new Frustum();
  12933. const _shadowMapSize = new Vector2(),
  12934. _viewportSize = new Vector2(),
  12935. _viewport = new Vector4(),
  12936. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12937. _distanceMaterial = new MeshDistanceMaterial(),
  12938. _materialCache = {},
  12939. _maxTextureSize = _capabilities.maxTextureSize;
  12940. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  12941. const shadowMaterialVertical = new ShaderMaterial( {
  12942. defines: {
  12943. VSM_SAMPLES: 8
  12944. },
  12945. uniforms: {
  12946. shadow_pass: { value: null },
  12947. resolution: { value: new Vector2() },
  12948. radius: { value: 4.0 }
  12949. },
  12950. vertexShader: vertex,
  12951. fragmentShader: fragment
  12952. } );
  12953. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12954. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12955. const fullScreenTri = new BufferGeometry();
  12956. fullScreenTri.setAttribute(
  12957. 'position',
  12958. new BufferAttribute(
  12959. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12960. 3
  12961. )
  12962. );
  12963. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12964. const scope = this;
  12965. this.enabled = false;
  12966. this.autoUpdate = true;
  12967. this.needsUpdate = false;
  12968. this.type = PCFShadowMap;
  12969. this.render = function ( lights, scene, camera ) {
  12970. if ( scope.enabled === false ) return;
  12971. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12972. if ( lights.length === 0 ) return;
  12973. const currentRenderTarget = _renderer.getRenderTarget();
  12974. const activeCubeFace = _renderer.getActiveCubeFace();
  12975. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12976. const _state = _renderer.state;
  12977. // Set GL state for depth map.
  12978. _state.setBlending( NoBlending );
  12979. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12980. _state.buffers.depth.setTest( true );
  12981. _state.setScissorTest( false );
  12982. // render depth map
  12983. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12984. const light = lights[ i ];
  12985. const shadow = light.shadow;
  12986. if ( shadow === undefined ) {
  12987. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12988. continue;
  12989. }
  12990. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12991. _shadowMapSize.copy( shadow.mapSize );
  12992. const shadowFrameExtents = shadow.getFrameExtents();
  12993. _shadowMapSize.multiply( shadowFrameExtents );
  12994. _viewportSize.copy( shadow.mapSize );
  12995. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12996. if ( _shadowMapSize.x > _maxTextureSize ) {
  12997. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12998. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12999. shadow.mapSize.x = _viewportSize.x;
  13000. }
  13001. if ( _shadowMapSize.y > _maxTextureSize ) {
  13002. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13003. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13004. shadow.mapSize.y = _viewportSize.y;
  13005. }
  13006. }
  13007. if ( shadow.map === null ) {
  13008. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13009. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13010. shadow.map.texture.name = light.name + '.shadowMap';
  13011. shadow.camera.updateProjectionMatrix();
  13012. }
  13013. _renderer.setRenderTarget( shadow.map );
  13014. _renderer.clear();
  13015. const viewportCount = shadow.getViewportCount();
  13016. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13017. const viewport = shadow.getViewport( vp );
  13018. _viewport.set(
  13019. _viewportSize.x * viewport.x,
  13020. _viewportSize.y * viewport.y,
  13021. _viewportSize.x * viewport.z,
  13022. _viewportSize.y * viewport.w
  13023. );
  13024. _state.viewport( _viewport );
  13025. shadow.updateMatrices( light, vp );
  13026. _frustum = shadow.getFrustum();
  13027. renderObject( scene, camera, shadow.camera, light, this.type );
  13028. }
  13029. // do blur pass for VSM
  13030. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13031. VSMPass( shadow, camera );
  13032. }
  13033. shadow.needsUpdate = false;
  13034. }
  13035. scope.needsUpdate = false;
  13036. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13037. };
  13038. function VSMPass( shadow, camera ) {
  13039. const geometry = _objects.update( fullScreenMesh );
  13040. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13041. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13042. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13043. shadowMaterialVertical.needsUpdate = true;
  13044. shadowMaterialHorizontal.needsUpdate = true;
  13045. }
  13046. if ( shadow.mapPass === null ) {
  13047. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13048. }
  13049. // vertical pass
  13050. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13051. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13052. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13053. _renderer.setRenderTarget( shadow.mapPass );
  13054. _renderer.clear();
  13055. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13056. // horizontal pass
  13057. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13058. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13059. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13060. _renderer.setRenderTarget( shadow.map );
  13061. _renderer.clear();
  13062. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13063. }
  13064. function getDepthMaterial( object, material, light, type ) {
  13065. let result = null;
  13066. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13067. if ( customMaterial !== undefined ) {
  13068. result = customMaterial;
  13069. } else {
  13070. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13071. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13072. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13073. ( material.alphaMap && material.alphaTest > 0 ) ||
  13074. ( material.map && material.alphaTest > 0 ) ) {
  13075. // in this case we need a unique material instance reflecting the
  13076. // appropriate state
  13077. const keyA = result.uuid, keyB = material.uuid;
  13078. let materialsForVariant = _materialCache[ keyA ];
  13079. if ( materialsForVariant === undefined ) {
  13080. materialsForVariant = {};
  13081. _materialCache[ keyA ] = materialsForVariant;
  13082. }
  13083. let cachedMaterial = materialsForVariant[ keyB ];
  13084. if ( cachedMaterial === undefined ) {
  13085. cachedMaterial = result.clone();
  13086. materialsForVariant[ keyB ] = cachedMaterial;
  13087. }
  13088. result = cachedMaterial;
  13089. }
  13090. }
  13091. result.visible = material.visible;
  13092. result.wireframe = material.wireframe;
  13093. if ( type === VSMShadowMap ) {
  13094. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13095. } else {
  13096. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13097. }
  13098. result.alphaMap = material.alphaMap;
  13099. result.alphaTest = material.alphaTest;
  13100. result.map = material.map;
  13101. result.clipShadows = material.clipShadows;
  13102. result.clippingPlanes = material.clippingPlanes;
  13103. result.clipIntersection = material.clipIntersection;
  13104. result.displacementMap = material.displacementMap;
  13105. result.displacementScale = material.displacementScale;
  13106. result.displacementBias = material.displacementBias;
  13107. result.wireframeLinewidth = material.wireframeLinewidth;
  13108. result.linewidth = material.linewidth;
  13109. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13110. const materialProperties = _renderer.properties.get( result );
  13111. materialProperties.light = light;
  13112. }
  13113. return result;
  13114. }
  13115. function renderObject( object, camera, shadowCamera, light, type ) {
  13116. if ( object.visible === false ) return;
  13117. const visible = object.layers.test( camera.layers );
  13118. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13119. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13120. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13121. const geometry = _objects.update( object );
  13122. const material = object.material;
  13123. if ( Array.isArray( material ) ) {
  13124. const groups = geometry.groups;
  13125. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13126. const group = groups[ k ];
  13127. const groupMaterial = material[ group.materialIndex ];
  13128. if ( groupMaterial && groupMaterial.visible ) {
  13129. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13130. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13131. }
  13132. }
  13133. } else if ( material.visible ) {
  13134. const depthMaterial = getDepthMaterial( object, material, light, type );
  13135. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13136. }
  13137. }
  13138. }
  13139. const children = object.children;
  13140. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13141. renderObject( children[ i ], camera, shadowCamera, light, type );
  13142. }
  13143. }
  13144. }
  13145. function WebGLState( gl, extensions, capabilities ) {
  13146. const isWebGL2 = capabilities.isWebGL2;
  13147. function ColorBuffer() {
  13148. let locked = false;
  13149. const color = new Vector4();
  13150. let currentColorMask = null;
  13151. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13152. return {
  13153. setMask: function ( colorMask ) {
  13154. if ( currentColorMask !== colorMask && ! locked ) {
  13155. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13156. currentColorMask = colorMask;
  13157. }
  13158. },
  13159. setLocked: function ( lock ) {
  13160. locked = lock;
  13161. },
  13162. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13163. if ( premultipliedAlpha === true ) {
  13164. r *= a; g *= a; b *= a;
  13165. }
  13166. color.set( r, g, b, a );
  13167. if ( currentColorClear.equals( color ) === false ) {
  13168. gl.clearColor( r, g, b, a );
  13169. currentColorClear.copy( color );
  13170. }
  13171. },
  13172. reset: function () {
  13173. locked = false;
  13174. currentColorMask = null;
  13175. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13176. }
  13177. };
  13178. }
  13179. function DepthBuffer() {
  13180. let locked = false;
  13181. let currentDepthMask = null;
  13182. let currentDepthFunc = null;
  13183. let currentDepthClear = null;
  13184. return {
  13185. setTest: function ( depthTest ) {
  13186. if ( depthTest ) {
  13187. enable( 2929 );
  13188. } else {
  13189. disable( 2929 );
  13190. }
  13191. },
  13192. setMask: function ( depthMask ) {
  13193. if ( currentDepthMask !== depthMask && ! locked ) {
  13194. gl.depthMask( depthMask );
  13195. currentDepthMask = depthMask;
  13196. }
  13197. },
  13198. setFunc: function ( depthFunc ) {
  13199. if ( currentDepthFunc !== depthFunc ) {
  13200. switch ( depthFunc ) {
  13201. case NeverDepth:
  13202. gl.depthFunc( 512 );
  13203. break;
  13204. case AlwaysDepth:
  13205. gl.depthFunc( 519 );
  13206. break;
  13207. case LessDepth:
  13208. gl.depthFunc( 513 );
  13209. break;
  13210. case LessEqualDepth:
  13211. gl.depthFunc( 515 );
  13212. break;
  13213. case EqualDepth:
  13214. gl.depthFunc( 514 );
  13215. break;
  13216. case GreaterEqualDepth:
  13217. gl.depthFunc( 518 );
  13218. break;
  13219. case GreaterDepth:
  13220. gl.depthFunc( 516 );
  13221. break;
  13222. case NotEqualDepth:
  13223. gl.depthFunc( 517 );
  13224. break;
  13225. default:
  13226. gl.depthFunc( 515 );
  13227. }
  13228. currentDepthFunc = depthFunc;
  13229. }
  13230. },
  13231. setLocked: function ( lock ) {
  13232. locked = lock;
  13233. },
  13234. setClear: function ( depth ) {
  13235. if ( currentDepthClear !== depth ) {
  13236. gl.clearDepth( depth );
  13237. currentDepthClear = depth;
  13238. }
  13239. },
  13240. reset: function () {
  13241. locked = false;
  13242. currentDepthMask = null;
  13243. currentDepthFunc = null;
  13244. currentDepthClear = null;
  13245. }
  13246. };
  13247. }
  13248. function StencilBuffer() {
  13249. let locked = false;
  13250. let currentStencilMask = null;
  13251. let currentStencilFunc = null;
  13252. let currentStencilRef = null;
  13253. let currentStencilFuncMask = null;
  13254. let currentStencilFail = null;
  13255. let currentStencilZFail = null;
  13256. let currentStencilZPass = null;
  13257. let currentStencilClear = null;
  13258. return {
  13259. setTest: function ( stencilTest ) {
  13260. if ( ! locked ) {
  13261. if ( stencilTest ) {
  13262. enable( 2960 );
  13263. } else {
  13264. disable( 2960 );
  13265. }
  13266. }
  13267. },
  13268. setMask: function ( stencilMask ) {
  13269. if ( currentStencilMask !== stencilMask && ! locked ) {
  13270. gl.stencilMask( stencilMask );
  13271. currentStencilMask = stencilMask;
  13272. }
  13273. },
  13274. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13275. if ( currentStencilFunc !== stencilFunc ||
  13276. currentStencilRef !== stencilRef ||
  13277. currentStencilFuncMask !== stencilMask ) {
  13278. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13279. currentStencilFunc = stencilFunc;
  13280. currentStencilRef = stencilRef;
  13281. currentStencilFuncMask = stencilMask;
  13282. }
  13283. },
  13284. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13285. if ( currentStencilFail !== stencilFail ||
  13286. currentStencilZFail !== stencilZFail ||
  13287. currentStencilZPass !== stencilZPass ) {
  13288. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13289. currentStencilFail = stencilFail;
  13290. currentStencilZFail = stencilZFail;
  13291. currentStencilZPass = stencilZPass;
  13292. }
  13293. },
  13294. setLocked: function ( lock ) {
  13295. locked = lock;
  13296. },
  13297. setClear: function ( stencil ) {
  13298. if ( currentStencilClear !== stencil ) {
  13299. gl.clearStencil( stencil );
  13300. currentStencilClear = stencil;
  13301. }
  13302. },
  13303. reset: function () {
  13304. locked = false;
  13305. currentStencilMask = null;
  13306. currentStencilFunc = null;
  13307. currentStencilRef = null;
  13308. currentStencilFuncMask = null;
  13309. currentStencilFail = null;
  13310. currentStencilZFail = null;
  13311. currentStencilZPass = null;
  13312. currentStencilClear = null;
  13313. }
  13314. };
  13315. }
  13316. //
  13317. const colorBuffer = new ColorBuffer();
  13318. const depthBuffer = new DepthBuffer();
  13319. const stencilBuffer = new StencilBuffer();
  13320. const uboBindings = new WeakMap();
  13321. const uboProgramMap = new WeakMap();
  13322. let enabledCapabilities = {};
  13323. let currentBoundFramebuffers = {};
  13324. let currentDrawbuffers = new WeakMap();
  13325. let defaultDrawbuffers = [];
  13326. let currentProgram = null;
  13327. let currentBlendingEnabled = false;
  13328. let currentBlending = null;
  13329. let currentBlendEquation = null;
  13330. let currentBlendSrc = null;
  13331. let currentBlendDst = null;
  13332. let currentBlendEquationAlpha = null;
  13333. let currentBlendSrcAlpha = null;
  13334. let currentBlendDstAlpha = null;
  13335. let currentPremultipledAlpha = false;
  13336. let currentFlipSided = null;
  13337. let currentCullFace = null;
  13338. let currentLineWidth = null;
  13339. let currentPolygonOffsetFactor = null;
  13340. let currentPolygonOffsetUnits = null;
  13341. const maxTextures = gl.getParameter( 35661 );
  13342. let lineWidthAvailable = false;
  13343. let version = 0;
  13344. const glVersion = gl.getParameter( 7938 );
  13345. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13346. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13347. lineWidthAvailable = ( version >= 1.0 );
  13348. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13349. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13350. lineWidthAvailable = ( version >= 2.0 );
  13351. }
  13352. let currentTextureSlot = null;
  13353. let currentBoundTextures = {};
  13354. const scissorParam = gl.getParameter( 3088 );
  13355. const viewportParam = gl.getParameter( 2978 );
  13356. const currentScissor = new Vector4().fromArray( scissorParam );
  13357. const currentViewport = new Vector4().fromArray( viewportParam );
  13358. function createTexture( type, target, count ) {
  13359. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13360. const texture = gl.createTexture();
  13361. gl.bindTexture( type, texture );
  13362. gl.texParameteri( type, 10241, 9728 );
  13363. gl.texParameteri( type, 10240, 9728 );
  13364. for ( let i = 0; i < count; i ++ ) {
  13365. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  13366. }
  13367. return texture;
  13368. }
  13369. const emptyTextures = {};
  13370. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  13371. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  13372. // init
  13373. colorBuffer.setClear( 0, 0, 0, 1 );
  13374. depthBuffer.setClear( 1 );
  13375. stencilBuffer.setClear( 0 );
  13376. enable( 2929 );
  13377. depthBuffer.setFunc( LessEqualDepth );
  13378. setFlipSided( false );
  13379. setCullFace( CullFaceBack );
  13380. enable( 2884 );
  13381. setBlending( NoBlending );
  13382. //
  13383. function enable( id ) {
  13384. if ( enabledCapabilities[ id ] !== true ) {
  13385. gl.enable( id );
  13386. enabledCapabilities[ id ] = true;
  13387. }
  13388. }
  13389. function disable( id ) {
  13390. if ( enabledCapabilities[ id ] !== false ) {
  13391. gl.disable( id );
  13392. enabledCapabilities[ id ] = false;
  13393. }
  13394. }
  13395. function bindFramebuffer( target, framebuffer ) {
  13396. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13397. gl.bindFramebuffer( target, framebuffer );
  13398. currentBoundFramebuffers[ target ] = framebuffer;
  13399. if ( isWebGL2 ) {
  13400. // 36009 is equivalent to 36160
  13401. if ( target === 36009 ) {
  13402. currentBoundFramebuffers[ 36160 ] = framebuffer;
  13403. }
  13404. if ( target === 36160 ) {
  13405. currentBoundFramebuffers[ 36009 ] = framebuffer;
  13406. }
  13407. }
  13408. return true;
  13409. }
  13410. return false;
  13411. }
  13412. function drawBuffers( renderTarget, framebuffer ) {
  13413. let drawBuffers = defaultDrawbuffers;
  13414. let needsUpdate = false;
  13415. if ( renderTarget ) {
  13416. drawBuffers = currentDrawbuffers.get( framebuffer );
  13417. if ( drawBuffers === undefined ) {
  13418. drawBuffers = [];
  13419. currentDrawbuffers.set( framebuffer, drawBuffers );
  13420. }
  13421. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13422. const textures = renderTarget.texture;
  13423. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) {
  13424. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13425. drawBuffers[ i ] = 36064 + i;
  13426. }
  13427. drawBuffers.length = textures.length;
  13428. needsUpdate = true;
  13429. }
  13430. } else {
  13431. if ( drawBuffers[ 0 ] !== 36064 ) {
  13432. drawBuffers[ 0 ] = 36064;
  13433. needsUpdate = true;
  13434. }
  13435. }
  13436. } else {
  13437. if ( drawBuffers[ 0 ] !== 1029 ) {
  13438. drawBuffers[ 0 ] = 1029;
  13439. needsUpdate = true;
  13440. }
  13441. }
  13442. if ( needsUpdate ) {
  13443. if ( capabilities.isWebGL2 ) {
  13444. gl.drawBuffers( drawBuffers );
  13445. } else {
  13446. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13447. }
  13448. }
  13449. }
  13450. function useProgram( program ) {
  13451. if ( currentProgram !== program ) {
  13452. gl.useProgram( program );
  13453. currentProgram = program;
  13454. return true;
  13455. }
  13456. return false;
  13457. }
  13458. const equationToGL = {
  13459. [ AddEquation ]: 32774,
  13460. [ SubtractEquation ]: 32778,
  13461. [ ReverseSubtractEquation ]: 32779
  13462. };
  13463. if ( isWebGL2 ) {
  13464. equationToGL[ MinEquation ] = 32775;
  13465. equationToGL[ MaxEquation ] = 32776;
  13466. } else {
  13467. const extension = extensions.get( 'EXT_blend_minmax' );
  13468. if ( extension !== null ) {
  13469. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13470. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13471. }
  13472. }
  13473. const factorToGL = {
  13474. [ ZeroFactor ]: 0,
  13475. [ OneFactor ]: 1,
  13476. [ SrcColorFactor ]: 768,
  13477. [ SrcAlphaFactor ]: 770,
  13478. [ SrcAlphaSaturateFactor ]: 776,
  13479. [ DstColorFactor ]: 774,
  13480. [ DstAlphaFactor ]: 772,
  13481. [ OneMinusSrcColorFactor ]: 769,
  13482. [ OneMinusSrcAlphaFactor ]: 771,
  13483. [ OneMinusDstColorFactor ]: 775,
  13484. [ OneMinusDstAlphaFactor ]: 773
  13485. };
  13486. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13487. if ( blending === NoBlending ) {
  13488. if ( currentBlendingEnabled === true ) {
  13489. disable( 3042 );
  13490. currentBlendingEnabled = false;
  13491. }
  13492. return;
  13493. }
  13494. if ( currentBlendingEnabled === false ) {
  13495. enable( 3042 );
  13496. currentBlendingEnabled = true;
  13497. }
  13498. if ( blending !== CustomBlending ) {
  13499. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13500. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13501. gl.blendEquation( 32774 );
  13502. currentBlendEquation = AddEquation;
  13503. currentBlendEquationAlpha = AddEquation;
  13504. }
  13505. if ( premultipliedAlpha ) {
  13506. switch ( blending ) {
  13507. case NormalBlending:
  13508. gl.blendFuncSeparate( 1, 771, 1, 771 );
  13509. break;
  13510. case AdditiveBlending:
  13511. gl.blendFunc( 1, 1 );
  13512. break;
  13513. case SubtractiveBlending:
  13514. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13515. break;
  13516. case MultiplyBlending:
  13517. gl.blendFuncSeparate( 0, 768, 0, 770 );
  13518. break;
  13519. default:
  13520. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13521. break;
  13522. }
  13523. } else {
  13524. switch ( blending ) {
  13525. case NormalBlending:
  13526. gl.blendFuncSeparate( 770, 771, 1, 771 );
  13527. break;
  13528. case AdditiveBlending:
  13529. gl.blendFunc( 770, 1 );
  13530. break;
  13531. case SubtractiveBlending:
  13532. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13533. break;
  13534. case MultiplyBlending:
  13535. gl.blendFunc( 0, 768 );
  13536. break;
  13537. default:
  13538. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13539. break;
  13540. }
  13541. }
  13542. currentBlendSrc = null;
  13543. currentBlendDst = null;
  13544. currentBlendSrcAlpha = null;
  13545. currentBlendDstAlpha = null;
  13546. currentBlending = blending;
  13547. currentPremultipledAlpha = premultipliedAlpha;
  13548. }
  13549. return;
  13550. }
  13551. // custom blending
  13552. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13553. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13554. blendDstAlpha = blendDstAlpha || blendDst;
  13555. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13556. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13557. currentBlendEquation = blendEquation;
  13558. currentBlendEquationAlpha = blendEquationAlpha;
  13559. }
  13560. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13561. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13562. currentBlendSrc = blendSrc;
  13563. currentBlendDst = blendDst;
  13564. currentBlendSrcAlpha = blendSrcAlpha;
  13565. currentBlendDstAlpha = blendDstAlpha;
  13566. }
  13567. currentBlending = blending;
  13568. currentPremultipledAlpha = false;
  13569. }
  13570. function setMaterial( material, frontFaceCW ) {
  13571. material.side === DoubleSide
  13572. ? disable( 2884 )
  13573. : enable( 2884 );
  13574. let flipSided = ( material.side === BackSide );
  13575. if ( frontFaceCW ) flipSided = ! flipSided;
  13576. setFlipSided( flipSided );
  13577. ( material.blending === NormalBlending && material.transparent === false )
  13578. ? setBlending( NoBlending )
  13579. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13580. depthBuffer.setFunc( material.depthFunc );
  13581. depthBuffer.setTest( material.depthTest );
  13582. depthBuffer.setMask( material.depthWrite );
  13583. colorBuffer.setMask( material.colorWrite );
  13584. const stencilWrite = material.stencilWrite;
  13585. stencilBuffer.setTest( stencilWrite );
  13586. if ( stencilWrite ) {
  13587. stencilBuffer.setMask( material.stencilWriteMask );
  13588. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13589. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13590. }
  13591. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13592. material.alphaToCoverage === true
  13593. ? enable( 32926 )
  13594. : disable( 32926 );
  13595. }
  13596. //
  13597. function setFlipSided( flipSided ) {
  13598. if ( currentFlipSided !== flipSided ) {
  13599. if ( flipSided ) {
  13600. gl.frontFace( 2304 );
  13601. } else {
  13602. gl.frontFace( 2305 );
  13603. }
  13604. currentFlipSided = flipSided;
  13605. }
  13606. }
  13607. function setCullFace( cullFace ) {
  13608. if ( cullFace !== CullFaceNone ) {
  13609. enable( 2884 );
  13610. if ( cullFace !== currentCullFace ) {
  13611. if ( cullFace === CullFaceBack ) {
  13612. gl.cullFace( 1029 );
  13613. } else if ( cullFace === CullFaceFront ) {
  13614. gl.cullFace( 1028 );
  13615. } else {
  13616. gl.cullFace( 1032 );
  13617. }
  13618. }
  13619. } else {
  13620. disable( 2884 );
  13621. }
  13622. currentCullFace = cullFace;
  13623. }
  13624. function setLineWidth( width ) {
  13625. if ( width !== currentLineWidth ) {
  13626. if ( lineWidthAvailable ) gl.lineWidth( width );
  13627. currentLineWidth = width;
  13628. }
  13629. }
  13630. function setPolygonOffset( polygonOffset, factor, units ) {
  13631. if ( polygonOffset ) {
  13632. enable( 32823 );
  13633. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13634. gl.polygonOffset( factor, units );
  13635. currentPolygonOffsetFactor = factor;
  13636. currentPolygonOffsetUnits = units;
  13637. }
  13638. } else {
  13639. disable( 32823 );
  13640. }
  13641. }
  13642. function setScissorTest( scissorTest ) {
  13643. if ( scissorTest ) {
  13644. enable( 3089 );
  13645. } else {
  13646. disable( 3089 );
  13647. }
  13648. }
  13649. // texture
  13650. function activeTexture( webglSlot ) {
  13651. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  13652. if ( currentTextureSlot !== webglSlot ) {
  13653. gl.activeTexture( webglSlot );
  13654. currentTextureSlot = webglSlot;
  13655. }
  13656. }
  13657. function bindTexture( webglType, webglTexture, webglSlot ) {
  13658. if ( webglSlot === undefined ) {
  13659. if ( currentTextureSlot === null ) {
  13660. webglSlot = 33984 + maxTextures - 1;
  13661. } else {
  13662. webglSlot = currentTextureSlot;
  13663. }
  13664. }
  13665. let boundTexture = currentBoundTextures[ webglSlot ];
  13666. if ( boundTexture === undefined ) {
  13667. boundTexture = { type: undefined, texture: undefined };
  13668. currentBoundTextures[ webglSlot ] = boundTexture;
  13669. }
  13670. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13671. if ( currentTextureSlot !== webglSlot ) {
  13672. gl.activeTexture( webglSlot );
  13673. currentTextureSlot = webglSlot;
  13674. }
  13675. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13676. boundTexture.type = webglType;
  13677. boundTexture.texture = webglTexture;
  13678. }
  13679. }
  13680. function unbindTexture() {
  13681. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13682. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13683. gl.bindTexture( boundTexture.type, null );
  13684. boundTexture.type = undefined;
  13685. boundTexture.texture = undefined;
  13686. }
  13687. }
  13688. function compressedTexImage2D() {
  13689. try {
  13690. gl.compressedTexImage2D.apply( gl, arguments );
  13691. } catch ( error ) {
  13692. console.error( 'THREE.WebGLState:', error );
  13693. }
  13694. }
  13695. function compressedTexImage3D() {
  13696. try {
  13697. gl.compressedTexImage3D.apply( gl, arguments );
  13698. } catch ( error ) {
  13699. console.error( 'THREE.WebGLState:', error );
  13700. }
  13701. }
  13702. function texSubImage2D() {
  13703. try {
  13704. gl.texSubImage2D.apply( gl, arguments );
  13705. } catch ( error ) {
  13706. console.error( 'THREE.WebGLState:', error );
  13707. }
  13708. }
  13709. function texSubImage3D() {
  13710. try {
  13711. gl.texSubImage3D.apply( gl, arguments );
  13712. } catch ( error ) {
  13713. console.error( 'THREE.WebGLState:', error );
  13714. }
  13715. }
  13716. function compressedTexSubImage2D() {
  13717. try {
  13718. gl.compressedTexSubImage2D.apply( gl, arguments );
  13719. } catch ( error ) {
  13720. console.error( 'THREE.WebGLState:', error );
  13721. }
  13722. }
  13723. function compressedTexSubImage3D() {
  13724. try {
  13725. gl.compressedTexSubImage3D.apply( gl, arguments );
  13726. } catch ( error ) {
  13727. console.error( 'THREE.WebGLState:', error );
  13728. }
  13729. }
  13730. function texStorage2D() {
  13731. try {
  13732. gl.texStorage2D.apply( gl, arguments );
  13733. } catch ( error ) {
  13734. console.error( 'THREE.WebGLState:', error );
  13735. }
  13736. }
  13737. function texStorage3D() {
  13738. try {
  13739. gl.texStorage3D.apply( gl, arguments );
  13740. } catch ( error ) {
  13741. console.error( 'THREE.WebGLState:', error );
  13742. }
  13743. }
  13744. function texImage2D() {
  13745. try {
  13746. gl.texImage2D.apply( gl, arguments );
  13747. } catch ( error ) {
  13748. console.error( 'THREE.WebGLState:', error );
  13749. }
  13750. }
  13751. function texImage3D() {
  13752. try {
  13753. gl.texImage3D.apply( gl, arguments );
  13754. } catch ( error ) {
  13755. console.error( 'THREE.WebGLState:', error );
  13756. }
  13757. }
  13758. //
  13759. function scissor( scissor ) {
  13760. if ( currentScissor.equals( scissor ) === false ) {
  13761. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13762. currentScissor.copy( scissor );
  13763. }
  13764. }
  13765. function viewport( viewport ) {
  13766. if ( currentViewport.equals( viewport ) === false ) {
  13767. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13768. currentViewport.copy( viewport );
  13769. }
  13770. }
  13771. function updateUBOMapping( uniformsGroup, program ) {
  13772. let mapping = uboProgramMap.get( program );
  13773. if ( mapping === undefined ) {
  13774. mapping = new WeakMap();
  13775. uboProgramMap.set( program, mapping );
  13776. }
  13777. let blockIndex = mapping.get( uniformsGroup );
  13778. if ( blockIndex === undefined ) {
  13779. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13780. mapping.set( uniformsGroup, blockIndex );
  13781. }
  13782. }
  13783. function uniformBlockBinding( uniformsGroup, program ) {
  13784. const mapping = uboProgramMap.get( program );
  13785. const blockIndex = mapping.get( uniformsGroup );
  13786. if ( uboBindings.get( program ) !== blockIndex ) {
  13787. // bind shader specific block index to global block point
  13788. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13789. uboBindings.set( program, blockIndex );
  13790. }
  13791. }
  13792. //
  13793. function reset() {
  13794. // reset state
  13795. gl.disable( 3042 );
  13796. gl.disable( 2884 );
  13797. gl.disable( 2929 );
  13798. gl.disable( 32823 );
  13799. gl.disable( 3089 );
  13800. gl.disable( 2960 );
  13801. gl.disable( 32926 );
  13802. gl.blendEquation( 32774 );
  13803. gl.blendFunc( 1, 0 );
  13804. gl.blendFuncSeparate( 1, 0, 1, 0 );
  13805. gl.colorMask( true, true, true, true );
  13806. gl.clearColor( 0, 0, 0, 0 );
  13807. gl.depthMask( true );
  13808. gl.depthFunc( 513 );
  13809. gl.clearDepth( 1 );
  13810. gl.stencilMask( 0xffffffff );
  13811. gl.stencilFunc( 519, 0, 0xffffffff );
  13812. gl.stencilOp( 7680, 7680, 7680 );
  13813. gl.clearStencil( 0 );
  13814. gl.cullFace( 1029 );
  13815. gl.frontFace( 2305 );
  13816. gl.polygonOffset( 0, 0 );
  13817. gl.activeTexture( 33984 );
  13818. gl.bindFramebuffer( 36160, null );
  13819. if ( isWebGL2 === true ) {
  13820. gl.bindFramebuffer( 36009, null );
  13821. gl.bindFramebuffer( 36008, null );
  13822. }
  13823. gl.useProgram( null );
  13824. gl.lineWidth( 1 );
  13825. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13826. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13827. // reset internals
  13828. enabledCapabilities = {};
  13829. currentTextureSlot = null;
  13830. currentBoundTextures = {};
  13831. currentBoundFramebuffers = {};
  13832. currentDrawbuffers = new WeakMap();
  13833. defaultDrawbuffers = [];
  13834. currentProgram = null;
  13835. currentBlendingEnabled = false;
  13836. currentBlending = null;
  13837. currentBlendEquation = null;
  13838. currentBlendSrc = null;
  13839. currentBlendDst = null;
  13840. currentBlendEquationAlpha = null;
  13841. currentBlendSrcAlpha = null;
  13842. currentBlendDstAlpha = null;
  13843. currentPremultipledAlpha = false;
  13844. currentFlipSided = null;
  13845. currentCullFace = null;
  13846. currentLineWidth = null;
  13847. currentPolygonOffsetFactor = null;
  13848. currentPolygonOffsetUnits = null;
  13849. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13850. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13851. colorBuffer.reset();
  13852. depthBuffer.reset();
  13853. stencilBuffer.reset();
  13854. }
  13855. return {
  13856. buffers: {
  13857. color: colorBuffer,
  13858. depth: depthBuffer,
  13859. stencil: stencilBuffer
  13860. },
  13861. enable: enable,
  13862. disable: disable,
  13863. bindFramebuffer: bindFramebuffer,
  13864. drawBuffers: drawBuffers,
  13865. useProgram: useProgram,
  13866. setBlending: setBlending,
  13867. setMaterial: setMaterial,
  13868. setFlipSided: setFlipSided,
  13869. setCullFace: setCullFace,
  13870. setLineWidth: setLineWidth,
  13871. setPolygonOffset: setPolygonOffset,
  13872. setScissorTest: setScissorTest,
  13873. activeTexture: activeTexture,
  13874. bindTexture: bindTexture,
  13875. unbindTexture: unbindTexture,
  13876. compressedTexImage2D: compressedTexImage2D,
  13877. compressedTexImage3D: compressedTexImage3D,
  13878. texImage2D: texImage2D,
  13879. texImage3D: texImage3D,
  13880. updateUBOMapping: updateUBOMapping,
  13881. uniformBlockBinding: uniformBlockBinding,
  13882. texStorage2D: texStorage2D,
  13883. texStorage3D: texStorage3D,
  13884. texSubImage2D: texSubImage2D,
  13885. texSubImage3D: texSubImage3D,
  13886. compressedTexSubImage2D: compressedTexSubImage2D,
  13887. compressedTexSubImage3D: compressedTexSubImage3D,
  13888. scissor: scissor,
  13889. viewport: viewport,
  13890. reset: reset
  13891. };
  13892. }
  13893. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13894. const isWebGL2 = capabilities.isWebGL2;
  13895. const maxTextures = capabilities.maxTextures;
  13896. const maxCubemapSize = capabilities.maxCubemapSize;
  13897. const maxTextureSize = capabilities.maxTextureSize;
  13898. const maxSamples = capabilities.maxSamples;
  13899. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13900. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  13901. const _videoTextures = new WeakMap();
  13902. let _canvas;
  13903. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13904. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13905. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13906. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13907. let useOffscreenCanvas = false;
  13908. try {
  13909. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13910. // eslint-disable-next-line compat/compat
  13911. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13912. } catch ( err ) {
  13913. // Ignore any errors
  13914. }
  13915. function createCanvas( width, height ) {
  13916. // Use OffscreenCanvas when available. Specially needed in web workers
  13917. return useOffscreenCanvas ?
  13918. // eslint-disable-next-line compat/compat
  13919. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13920. }
  13921. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13922. let scale = 1;
  13923. // handle case if texture exceeds max size
  13924. if ( image.width > maxSize || image.height > maxSize ) {
  13925. scale = maxSize / Math.max( image.width, image.height );
  13926. }
  13927. // only perform resize if necessary
  13928. if ( scale < 1 || needsPowerOfTwo === true ) {
  13929. // only perform resize for certain image types
  13930. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13931. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13932. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13933. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13934. const width = floor( scale * image.width );
  13935. const height = floor( scale * image.height );
  13936. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13937. // cube textures can't reuse the same canvas
  13938. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13939. canvas.width = width;
  13940. canvas.height = height;
  13941. const context = canvas.getContext( '2d' );
  13942. context.drawImage( image, 0, 0, width, height );
  13943. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13944. return canvas;
  13945. } else {
  13946. if ( 'data' in image ) {
  13947. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13948. }
  13949. return image;
  13950. }
  13951. }
  13952. return image;
  13953. }
  13954. function isPowerOfTwo$1( image ) {
  13955. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13956. }
  13957. function textureNeedsPowerOfTwo( texture ) {
  13958. if ( isWebGL2 ) return false;
  13959. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13960. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13961. }
  13962. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13963. return texture.generateMipmaps && supportsMips &&
  13964. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13965. }
  13966. function generateMipmap( target ) {
  13967. _gl.generateMipmap( target );
  13968. }
  13969. function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) {
  13970. if ( isWebGL2 === false ) return glFormat;
  13971. if ( internalFormatName !== null ) {
  13972. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13973. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13974. }
  13975. let internalFormat = glFormat;
  13976. if ( glFormat === 6403 ) {
  13977. if ( glType === 5126 ) internalFormat = 33326;
  13978. if ( glType === 5131 ) internalFormat = 33325;
  13979. if ( glType === 5121 ) internalFormat = 33321;
  13980. }
  13981. if ( glFormat === 33319 ) {
  13982. if ( glType === 5126 ) internalFormat = 33328;
  13983. if ( glType === 5131 ) internalFormat = 33327;
  13984. if ( glType === 5121 ) internalFormat = 33323;
  13985. }
  13986. if ( glFormat === 6408 ) {
  13987. if ( glType === 5126 ) internalFormat = 34836;
  13988. if ( glType === 5131 ) internalFormat = 34842;
  13989. if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? 35907 : 32856;
  13990. if ( glType === 32819 ) internalFormat = 32854;
  13991. if ( glType === 32820 ) internalFormat = 32855;
  13992. }
  13993. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13994. internalFormat === 33327 || internalFormat === 33328 ||
  13995. internalFormat === 34842 || internalFormat === 34836 ) {
  13996. extensions.get( 'EXT_color_buffer_float' );
  13997. }
  13998. return internalFormat;
  13999. }
  14000. function getMipLevels( texture, image, supportsMips ) {
  14001. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14002. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14003. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14004. // user-defined mipmaps
  14005. return texture.mipmaps.length;
  14006. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14007. return image.mipmaps.length;
  14008. } else {
  14009. // texture without mipmaps (only base level)
  14010. return 1;
  14011. }
  14012. }
  14013. // Fallback filters for non-power-of-2 textures
  14014. function filterFallback( f ) {
  14015. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  14016. return 9728;
  14017. }
  14018. return 9729;
  14019. }
  14020. //
  14021. function onTextureDispose( event ) {
  14022. const texture = event.target;
  14023. texture.removeEventListener( 'dispose', onTextureDispose );
  14024. deallocateTexture( texture );
  14025. if ( texture.isVideoTexture ) {
  14026. _videoTextures.delete( texture );
  14027. }
  14028. }
  14029. function onRenderTargetDispose( event ) {
  14030. const renderTarget = event.target;
  14031. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14032. deallocateRenderTarget( renderTarget );
  14033. }
  14034. //
  14035. function deallocateTexture( texture ) {
  14036. const textureProperties = properties.get( texture );
  14037. if ( textureProperties.__webglInit === undefined ) return;
  14038. // check if it's necessary to remove the WebGLTexture object
  14039. const source = texture.source;
  14040. const webglTextures = _sources.get( source );
  14041. if ( webglTextures ) {
  14042. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14043. webglTexture.usedTimes --;
  14044. // the WebGLTexture object is not used anymore, remove it
  14045. if ( webglTexture.usedTimes === 0 ) {
  14046. deleteTexture( texture );
  14047. }
  14048. // remove the weak map entry if no WebGLTexture uses the source anymore
  14049. if ( Object.keys( webglTextures ).length === 0 ) {
  14050. _sources.delete( source );
  14051. }
  14052. }
  14053. properties.remove( texture );
  14054. }
  14055. function deleteTexture( texture ) {
  14056. const textureProperties = properties.get( texture );
  14057. _gl.deleteTexture( textureProperties.__webglTexture );
  14058. const source = texture.source;
  14059. const webglTextures = _sources.get( source );
  14060. delete webglTextures[ textureProperties.__cacheKey ];
  14061. info.memory.textures --;
  14062. }
  14063. function deallocateRenderTarget( renderTarget ) {
  14064. const texture = renderTarget.texture;
  14065. const renderTargetProperties = properties.get( renderTarget );
  14066. const textureProperties = properties.get( texture );
  14067. if ( textureProperties.__webglTexture !== undefined ) {
  14068. _gl.deleteTexture( textureProperties.__webglTexture );
  14069. info.memory.textures --;
  14070. }
  14071. if ( renderTarget.depthTexture ) {
  14072. renderTarget.depthTexture.dispose();
  14073. }
  14074. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14075. for ( let i = 0; i < 6; i ++ ) {
  14076. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14077. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14078. }
  14079. } else {
  14080. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14081. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14082. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14083. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14084. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14085. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14086. }
  14087. }
  14088. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14089. }
  14090. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  14091. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  14092. const attachmentProperties = properties.get( texture[ i ] );
  14093. if ( attachmentProperties.__webglTexture ) {
  14094. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14095. info.memory.textures --;
  14096. }
  14097. properties.remove( texture[ i ] );
  14098. }
  14099. }
  14100. properties.remove( texture );
  14101. properties.remove( renderTarget );
  14102. }
  14103. //
  14104. let textureUnits = 0;
  14105. function resetTextureUnits() {
  14106. textureUnits = 0;
  14107. }
  14108. function allocateTextureUnit() {
  14109. const textureUnit = textureUnits;
  14110. if ( textureUnit >= maxTextures ) {
  14111. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  14112. }
  14113. textureUnits += 1;
  14114. return textureUnit;
  14115. }
  14116. function getTextureCacheKey( texture ) {
  14117. const array = [];
  14118. array.push( texture.wrapS );
  14119. array.push( texture.wrapT );
  14120. array.push( texture.wrapR || 0 );
  14121. array.push( texture.magFilter );
  14122. array.push( texture.minFilter );
  14123. array.push( texture.anisotropy );
  14124. array.push( texture.internalFormat );
  14125. array.push( texture.format );
  14126. array.push( texture.type );
  14127. array.push( texture.generateMipmaps );
  14128. array.push( texture.premultiplyAlpha );
  14129. array.push( texture.flipY );
  14130. array.push( texture.unpackAlignment );
  14131. array.push( texture.encoding );
  14132. return array.join();
  14133. }
  14134. //
  14135. function setTexture2D( texture, slot ) {
  14136. const textureProperties = properties.get( texture );
  14137. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14138. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14139. const image = texture.image;
  14140. if ( image === null ) {
  14141. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14142. } else if ( image.complete === false ) {
  14143. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14144. } else {
  14145. uploadTexture( textureProperties, texture, slot );
  14146. return;
  14147. }
  14148. }
  14149. state.bindTexture( 3553, textureProperties.__webglTexture, 33984 + slot );
  14150. }
  14151. function setTexture2DArray( texture, slot ) {
  14152. const textureProperties = properties.get( texture );
  14153. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14154. uploadTexture( textureProperties, texture, slot );
  14155. return;
  14156. }
  14157. state.bindTexture( 35866, textureProperties.__webglTexture, 33984 + slot );
  14158. }
  14159. function setTexture3D( texture, slot ) {
  14160. const textureProperties = properties.get( texture );
  14161. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14162. uploadTexture( textureProperties, texture, slot );
  14163. return;
  14164. }
  14165. state.bindTexture( 32879, textureProperties.__webglTexture, 33984 + slot );
  14166. }
  14167. function setTextureCube( texture, slot ) {
  14168. const textureProperties = properties.get( texture );
  14169. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14170. uploadCubeTexture( textureProperties, texture, slot );
  14171. return;
  14172. }
  14173. state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot );
  14174. }
  14175. const wrappingToGL = {
  14176. [ RepeatWrapping ]: 10497,
  14177. [ ClampToEdgeWrapping ]: 33071,
  14178. [ MirroredRepeatWrapping ]: 33648
  14179. };
  14180. const filterToGL = {
  14181. [ NearestFilter ]: 9728,
  14182. [ NearestMipmapNearestFilter ]: 9984,
  14183. [ NearestMipmapLinearFilter ]: 9986,
  14184. [ LinearFilter ]: 9729,
  14185. [ LinearMipmapNearestFilter ]: 9985,
  14186. [ LinearMipmapLinearFilter ]: 9987
  14187. };
  14188. function setTextureParameters( textureType, texture, supportsMips ) {
  14189. if ( supportsMips ) {
  14190. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  14191. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  14192. if ( textureType === 32879 || textureType === 35866 ) {
  14193. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  14194. }
  14195. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  14196. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  14197. } else {
  14198. _gl.texParameteri( textureType, 10242, 33071 );
  14199. _gl.texParameteri( textureType, 10243, 33071 );
  14200. if ( textureType === 32879 || textureType === 35866 ) {
  14201. _gl.texParameteri( textureType, 32882, 33071 );
  14202. }
  14203. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14204. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14205. }
  14206. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  14207. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  14208. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14209. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14210. }
  14211. }
  14212. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14213. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14214. if ( texture.magFilter === NearestFilter ) return;
  14215. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14216. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14217. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14218. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14219. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14220. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14221. }
  14222. }
  14223. }
  14224. function initTexture( textureProperties, texture ) {
  14225. let forceUpload = false;
  14226. if ( textureProperties.__webglInit === undefined ) {
  14227. textureProperties.__webglInit = true;
  14228. texture.addEventListener( 'dispose', onTextureDispose );
  14229. }
  14230. // create Source <-> WebGLTextures mapping if necessary
  14231. const source = texture.source;
  14232. let webglTextures = _sources.get( source );
  14233. if ( webglTextures === undefined ) {
  14234. webglTextures = {};
  14235. _sources.set( source, webglTextures );
  14236. }
  14237. // check if there is already a WebGLTexture object for the given texture parameters
  14238. const textureCacheKey = getTextureCacheKey( texture );
  14239. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14240. // if not, create a new instance of WebGLTexture
  14241. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14242. // create new entry
  14243. webglTextures[ textureCacheKey ] = {
  14244. texture: _gl.createTexture(),
  14245. usedTimes: 0
  14246. };
  14247. info.memory.textures ++;
  14248. // when a new instance of WebGLTexture was created, a texture upload is required
  14249. // even if the image contents are identical
  14250. forceUpload = true;
  14251. }
  14252. webglTextures[ textureCacheKey ].usedTimes ++;
  14253. // every time the texture cache key changes, it's necessary to check if an instance of
  14254. // WebGLTexture can be deleted in order to avoid a memory leak.
  14255. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14256. if ( webglTexture !== undefined ) {
  14257. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14258. if ( webglTexture.usedTimes === 0 ) {
  14259. deleteTexture( texture );
  14260. }
  14261. }
  14262. // store references to cache key and WebGLTexture object
  14263. textureProperties.__cacheKey = textureCacheKey;
  14264. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14265. }
  14266. return forceUpload;
  14267. }
  14268. function uploadTexture( textureProperties, texture, slot ) {
  14269. let textureType = 3553;
  14270. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = 35866;
  14271. if ( texture.isData3DTexture ) textureType = 32879;
  14272. const forceUpload = initTexture( textureProperties, texture );
  14273. const source = texture.source;
  14274. state.bindTexture( textureType, textureProperties.__webglTexture, 33984 + slot );
  14275. const sourceProperties = properties.get( source );
  14276. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14277. state.activeTexture( 33984 + slot );
  14278. _gl.pixelStorei( 37440, texture.flipY );
  14279. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14280. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14281. _gl.pixelStorei( 37443, 0 );
  14282. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14283. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  14284. image = verifyColorSpace( texture, image );
  14285. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14286. glFormat = utils.convert( texture.format, texture.encoding );
  14287. let glType = utils.convert( texture.type ),
  14288. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  14289. setTextureParameters( textureType, texture, supportsMips );
  14290. let mipmap;
  14291. const mipmaps = texture.mipmaps;
  14292. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14293. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14294. const levels = getMipLevels( texture, image, supportsMips );
  14295. if ( texture.isDepthTexture ) {
  14296. // populate depth texture with dummy data
  14297. glInternalFormat = 6402;
  14298. if ( isWebGL2 ) {
  14299. if ( texture.type === FloatType ) {
  14300. glInternalFormat = 36012;
  14301. } else if ( texture.type === UnsignedIntType ) {
  14302. glInternalFormat = 33190;
  14303. } else if ( texture.type === UnsignedInt248Type ) {
  14304. glInternalFormat = 35056;
  14305. } else {
  14306. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  14307. }
  14308. } else {
  14309. if ( texture.type === FloatType ) {
  14310. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14311. }
  14312. }
  14313. // validation checks for WebGL 1
  14314. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  14315. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14316. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14317. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14318. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14319. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14320. texture.type = UnsignedIntType;
  14321. glType = utils.convert( texture.type );
  14322. }
  14323. }
  14324. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  14325. // Depth stencil textures need the DEPTH_STENCIL internal format
  14326. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14327. glInternalFormat = 34041;
  14328. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14329. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14330. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14331. if ( texture.type !== UnsignedInt248Type ) {
  14332. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14333. texture.type = UnsignedInt248Type;
  14334. glType = utils.convert( texture.type );
  14335. }
  14336. }
  14337. //
  14338. if ( allocateMemory ) {
  14339. if ( useTexStorage ) {
  14340. state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height );
  14341. } else {
  14342. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14343. }
  14344. }
  14345. } else if ( texture.isDataTexture ) {
  14346. // use manually created mipmaps if available
  14347. // if there are no manual mipmaps
  14348. // set 0 level mipmap and then use GL to generate other mipmap levels
  14349. if ( mipmaps.length > 0 && supportsMips ) {
  14350. if ( useTexStorage && allocateMemory ) {
  14351. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14352. }
  14353. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14354. mipmap = mipmaps[ i ];
  14355. if ( useTexStorage ) {
  14356. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14357. } else {
  14358. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14359. }
  14360. }
  14361. texture.generateMipmaps = false;
  14362. } else {
  14363. if ( useTexStorage ) {
  14364. if ( allocateMemory ) {
  14365. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14366. }
  14367. state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14368. } else {
  14369. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14370. }
  14371. }
  14372. } else if ( texture.isCompressedTexture ) {
  14373. if ( texture.isCompressedArrayTexture ) {
  14374. if ( useTexStorage && allocateMemory ) {
  14375. state.texStorage3D( 35866, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14376. }
  14377. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14378. mipmap = mipmaps[ i ];
  14379. if ( texture.format !== RGBAFormat ) {
  14380. if ( glFormat !== null ) {
  14381. if ( useTexStorage ) {
  14382. state.compressedTexSubImage3D( 35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14383. } else {
  14384. state.compressedTexImage3D( 35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14385. }
  14386. } else {
  14387. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14388. }
  14389. } else {
  14390. if ( useTexStorage ) {
  14391. state.texSubImage3D( 35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14392. } else {
  14393. state.texImage3D( 35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14394. }
  14395. }
  14396. }
  14397. } else {
  14398. if ( useTexStorage && allocateMemory ) {
  14399. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14400. }
  14401. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14402. mipmap = mipmaps[ i ];
  14403. if ( texture.format !== RGBAFormat ) {
  14404. if ( glFormat !== null ) {
  14405. if ( useTexStorage ) {
  14406. state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14407. } else {
  14408. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14409. }
  14410. } else {
  14411. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14412. }
  14413. } else {
  14414. if ( useTexStorage ) {
  14415. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14416. } else {
  14417. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14418. }
  14419. }
  14420. }
  14421. }
  14422. } else if ( texture.isDataArrayTexture ) {
  14423. if ( useTexStorage ) {
  14424. if ( allocateMemory ) {
  14425. state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth );
  14426. }
  14427. state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14428. } else {
  14429. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14430. }
  14431. } else if ( texture.isData3DTexture ) {
  14432. if ( useTexStorage ) {
  14433. if ( allocateMemory ) {
  14434. state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth );
  14435. }
  14436. state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14437. } else {
  14438. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14439. }
  14440. } else if ( texture.isFramebufferTexture ) {
  14441. if ( allocateMemory ) {
  14442. if ( useTexStorage ) {
  14443. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14444. } else {
  14445. let width = image.width, height = image.height;
  14446. for ( let i = 0; i < levels; i ++ ) {
  14447. state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14448. width >>= 1;
  14449. height >>= 1;
  14450. }
  14451. }
  14452. }
  14453. } else {
  14454. // regular Texture (image, video, canvas)
  14455. // use manually created mipmaps if available
  14456. // if there are no manual mipmaps
  14457. // set 0 level mipmap and then use GL to generate other mipmap levels
  14458. if ( mipmaps.length > 0 && supportsMips ) {
  14459. if ( useTexStorage && allocateMemory ) {
  14460. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14461. }
  14462. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14463. mipmap = mipmaps[ i ];
  14464. if ( useTexStorage ) {
  14465. state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap );
  14466. } else {
  14467. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  14468. }
  14469. }
  14470. texture.generateMipmaps = false;
  14471. } else {
  14472. if ( useTexStorage ) {
  14473. if ( allocateMemory ) {
  14474. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14475. }
  14476. state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image );
  14477. } else {
  14478. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  14479. }
  14480. }
  14481. }
  14482. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14483. generateMipmap( textureType );
  14484. }
  14485. sourceProperties.__version = source.version;
  14486. if ( texture.onUpdate ) texture.onUpdate( texture );
  14487. }
  14488. textureProperties.__version = texture.version;
  14489. }
  14490. function uploadCubeTexture( textureProperties, texture, slot ) {
  14491. if ( texture.image.length !== 6 ) return;
  14492. const forceUpload = initTexture( textureProperties, texture );
  14493. const source = texture.source;
  14494. state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot );
  14495. const sourceProperties = properties.get( source );
  14496. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14497. state.activeTexture( 33984 + slot );
  14498. _gl.pixelStorei( 37440, texture.flipY );
  14499. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14500. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14501. _gl.pixelStorei( 37443, 0 );
  14502. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14503. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14504. const cubeImage = [];
  14505. for ( let i = 0; i < 6; i ++ ) {
  14506. if ( ! isCompressed && ! isDataTexture ) {
  14507. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14508. } else {
  14509. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14510. }
  14511. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14512. }
  14513. const image = cubeImage[ 0 ],
  14514. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14515. glFormat = utils.convert( texture.format, texture.encoding ),
  14516. glType = utils.convert( texture.type ),
  14517. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14518. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14519. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14520. let levels = getMipLevels( texture, image, supportsMips );
  14521. setTextureParameters( 34067, texture, supportsMips );
  14522. let mipmaps;
  14523. if ( isCompressed ) {
  14524. if ( useTexStorage && allocateMemory ) {
  14525. state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height );
  14526. }
  14527. for ( let i = 0; i < 6; i ++ ) {
  14528. mipmaps = cubeImage[ i ].mipmaps;
  14529. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14530. const mipmap = mipmaps[ j ];
  14531. if ( texture.format !== RGBAFormat ) {
  14532. if ( glFormat !== null ) {
  14533. if ( useTexStorage ) {
  14534. state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14535. } else {
  14536. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14537. }
  14538. } else {
  14539. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14540. }
  14541. } else {
  14542. if ( useTexStorage ) {
  14543. state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14544. } else {
  14545. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14546. }
  14547. }
  14548. }
  14549. }
  14550. } else {
  14551. mipmaps = texture.mipmaps;
  14552. if ( useTexStorage && allocateMemory ) {
  14553. // TODO: Uniformly handle mipmap definitions
  14554. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14555. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14556. if ( mipmaps.length > 0 ) levels ++;
  14557. state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14558. }
  14559. for ( let i = 0; i < 6; i ++ ) {
  14560. if ( isDataTexture ) {
  14561. if ( useTexStorage ) {
  14562. state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14563. } else {
  14564. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14565. }
  14566. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14567. const mipmap = mipmaps[ j ];
  14568. const mipmapImage = mipmap.image[ i ].image;
  14569. if ( useTexStorage ) {
  14570. state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14571. } else {
  14572. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14573. }
  14574. }
  14575. } else {
  14576. if ( useTexStorage ) {
  14577. state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14578. } else {
  14579. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14580. }
  14581. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14582. const mipmap = mipmaps[ j ];
  14583. if ( useTexStorage ) {
  14584. state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14585. } else {
  14586. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14587. }
  14588. }
  14589. }
  14590. }
  14591. }
  14592. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14593. // We assume images for cube map have the same size.
  14594. generateMipmap( 34067 );
  14595. }
  14596. sourceProperties.__version = source.version;
  14597. if ( texture.onUpdate ) texture.onUpdate( texture );
  14598. }
  14599. textureProperties.__version = texture.version;
  14600. }
  14601. // Render targets
  14602. // Setup storage for target texture and bind it to correct framebuffer
  14603. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14604. const glFormat = utils.convert( texture.format, texture.encoding );
  14605. const glType = utils.convert( texture.type );
  14606. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14607. const renderTargetProperties = properties.get( renderTarget );
  14608. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14609. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  14610. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14611. } else {
  14612. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14613. }
  14614. }
  14615. state.bindFramebuffer( 36160, framebuffer );
  14616. if ( useMultisampledRTT( renderTarget ) ) {
  14617. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14618. } else if ( textureTarget === 3553 || ( textureTarget >= 34069 && textureTarget <= 34074 ) ) { // see #24753
  14619. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14620. }
  14621. state.bindFramebuffer( 36160, null );
  14622. }
  14623. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14624. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14625. _gl.bindRenderbuffer( 36161, renderbuffer );
  14626. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14627. let glInternalFormat = 33189;
  14628. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14629. const depthTexture = renderTarget.depthTexture;
  14630. if ( depthTexture && depthTexture.isDepthTexture ) {
  14631. if ( depthTexture.type === FloatType ) {
  14632. glInternalFormat = 36012;
  14633. } else if ( depthTexture.type === UnsignedIntType ) {
  14634. glInternalFormat = 33190;
  14635. }
  14636. }
  14637. const samples = getRenderTargetSamples( renderTarget );
  14638. if ( useMultisampledRTT( renderTarget ) ) {
  14639. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14640. } else {
  14641. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14642. }
  14643. } else {
  14644. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14645. }
  14646. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  14647. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14648. const samples = getRenderTargetSamples( renderTarget );
  14649. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14650. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14651. } else if ( useMultisampledRTT( renderTarget ) ) {
  14652. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14653. } else {
  14654. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  14655. }
  14656. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  14657. } else {
  14658. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14659. for ( let i = 0; i < textures.length; i ++ ) {
  14660. const texture = textures[ i ];
  14661. const glFormat = utils.convert( texture.format, texture.encoding );
  14662. const glType = utils.convert( texture.type );
  14663. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14664. const samples = getRenderTargetSamples( renderTarget );
  14665. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14666. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14667. } else if ( useMultisampledRTT( renderTarget ) ) {
  14668. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14669. } else {
  14670. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14671. }
  14672. }
  14673. }
  14674. _gl.bindRenderbuffer( 36161, null );
  14675. }
  14676. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14677. function setupDepthTexture( framebuffer, renderTarget ) {
  14678. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14679. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14680. state.bindFramebuffer( 36160, framebuffer );
  14681. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14682. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14683. }
  14684. // upload an empty depth texture with framebuffer size
  14685. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14686. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14687. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14688. renderTarget.depthTexture.image.width = renderTarget.width;
  14689. renderTarget.depthTexture.image.height = renderTarget.height;
  14690. renderTarget.depthTexture.needsUpdate = true;
  14691. }
  14692. setTexture2D( renderTarget.depthTexture, 0 );
  14693. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14694. const samples = getRenderTargetSamples( renderTarget );
  14695. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14696. if ( useMultisampledRTT( renderTarget ) ) {
  14697. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples );
  14698. } else {
  14699. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  14700. }
  14701. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14702. if ( useMultisampledRTT( renderTarget ) ) {
  14703. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples );
  14704. } else {
  14705. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  14706. }
  14707. } else {
  14708. throw new Error( 'Unknown depthTexture format' );
  14709. }
  14710. }
  14711. // Setup GL resources for a non-texture depth buffer
  14712. function setupDepthRenderbuffer( renderTarget ) {
  14713. const renderTargetProperties = properties.get( renderTarget );
  14714. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14715. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14716. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14717. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14718. } else {
  14719. if ( isCube ) {
  14720. renderTargetProperties.__webglDepthbuffer = [];
  14721. for ( let i = 0; i < 6; i ++ ) {
  14722. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  14723. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14724. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14725. }
  14726. } else {
  14727. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14728. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14729. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14730. }
  14731. }
  14732. state.bindFramebuffer( 36160, null );
  14733. }
  14734. // rebind framebuffer with external textures
  14735. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14736. const renderTargetProperties = properties.get( renderTarget );
  14737. if ( colorTexture !== undefined ) {
  14738. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 );
  14739. }
  14740. if ( depthTexture !== undefined ) {
  14741. setupDepthRenderbuffer( renderTarget );
  14742. }
  14743. }
  14744. // Set up GL resources for the render target
  14745. function setupRenderTarget( renderTarget ) {
  14746. const texture = renderTarget.texture;
  14747. const renderTargetProperties = properties.get( renderTarget );
  14748. const textureProperties = properties.get( texture );
  14749. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14750. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14751. if ( textureProperties.__webglTexture === undefined ) {
  14752. textureProperties.__webglTexture = _gl.createTexture();
  14753. }
  14754. textureProperties.__version = texture.version;
  14755. info.memory.textures ++;
  14756. }
  14757. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14758. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14759. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14760. // Setup framebuffer
  14761. if ( isCube ) {
  14762. renderTargetProperties.__webglFramebuffer = [];
  14763. for ( let i = 0; i < 6; i ++ ) {
  14764. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14765. }
  14766. } else {
  14767. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14768. if ( isMultipleRenderTargets ) {
  14769. if ( capabilities.drawBuffers ) {
  14770. const textures = renderTarget.texture;
  14771. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14772. const attachmentProperties = properties.get( textures[ i ] );
  14773. if ( attachmentProperties.__webglTexture === undefined ) {
  14774. attachmentProperties.__webglTexture = _gl.createTexture();
  14775. info.memory.textures ++;
  14776. }
  14777. }
  14778. } else {
  14779. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14780. }
  14781. }
  14782. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14783. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14784. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14785. renderTargetProperties.__webglColorRenderbuffer = [];
  14786. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14787. for ( let i = 0; i < textures.length; i ++ ) {
  14788. const texture = textures[ i ];
  14789. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14790. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14791. const glFormat = utils.convert( texture.format, texture.encoding );
  14792. const glType = utils.convert( texture.type );
  14793. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true );
  14794. const samples = getRenderTargetSamples( renderTarget );
  14795. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14796. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14797. }
  14798. _gl.bindRenderbuffer( 36161, null );
  14799. if ( renderTarget.depthBuffer ) {
  14800. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14801. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14802. }
  14803. state.bindFramebuffer( 36160, null );
  14804. }
  14805. }
  14806. // Setup color buffer
  14807. if ( isCube ) {
  14808. state.bindTexture( 34067, textureProperties.__webglTexture );
  14809. setTextureParameters( 34067, texture, supportsMips );
  14810. for ( let i = 0; i < 6; i ++ ) {
  14811. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  14812. }
  14813. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14814. generateMipmap( 34067 );
  14815. }
  14816. state.unbindTexture();
  14817. } else if ( isMultipleRenderTargets ) {
  14818. const textures = renderTarget.texture;
  14819. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14820. const attachment = textures[ i ];
  14821. const attachmentProperties = properties.get( attachment );
  14822. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  14823. setTextureParameters( 3553, attachment, supportsMips );
  14824. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  14825. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14826. generateMipmap( 3553 );
  14827. }
  14828. }
  14829. state.unbindTexture();
  14830. } else {
  14831. let glTextureType = 3553;
  14832. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14833. if ( isWebGL2 ) {
  14834. glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866;
  14835. } else {
  14836. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14837. }
  14838. }
  14839. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14840. setTextureParameters( glTextureType, texture, supportsMips );
  14841. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  14842. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14843. generateMipmap( glTextureType );
  14844. }
  14845. state.unbindTexture();
  14846. }
  14847. // Setup depth and stencil buffers
  14848. if ( renderTarget.depthBuffer ) {
  14849. setupDepthRenderbuffer( renderTarget );
  14850. }
  14851. }
  14852. function updateRenderTargetMipmap( renderTarget ) {
  14853. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14854. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14855. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14856. const texture = textures[ i ];
  14857. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14858. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14859. const webglTexture = properties.get( texture ).__webglTexture;
  14860. state.bindTexture( target, webglTexture );
  14861. generateMipmap( target );
  14862. state.unbindTexture();
  14863. }
  14864. }
  14865. }
  14866. function updateMultisampleRenderTarget( renderTarget ) {
  14867. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14868. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14869. const width = renderTarget.width;
  14870. const height = renderTarget.height;
  14871. let mask = 16384;
  14872. const invalidationArray = [];
  14873. const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096;
  14874. const renderTargetProperties = properties.get( renderTarget );
  14875. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14876. // If MRT we need to remove FBO attachments
  14877. if ( isMultipleRenderTargets ) {
  14878. for ( let i = 0; i < textures.length; i ++ ) {
  14879. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14880. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null );
  14881. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14882. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 );
  14883. }
  14884. }
  14885. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  14886. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  14887. for ( let i = 0; i < textures.length; i ++ ) {
  14888. invalidationArray.push( 36064 + i );
  14889. if ( renderTarget.depthBuffer ) {
  14890. invalidationArray.push( depthStyle );
  14891. }
  14892. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14893. if ( ignoreDepthValues === false ) {
  14894. if ( renderTarget.depthBuffer ) mask |= 256;
  14895. if ( renderTarget.stencilBuffer ) mask |= 1024;
  14896. }
  14897. if ( isMultipleRenderTargets ) {
  14898. _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14899. }
  14900. if ( ignoreDepthValues === true ) {
  14901. _gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14902. _gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14903. }
  14904. if ( isMultipleRenderTargets ) {
  14905. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14906. _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 );
  14907. }
  14908. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  14909. if ( supportsInvalidateFramebuffer ) {
  14910. _gl.invalidateFramebuffer( 36008, invalidationArray );
  14911. }
  14912. }
  14913. state.bindFramebuffer( 36008, null );
  14914. state.bindFramebuffer( 36009, null );
  14915. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14916. if ( isMultipleRenderTargets ) {
  14917. for ( let i = 0; i < textures.length; i ++ ) {
  14918. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14919. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14920. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14921. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14922. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 );
  14923. }
  14924. }
  14925. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  14926. }
  14927. }
  14928. function getRenderTargetSamples( renderTarget ) {
  14929. return Math.min( maxSamples, renderTarget.samples );
  14930. }
  14931. function useMultisampledRTT( renderTarget ) {
  14932. const renderTargetProperties = properties.get( renderTarget );
  14933. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14934. }
  14935. function updateVideoTexture( texture ) {
  14936. const frame = info.render.frame;
  14937. // Check the last frame we updated the VideoTexture
  14938. if ( _videoTextures.get( texture ) !== frame ) {
  14939. _videoTextures.set( texture, frame );
  14940. texture.update();
  14941. }
  14942. }
  14943. function verifyColorSpace( texture, image ) {
  14944. const encoding = texture.encoding;
  14945. const format = texture.format;
  14946. const type = texture.type;
  14947. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14948. if ( encoding !== LinearEncoding ) {
  14949. // sRGB
  14950. if ( encoding === sRGBEncoding ) {
  14951. if ( isWebGL2 === false ) {
  14952. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14953. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14954. texture.format = _SRGBAFormat;
  14955. // it's not possible to generate mips in WebGL 1 with this extension
  14956. texture.minFilter = LinearFilter;
  14957. texture.generateMipmaps = false;
  14958. } else {
  14959. // slow fallback (CPU decode)
  14960. image = ImageUtils.sRGBToLinear( image );
  14961. }
  14962. } else {
  14963. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14964. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14965. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14966. }
  14967. }
  14968. } else {
  14969. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14970. }
  14971. }
  14972. return image;
  14973. }
  14974. //
  14975. this.allocateTextureUnit = allocateTextureUnit;
  14976. this.resetTextureUnits = resetTextureUnits;
  14977. this.setTexture2D = setTexture2D;
  14978. this.setTexture2DArray = setTexture2DArray;
  14979. this.setTexture3D = setTexture3D;
  14980. this.setTextureCube = setTextureCube;
  14981. this.rebindTextures = rebindTextures;
  14982. this.setupRenderTarget = setupRenderTarget;
  14983. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14984. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14985. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14986. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14987. this.useMultisampledRTT = useMultisampledRTT;
  14988. }
  14989. function WebGLUtils( gl, extensions, capabilities ) {
  14990. const isWebGL2 = capabilities.isWebGL2;
  14991. function convert( p, encoding = null ) {
  14992. let extension;
  14993. if ( p === UnsignedByteType ) return 5121;
  14994. if ( p === UnsignedShort4444Type ) return 32819;
  14995. if ( p === UnsignedShort5551Type ) return 32820;
  14996. if ( p === ByteType ) return 5120;
  14997. if ( p === ShortType ) return 5122;
  14998. if ( p === UnsignedShortType ) return 5123;
  14999. if ( p === IntType ) return 5124;
  15000. if ( p === UnsignedIntType ) return 5125;
  15001. if ( p === FloatType ) return 5126;
  15002. if ( p === HalfFloatType ) {
  15003. if ( isWebGL2 ) return 5131;
  15004. extension = extensions.get( 'OES_texture_half_float' );
  15005. if ( extension !== null ) {
  15006. return extension.HALF_FLOAT_OES;
  15007. } else {
  15008. return null;
  15009. }
  15010. }
  15011. if ( p === AlphaFormat ) return 6406;
  15012. if ( p === RGBAFormat ) return 6408;
  15013. if ( p === LuminanceFormat ) return 6409;
  15014. if ( p === LuminanceAlphaFormat ) return 6410;
  15015. if ( p === DepthFormat ) return 6402;
  15016. if ( p === DepthStencilFormat ) return 34041;
  15017. // WebGL 1 sRGB fallback
  15018. if ( p === _SRGBAFormat ) {
  15019. extension = extensions.get( 'EXT_sRGB' );
  15020. if ( extension !== null ) {
  15021. return extension.SRGB_ALPHA_EXT;
  15022. } else {
  15023. return null;
  15024. }
  15025. }
  15026. // WebGL2 formats.
  15027. if ( p === RedFormat ) return 6403;
  15028. if ( p === RedIntegerFormat ) return 36244;
  15029. if ( p === RGFormat ) return 33319;
  15030. if ( p === RGIntegerFormat ) return 33320;
  15031. if ( p === RGBAIntegerFormat ) return 36249;
  15032. // S3TC
  15033. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15034. if ( encoding === sRGBEncoding ) {
  15035. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15036. if ( extension !== null ) {
  15037. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15038. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15039. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15040. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15041. } else {
  15042. return null;
  15043. }
  15044. } else {
  15045. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15046. if ( extension !== null ) {
  15047. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15048. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15049. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15050. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15051. } else {
  15052. return null;
  15053. }
  15054. }
  15055. }
  15056. // PVRTC
  15057. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15058. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15059. if ( extension !== null ) {
  15060. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15061. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15062. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15063. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15064. } else {
  15065. return null;
  15066. }
  15067. }
  15068. // ETC1
  15069. if ( p === RGB_ETC1_Format ) {
  15070. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  15071. if ( extension !== null ) {
  15072. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15073. } else {
  15074. return null;
  15075. }
  15076. }
  15077. // ETC2
  15078. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15079. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15080. if ( extension !== null ) {
  15081. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15082. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15083. } else {
  15084. return null;
  15085. }
  15086. }
  15087. // ASTC
  15088. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15089. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15090. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15091. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15092. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15093. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15094. if ( extension !== null ) {
  15095. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15096. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15097. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15098. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15099. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15100. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15101. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15102. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15103. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15104. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15105. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15106. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15107. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15108. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15109. } else {
  15110. return null;
  15111. }
  15112. }
  15113. // BPTC
  15114. if ( p === RGBA_BPTC_Format ) {
  15115. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15116. if ( extension !== null ) {
  15117. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15118. } else {
  15119. return null;
  15120. }
  15121. }
  15122. // RGTC
  15123. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15124. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15125. if ( extension !== null ) {
  15126. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15127. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15128. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15129. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15130. } else {
  15131. return null;
  15132. }
  15133. }
  15134. //
  15135. if ( p === UnsignedInt248Type ) {
  15136. if ( isWebGL2 ) return 34042;
  15137. extension = extensions.get( 'WEBGL_depth_texture' );
  15138. if ( extension !== null ) {
  15139. return extension.UNSIGNED_INT_24_8_WEBGL;
  15140. } else {
  15141. return null;
  15142. }
  15143. }
  15144. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15145. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15146. }
  15147. return { convert: convert };
  15148. }
  15149. class ArrayCamera extends PerspectiveCamera {
  15150. constructor( array = [] ) {
  15151. super();
  15152. this.isArrayCamera = true;
  15153. this.cameras = array;
  15154. }
  15155. }
  15156. class Group extends Object3D {
  15157. constructor() {
  15158. super();
  15159. this.isGroup = true;
  15160. this.type = 'Group';
  15161. }
  15162. }
  15163. const _moveEvent = { type: 'move' };
  15164. class WebXRController {
  15165. constructor() {
  15166. this._targetRay = null;
  15167. this._grip = null;
  15168. this._hand = null;
  15169. }
  15170. getHandSpace() {
  15171. if ( this._hand === null ) {
  15172. this._hand = new Group();
  15173. this._hand.matrixAutoUpdate = false;
  15174. this._hand.visible = false;
  15175. this._hand.joints = {};
  15176. this._hand.inputState = { pinching: false };
  15177. }
  15178. return this._hand;
  15179. }
  15180. getTargetRaySpace() {
  15181. if ( this._targetRay === null ) {
  15182. this._targetRay = new Group();
  15183. this._targetRay.matrixAutoUpdate = false;
  15184. this._targetRay.visible = false;
  15185. this._targetRay.hasLinearVelocity = false;
  15186. this._targetRay.linearVelocity = new Vector3();
  15187. this._targetRay.hasAngularVelocity = false;
  15188. this._targetRay.angularVelocity = new Vector3();
  15189. }
  15190. return this._targetRay;
  15191. }
  15192. getGripSpace() {
  15193. if ( this._grip === null ) {
  15194. this._grip = new Group();
  15195. this._grip.matrixAutoUpdate = false;
  15196. this._grip.visible = false;
  15197. this._grip.hasLinearVelocity = false;
  15198. this._grip.linearVelocity = new Vector3();
  15199. this._grip.hasAngularVelocity = false;
  15200. this._grip.angularVelocity = new Vector3();
  15201. }
  15202. return this._grip;
  15203. }
  15204. dispatchEvent( event ) {
  15205. if ( this._targetRay !== null ) {
  15206. this._targetRay.dispatchEvent( event );
  15207. }
  15208. if ( this._grip !== null ) {
  15209. this._grip.dispatchEvent( event );
  15210. }
  15211. if ( this._hand !== null ) {
  15212. this._hand.dispatchEvent( event );
  15213. }
  15214. return this;
  15215. }
  15216. connect( inputSource ) {
  15217. if ( inputSource && inputSource.hand ) {
  15218. const hand = this._hand;
  15219. if ( hand ) {
  15220. for ( const inputjoint of inputSource.hand.values() ) {
  15221. // Initialize hand with joints when connected
  15222. this._getHandJoint( hand, inputjoint );
  15223. }
  15224. }
  15225. }
  15226. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15227. return this;
  15228. }
  15229. disconnect( inputSource ) {
  15230. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15231. if ( this._targetRay !== null ) {
  15232. this._targetRay.visible = false;
  15233. }
  15234. if ( this._grip !== null ) {
  15235. this._grip.visible = false;
  15236. }
  15237. if ( this._hand !== null ) {
  15238. this._hand.visible = false;
  15239. }
  15240. return this;
  15241. }
  15242. update( inputSource, frame, referenceSpace ) {
  15243. let inputPose = null;
  15244. let gripPose = null;
  15245. let handPose = null;
  15246. const targetRay = this._targetRay;
  15247. const grip = this._grip;
  15248. const hand = this._hand;
  15249. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15250. if ( hand && inputSource.hand ) {
  15251. handPose = true;
  15252. for ( const inputjoint of inputSource.hand.values() ) {
  15253. // Update the joints groups with the XRJoint poses
  15254. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15255. // The transform of this joint will be updated with the joint pose on each frame
  15256. const joint = this._getHandJoint( hand, inputjoint );
  15257. if ( jointPose !== null ) {
  15258. joint.matrix.fromArray( jointPose.transform.matrix );
  15259. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15260. joint.jointRadius = jointPose.radius;
  15261. }
  15262. joint.visible = jointPose !== null;
  15263. }
  15264. // Custom events
  15265. // Check pinchz
  15266. const indexTip = hand.joints[ 'index-finger-tip' ];
  15267. const thumbTip = hand.joints[ 'thumb-tip' ];
  15268. const distance = indexTip.position.distanceTo( thumbTip.position );
  15269. const distanceToPinch = 0.02;
  15270. const threshold = 0.005;
  15271. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15272. hand.inputState.pinching = false;
  15273. this.dispatchEvent( {
  15274. type: 'pinchend',
  15275. handedness: inputSource.handedness,
  15276. target: this
  15277. } );
  15278. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15279. hand.inputState.pinching = true;
  15280. this.dispatchEvent( {
  15281. type: 'pinchstart',
  15282. handedness: inputSource.handedness,
  15283. target: this
  15284. } );
  15285. }
  15286. } else {
  15287. if ( grip !== null && inputSource.gripSpace ) {
  15288. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15289. if ( gripPose !== null ) {
  15290. grip.matrix.fromArray( gripPose.transform.matrix );
  15291. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15292. if ( gripPose.linearVelocity ) {
  15293. grip.hasLinearVelocity = true;
  15294. grip.linearVelocity.copy( gripPose.linearVelocity );
  15295. } else {
  15296. grip.hasLinearVelocity = false;
  15297. }
  15298. if ( gripPose.angularVelocity ) {
  15299. grip.hasAngularVelocity = true;
  15300. grip.angularVelocity.copy( gripPose.angularVelocity );
  15301. } else {
  15302. grip.hasAngularVelocity = false;
  15303. }
  15304. }
  15305. }
  15306. }
  15307. if ( targetRay !== null ) {
  15308. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15309. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15310. if ( inputPose === null && gripPose !== null ) {
  15311. inputPose = gripPose;
  15312. }
  15313. if ( inputPose !== null ) {
  15314. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15315. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15316. if ( inputPose.linearVelocity ) {
  15317. targetRay.hasLinearVelocity = true;
  15318. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15319. } else {
  15320. targetRay.hasLinearVelocity = false;
  15321. }
  15322. if ( inputPose.angularVelocity ) {
  15323. targetRay.hasAngularVelocity = true;
  15324. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15325. } else {
  15326. targetRay.hasAngularVelocity = false;
  15327. }
  15328. this.dispatchEvent( _moveEvent );
  15329. }
  15330. }
  15331. }
  15332. if ( targetRay !== null ) {
  15333. targetRay.visible = ( inputPose !== null );
  15334. }
  15335. if ( grip !== null ) {
  15336. grip.visible = ( gripPose !== null );
  15337. }
  15338. if ( hand !== null ) {
  15339. hand.visible = ( handPose !== null );
  15340. }
  15341. return this;
  15342. }
  15343. // private method
  15344. _getHandJoint( hand, inputjoint ) {
  15345. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15346. const joint = new Group();
  15347. joint.matrixAutoUpdate = false;
  15348. joint.visible = false;
  15349. hand.joints[ inputjoint.jointName ] = joint;
  15350. hand.add( joint );
  15351. }
  15352. return hand.joints[ inputjoint.jointName ];
  15353. }
  15354. }
  15355. class DepthTexture extends Texture {
  15356. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15357. format = format !== undefined ? format : DepthFormat;
  15358. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15359. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15360. }
  15361. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15362. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15363. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15364. this.isDepthTexture = true;
  15365. this.image = { width: width, height: height };
  15366. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15367. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15368. this.flipY = false;
  15369. this.generateMipmaps = false;
  15370. }
  15371. }
  15372. class WebXRManager extends EventDispatcher {
  15373. constructor( renderer, gl ) {
  15374. super();
  15375. const scope = this;
  15376. let session = null;
  15377. let framebufferScaleFactor = 1.0;
  15378. let referenceSpace = null;
  15379. let referenceSpaceType = 'local-floor';
  15380. // Set default foveation to maximum.
  15381. let foveation = 1.0;
  15382. let customReferenceSpace = null;
  15383. let pose = null;
  15384. let glBinding = null;
  15385. let glProjLayer = null;
  15386. let glBaseLayer = null;
  15387. let xrFrame = null;
  15388. const attributes = gl.getContextAttributes();
  15389. let initialRenderTarget = null;
  15390. let newRenderTarget = null;
  15391. const controllers = [];
  15392. const controllerInputSources = [];
  15393. const planes = new Set();
  15394. const planesLastChangedTimes = new Map();
  15395. //
  15396. const cameraL = new PerspectiveCamera();
  15397. cameraL.layers.enable( 1 );
  15398. cameraL.viewport = new Vector4();
  15399. const cameraR = new PerspectiveCamera();
  15400. cameraR.layers.enable( 2 );
  15401. cameraR.viewport = new Vector4();
  15402. const cameras = [ cameraL, cameraR ];
  15403. const cameraVR = new ArrayCamera();
  15404. cameraVR.layers.enable( 1 );
  15405. cameraVR.layers.enable( 2 );
  15406. let _currentDepthNear = null;
  15407. let _currentDepthFar = null;
  15408. //
  15409. this.cameraAutoUpdate = true;
  15410. this.enabled = false;
  15411. this.isPresenting = false;
  15412. this.getController = function ( index ) {
  15413. let controller = controllers[ index ];
  15414. if ( controller === undefined ) {
  15415. controller = new WebXRController();
  15416. controllers[ index ] = controller;
  15417. }
  15418. return controller.getTargetRaySpace();
  15419. };
  15420. this.getControllerGrip = function ( index ) {
  15421. let controller = controllers[ index ];
  15422. if ( controller === undefined ) {
  15423. controller = new WebXRController();
  15424. controllers[ index ] = controller;
  15425. }
  15426. return controller.getGripSpace();
  15427. };
  15428. this.getHand = function ( index ) {
  15429. let controller = controllers[ index ];
  15430. if ( controller === undefined ) {
  15431. controller = new WebXRController();
  15432. controllers[ index ] = controller;
  15433. }
  15434. return controller.getHandSpace();
  15435. };
  15436. //
  15437. function onSessionEvent( event ) {
  15438. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15439. if ( controllerIndex === - 1 ) {
  15440. return;
  15441. }
  15442. const controller = controllers[ controllerIndex ];
  15443. if ( controller !== undefined ) {
  15444. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15445. }
  15446. }
  15447. function onSessionEnd() {
  15448. session.removeEventListener( 'select', onSessionEvent );
  15449. session.removeEventListener( 'selectstart', onSessionEvent );
  15450. session.removeEventListener( 'selectend', onSessionEvent );
  15451. session.removeEventListener( 'squeeze', onSessionEvent );
  15452. session.removeEventListener( 'squeezestart', onSessionEvent );
  15453. session.removeEventListener( 'squeezeend', onSessionEvent );
  15454. session.removeEventListener( 'end', onSessionEnd );
  15455. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15456. for ( let i = 0; i < controllers.length; i ++ ) {
  15457. const inputSource = controllerInputSources[ i ];
  15458. if ( inputSource === null ) continue;
  15459. controllerInputSources[ i ] = null;
  15460. controllers[ i ].disconnect( inputSource );
  15461. }
  15462. _currentDepthNear = null;
  15463. _currentDepthFar = null;
  15464. // restore framebuffer/rendering state
  15465. renderer.setRenderTarget( initialRenderTarget );
  15466. glBaseLayer = null;
  15467. glProjLayer = null;
  15468. glBinding = null;
  15469. session = null;
  15470. newRenderTarget = null;
  15471. //
  15472. animation.stop();
  15473. scope.isPresenting = false;
  15474. scope.dispatchEvent( { type: 'sessionend' } );
  15475. }
  15476. this.setFramebufferScaleFactor = function ( value ) {
  15477. framebufferScaleFactor = value;
  15478. if ( scope.isPresenting === true ) {
  15479. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15480. }
  15481. };
  15482. this.setReferenceSpaceType = function ( value ) {
  15483. referenceSpaceType = value;
  15484. if ( scope.isPresenting === true ) {
  15485. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15486. }
  15487. };
  15488. this.getReferenceSpace = function () {
  15489. return customReferenceSpace || referenceSpace;
  15490. };
  15491. this.setReferenceSpace = function ( space ) {
  15492. customReferenceSpace = space;
  15493. };
  15494. this.getBaseLayer = function () {
  15495. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15496. };
  15497. this.getBinding = function () {
  15498. return glBinding;
  15499. };
  15500. this.getFrame = function () {
  15501. return xrFrame;
  15502. };
  15503. this.getSession = function () {
  15504. return session;
  15505. };
  15506. this.setSession = async function ( value ) {
  15507. session = value;
  15508. if ( session !== null ) {
  15509. initialRenderTarget = renderer.getRenderTarget();
  15510. session.addEventListener( 'select', onSessionEvent );
  15511. session.addEventListener( 'selectstart', onSessionEvent );
  15512. session.addEventListener( 'selectend', onSessionEvent );
  15513. session.addEventListener( 'squeeze', onSessionEvent );
  15514. session.addEventListener( 'squeezestart', onSessionEvent );
  15515. session.addEventListener( 'squeezeend', onSessionEvent );
  15516. session.addEventListener( 'end', onSessionEnd );
  15517. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15518. if ( attributes.xrCompatible !== true ) {
  15519. await gl.makeXRCompatible();
  15520. }
  15521. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15522. const layerInit = {
  15523. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15524. alpha: attributes.alpha,
  15525. depth: attributes.depth,
  15526. stencil: attributes.stencil,
  15527. framebufferScaleFactor: framebufferScaleFactor
  15528. };
  15529. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15530. session.updateRenderState( { baseLayer: glBaseLayer } );
  15531. newRenderTarget = new WebGLRenderTarget(
  15532. glBaseLayer.framebufferWidth,
  15533. glBaseLayer.framebufferHeight,
  15534. {
  15535. format: RGBAFormat,
  15536. type: UnsignedByteType,
  15537. encoding: renderer.outputEncoding,
  15538. stencilBuffer: attributes.stencil
  15539. }
  15540. );
  15541. } else {
  15542. let depthFormat = null;
  15543. let depthType = null;
  15544. let glDepthFormat = null;
  15545. if ( attributes.depth ) {
  15546. glDepthFormat = attributes.stencil ? 35056 : 33190;
  15547. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15548. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15549. }
  15550. const projectionlayerInit = {
  15551. colorFormat: 32856,
  15552. depthFormat: glDepthFormat,
  15553. scaleFactor: framebufferScaleFactor
  15554. };
  15555. glBinding = new XRWebGLBinding( session, gl );
  15556. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15557. session.updateRenderState( { layers: [ glProjLayer ] } );
  15558. newRenderTarget = new WebGLRenderTarget(
  15559. glProjLayer.textureWidth,
  15560. glProjLayer.textureHeight,
  15561. {
  15562. format: RGBAFormat,
  15563. type: UnsignedByteType,
  15564. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15565. stencilBuffer: attributes.stencil,
  15566. encoding: renderer.outputEncoding,
  15567. samples: attributes.antialias ? 4 : 0
  15568. } );
  15569. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15570. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15571. }
  15572. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15573. this.setFoveation( foveation );
  15574. customReferenceSpace = null;
  15575. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15576. animation.setContext( session );
  15577. animation.start();
  15578. scope.isPresenting = true;
  15579. scope.dispatchEvent( { type: 'sessionstart' } );
  15580. }
  15581. };
  15582. function onInputSourcesChange( event ) {
  15583. // Notify disconnected
  15584. for ( let i = 0; i < event.removed.length; i ++ ) {
  15585. const inputSource = event.removed[ i ];
  15586. const index = controllerInputSources.indexOf( inputSource );
  15587. if ( index >= 0 ) {
  15588. controllerInputSources[ index ] = null;
  15589. controllers[ index ].disconnect( inputSource );
  15590. }
  15591. }
  15592. // Notify connected
  15593. for ( let i = 0; i < event.added.length; i ++ ) {
  15594. const inputSource = event.added[ i ];
  15595. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15596. if ( controllerIndex === - 1 ) {
  15597. // Assign input source a controller that currently has no input source
  15598. for ( let i = 0; i < controllers.length; i ++ ) {
  15599. if ( i >= controllerInputSources.length ) {
  15600. controllerInputSources.push( inputSource );
  15601. controllerIndex = i;
  15602. break;
  15603. } else if ( controllerInputSources[ i ] === null ) {
  15604. controllerInputSources[ i ] = inputSource;
  15605. controllerIndex = i;
  15606. break;
  15607. }
  15608. }
  15609. // If all controllers do currently receive input we ignore new ones
  15610. if ( controllerIndex === - 1 ) break;
  15611. }
  15612. const controller = controllers[ controllerIndex ];
  15613. if ( controller ) {
  15614. controller.connect( inputSource );
  15615. }
  15616. }
  15617. }
  15618. //
  15619. const cameraLPos = new Vector3();
  15620. const cameraRPos = new Vector3();
  15621. /**
  15622. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15623. * the cameras' projection and world matrices have already been set.
  15624. * And that near and far planes are identical for both cameras.
  15625. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15626. */
  15627. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15628. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15629. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15630. const ipd = cameraLPos.distanceTo( cameraRPos );
  15631. const projL = cameraL.projectionMatrix.elements;
  15632. const projR = cameraR.projectionMatrix.elements;
  15633. // VR systems will have identical far and near planes, and
  15634. // most likely identical top and bottom frustum extents.
  15635. // Use the left camera for these values.
  15636. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15637. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15638. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15639. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15640. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15641. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15642. const left = near * leftFov;
  15643. const right = near * rightFov;
  15644. // Calculate the new camera's position offset from the
  15645. // left camera. xOffset should be roughly half `ipd`.
  15646. const zOffset = ipd / ( - leftFov + rightFov );
  15647. const xOffset = zOffset * - leftFov;
  15648. // TODO: Better way to apply this offset?
  15649. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15650. camera.translateX( xOffset );
  15651. camera.translateZ( zOffset );
  15652. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15653. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15654. // Find the union of the frustum values of the cameras and scale
  15655. // the values so that the near plane's position does not change in world space,
  15656. // although must now be relative to the new union camera.
  15657. const near2 = near + zOffset;
  15658. const far2 = far + zOffset;
  15659. const left2 = left - xOffset;
  15660. const right2 = right + ( ipd - xOffset );
  15661. const top2 = topFov * far / far2 * near2;
  15662. const bottom2 = bottomFov * far / far2 * near2;
  15663. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15664. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  15665. }
  15666. function updateCamera( camera, parent ) {
  15667. if ( parent === null ) {
  15668. camera.matrixWorld.copy( camera.matrix );
  15669. } else {
  15670. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15671. }
  15672. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15673. }
  15674. this.updateCamera = function ( camera ) {
  15675. if ( session === null ) return;
  15676. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15677. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15678. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15679. // Note that the new renderState won't apply until the next frame. See #18320
  15680. session.updateRenderState( {
  15681. depthNear: cameraVR.near,
  15682. depthFar: cameraVR.far
  15683. } );
  15684. _currentDepthNear = cameraVR.near;
  15685. _currentDepthFar = cameraVR.far;
  15686. }
  15687. const parent = camera.parent;
  15688. const cameras = cameraVR.cameras;
  15689. updateCamera( cameraVR, parent );
  15690. for ( let i = 0; i < cameras.length; i ++ ) {
  15691. updateCamera( cameras[ i ], parent );
  15692. }
  15693. // update projection matrix for proper view frustum culling
  15694. if ( cameras.length === 2 ) {
  15695. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15696. } else {
  15697. // assume single camera setup (AR)
  15698. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15699. }
  15700. // update user camera and its children
  15701. updateUserCamera( camera, cameraVR, parent );
  15702. };
  15703. function updateUserCamera( camera, cameraVR, parent ) {
  15704. if ( parent === null ) {
  15705. camera.matrix.copy( cameraVR.matrixWorld );
  15706. } else {
  15707. camera.matrix.copy( parent.matrixWorld );
  15708. camera.matrix.invert();
  15709. camera.matrix.multiply( cameraVR.matrixWorld );
  15710. }
  15711. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15712. camera.updateMatrixWorld( true );
  15713. const children = camera.children;
  15714. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15715. children[ i ].updateMatrixWorld( true );
  15716. }
  15717. camera.projectionMatrix.copy( cameraVR.projectionMatrix );
  15718. camera.projectionMatrixInverse.copy( cameraVR.projectionMatrixInverse );
  15719. if ( camera.isPerspectiveCamera ) {
  15720. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  15721. camera.zoom = 1;
  15722. }
  15723. }
  15724. this.getCamera = function () {
  15725. return cameraVR;
  15726. };
  15727. this.getFoveation = function () {
  15728. if ( glProjLayer === null && glBaseLayer === null ) {
  15729. return undefined;
  15730. }
  15731. return foveation;
  15732. };
  15733. this.setFoveation = function ( value ) {
  15734. // 0 = no foveation = full resolution
  15735. // 1 = maximum foveation = the edges render at lower resolution
  15736. foveation = value;
  15737. if ( glProjLayer !== null ) {
  15738. glProjLayer.fixedFoveation = value;
  15739. }
  15740. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15741. glBaseLayer.fixedFoveation = value;
  15742. }
  15743. };
  15744. this.getPlanes = function () {
  15745. return planes;
  15746. };
  15747. // Animation Loop
  15748. let onAnimationFrameCallback = null;
  15749. function onAnimationFrame( time, frame ) {
  15750. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15751. xrFrame = frame;
  15752. if ( pose !== null ) {
  15753. const views = pose.views;
  15754. if ( glBaseLayer !== null ) {
  15755. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15756. renderer.setRenderTarget( newRenderTarget );
  15757. }
  15758. let cameraVRNeedsUpdate = false;
  15759. // check if it's necessary to rebuild cameraVR's camera list
  15760. if ( views.length !== cameraVR.cameras.length ) {
  15761. cameraVR.cameras.length = 0;
  15762. cameraVRNeedsUpdate = true;
  15763. }
  15764. for ( let i = 0; i < views.length; i ++ ) {
  15765. const view = views[ i ];
  15766. let viewport = null;
  15767. if ( glBaseLayer !== null ) {
  15768. viewport = glBaseLayer.getViewport( view );
  15769. } else {
  15770. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15771. viewport = glSubImage.viewport;
  15772. // For side-by-side projection, we only produce a single texture for both eyes.
  15773. if ( i === 0 ) {
  15774. renderer.setRenderTargetTextures(
  15775. newRenderTarget,
  15776. glSubImage.colorTexture,
  15777. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15778. renderer.setRenderTarget( newRenderTarget );
  15779. }
  15780. }
  15781. let camera = cameras[ i ];
  15782. if ( camera === undefined ) {
  15783. camera = new PerspectiveCamera();
  15784. camera.layers.enable( i );
  15785. camera.viewport = new Vector4();
  15786. cameras[ i ] = camera;
  15787. }
  15788. camera.matrix.fromArray( view.transform.matrix );
  15789. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15790. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15791. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  15792. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15793. if ( i === 0 ) {
  15794. cameraVR.matrix.copy( camera.matrix );
  15795. cameraVR.matrix.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15796. }
  15797. if ( cameraVRNeedsUpdate === true ) {
  15798. cameraVR.cameras.push( camera );
  15799. }
  15800. }
  15801. }
  15802. //
  15803. for ( let i = 0; i < controllers.length; i ++ ) {
  15804. const inputSource = controllerInputSources[ i ];
  15805. const controller = controllers[ i ];
  15806. if ( inputSource !== null && controller !== undefined ) {
  15807. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15808. }
  15809. }
  15810. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15811. if ( frame.detectedPlanes ) {
  15812. scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } );
  15813. let planesToRemove = null;
  15814. for ( const plane of planes ) {
  15815. if ( ! frame.detectedPlanes.has( plane ) ) {
  15816. if ( planesToRemove === null ) {
  15817. planesToRemove = [];
  15818. }
  15819. planesToRemove.push( plane );
  15820. }
  15821. }
  15822. if ( planesToRemove !== null ) {
  15823. for ( const plane of planesToRemove ) {
  15824. planes.delete( plane );
  15825. planesLastChangedTimes.delete( plane );
  15826. scope.dispatchEvent( { type: 'planeremoved', data: plane } );
  15827. }
  15828. }
  15829. for ( const plane of frame.detectedPlanes ) {
  15830. if ( ! planes.has( plane ) ) {
  15831. planes.add( plane );
  15832. planesLastChangedTimes.set( plane, frame.lastChangedTime );
  15833. scope.dispatchEvent( { type: 'planeadded', data: plane } );
  15834. } else {
  15835. const lastKnownTime = planesLastChangedTimes.get( plane );
  15836. if ( plane.lastChangedTime > lastKnownTime ) {
  15837. planesLastChangedTimes.set( plane, plane.lastChangedTime );
  15838. scope.dispatchEvent( { type: 'planechanged', data: plane } );
  15839. }
  15840. }
  15841. }
  15842. }
  15843. xrFrame = null;
  15844. }
  15845. const animation = new WebGLAnimation();
  15846. animation.setAnimationLoop( onAnimationFrame );
  15847. this.setAnimationLoop = function ( callback ) {
  15848. onAnimationFrameCallback = callback;
  15849. };
  15850. this.dispose = function () {};
  15851. }
  15852. }
  15853. function WebGLMaterials( renderer, properties ) {
  15854. function refreshTransformUniform( map, uniform ) {
  15855. if ( map.matrixAutoUpdate === true ) {
  15856. map.updateMatrix();
  15857. }
  15858. uniform.value.copy( map.matrix );
  15859. }
  15860. function refreshFogUniforms( uniforms, fog ) {
  15861. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  15862. if ( fog.isFog ) {
  15863. uniforms.fogNear.value = fog.near;
  15864. uniforms.fogFar.value = fog.far;
  15865. } else if ( fog.isFogExp2 ) {
  15866. uniforms.fogDensity.value = fog.density;
  15867. }
  15868. }
  15869. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15870. if ( material.isMeshBasicMaterial ) {
  15871. refreshUniformsCommon( uniforms, material );
  15872. } else if ( material.isMeshLambertMaterial ) {
  15873. refreshUniformsCommon( uniforms, material );
  15874. } else if ( material.isMeshToonMaterial ) {
  15875. refreshUniformsCommon( uniforms, material );
  15876. refreshUniformsToon( uniforms, material );
  15877. } else if ( material.isMeshPhongMaterial ) {
  15878. refreshUniformsCommon( uniforms, material );
  15879. refreshUniformsPhong( uniforms, material );
  15880. } else if ( material.isMeshStandardMaterial ) {
  15881. refreshUniformsCommon( uniforms, material );
  15882. refreshUniformsStandard( uniforms, material );
  15883. if ( material.isMeshPhysicalMaterial ) {
  15884. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15885. }
  15886. } else if ( material.isMeshMatcapMaterial ) {
  15887. refreshUniformsCommon( uniforms, material );
  15888. refreshUniformsMatcap( uniforms, material );
  15889. } else if ( material.isMeshDepthMaterial ) {
  15890. refreshUniformsCommon( uniforms, material );
  15891. } else if ( material.isMeshDistanceMaterial ) {
  15892. refreshUniformsCommon( uniforms, material );
  15893. refreshUniformsDistance( uniforms, material );
  15894. } else if ( material.isMeshNormalMaterial ) {
  15895. refreshUniformsCommon( uniforms, material );
  15896. } else if ( material.isLineBasicMaterial ) {
  15897. refreshUniformsLine( uniforms, material );
  15898. if ( material.isLineDashedMaterial ) {
  15899. refreshUniformsDash( uniforms, material );
  15900. }
  15901. } else if ( material.isPointsMaterial ) {
  15902. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15903. } else if ( material.isSpriteMaterial ) {
  15904. refreshUniformsSprites( uniforms, material );
  15905. } else if ( material.isShadowMaterial ) {
  15906. uniforms.color.value.copy( material.color );
  15907. uniforms.opacity.value = material.opacity;
  15908. } else if ( material.isShaderMaterial ) {
  15909. material.uniformsNeedUpdate = false; // #15581
  15910. }
  15911. }
  15912. function refreshUniformsCommon( uniforms, material ) {
  15913. uniforms.opacity.value = material.opacity;
  15914. if ( material.color ) {
  15915. uniforms.diffuse.value.copy( material.color );
  15916. }
  15917. if ( material.emissive ) {
  15918. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15919. }
  15920. if ( material.map ) {
  15921. uniforms.map.value = material.map;
  15922. refreshTransformUniform( material.map, uniforms.mapTransform );
  15923. }
  15924. if ( material.alphaMap ) {
  15925. uniforms.alphaMap.value = material.alphaMap;
  15926. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  15927. }
  15928. if ( material.bumpMap ) {
  15929. uniforms.bumpMap.value = material.bumpMap;
  15930. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  15931. uniforms.bumpScale.value = material.bumpScale;
  15932. if ( material.side === BackSide ) {
  15933. uniforms.bumpScale.value *= - 1;
  15934. }
  15935. }
  15936. if ( material.normalMap ) {
  15937. uniforms.normalMap.value = material.normalMap;
  15938. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  15939. uniforms.normalScale.value.copy( material.normalScale );
  15940. if ( material.side === BackSide ) {
  15941. uniforms.normalScale.value.negate();
  15942. }
  15943. }
  15944. if ( material.displacementMap ) {
  15945. uniforms.displacementMap.value = material.displacementMap;
  15946. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  15947. uniforms.displacementScale.value = material.displacementScale;
  15948. uniforms.displacementBias.value = material.displacementBias;
  15949. }
  15950. if ( material.emissiveMap ) {
  15951. uniforms.emissiveMap.value = material.emissiveMap;
  15952. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  15953. }
  15954. if ( material.specularMap ) {
  15955. uniforms.specularMap.value = material.specularMap;
  15956. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  15957. }
  15958. if ( material.alphaTest > 0 ) {
  15959. uniforms.alphaTest.value = material.alphaTest;
  15960. }
  15961. const envMap = properties.get( material ).envMap;
  15962. if ( envMap ) {
  15963. uniforms.envMap.value = envMap;
  15964. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15965. uniforms.reflectivity.value = material.reflectivity;
  15966. uniforms.ior.value = material.ior;
  15967. uniforms.refractionRatio.value = material.refractionRatio;
  15968. }
  15969. if ( material.lightMap ) {
  15970. uniforms.lightMap.value = material.lightMap;
  15971. // artist-friendly light intensity scaling factor
  15972. const scaleFactor = ( renderer.useLegacyLights === true ) ? Math.PI : 1;
  15973. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15974. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  15975. }
  15976. if ( material.aoMap ) {
  15977. uniforms.aoMap.value = material.aoMap;
  15978. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15979. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  15980. }
  15981. }
  15982. function refreshUniformsLine( uniforms, material ) {
  15983. uniforms.diffuse.value.copy( material.color );
  15984. uniforms.opacity.value = material.opacity;
  15985. if ( material.map ) {
  15986. uniforms.map.value = material.map;
  15987. refreshTransformUniform( material.map, uniforms.mapTransform );
  15988. }
  15989. }
  15990. function refreshUniformsDash( uniforms, material ) {
  15991. uniforms.dashSize.value = material.dashSize;
  15992. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15993. uniforms.scale.value = material.scale;
  15994. }
  15995. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15996. uniforms.diffuse.value.copy( material.color );
  15997. uniforms.opacity.value = material.opacity;
  15998. uniforms.size.value = material.size * pixelRatio;
  15999. uniforms.scale.value = height * 0.5;
  16000. if ( material.map ) {
  16001. uniforms.map.value = material.map;
  16002. refreshTransformUniform( material.map, uniforms.uvTransform );
  16003. }
  16004. if ( material.alphaMap ) {
  16005. uniforms.alphaMap.value = material.alphaMap;
  16006. }
  16007. if ( material.alphaTest > 0 ) {
  16008. uniforms.alphaTest.value = material.alphaTest;
  16009. }
  16010. }
  16011. function refreshUniformsSprites( uniforms, material ) {
  16012. uniforms.diffuse.value.copy( material.color );
  16013. uniforms.opacity.value = material.opacity;
  16014. uniforms.rotation.value = material.rotation;
  16015. if ( material.map ) {
  16016. uniforms.map.value = material.map;
  16017. refreshTransformUniform( material.map, uniforms.mapTransform );
  16018. }
  16019. if ( material.alphaMap ) {
  16020. uniforms.alphaMap.value = material.alphaMap;
  16021. }
  16022. if ( material.alphaTest > 0 ) {
  16023. uniforms.alphaTest.value = material.alphaTest;
  16024. }
  16025. }
  16026. function refreshUniformsPhong( uniforms, material ) {
  16027. uniforms.specular.value.copy( material.specular );
  16028. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16029. }
  16030. function refreshUniformsToon( uniforms, material ) {
  16031. if ( material.gradientMap ) {
  16032. uniforms.gradientMap.value = material.gradientMap;
  16033. }
  16034. }
  16035. function refreshUniformsStandard( uniforms, material ) {
  16036. uniforms.metalness.value = material.metalness;
  16037. if ( material.metalnessMap ) {
  16038. uniforms.metalnessMap.value = material.metalnessMap;
  16039. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16040. }
  16041. uniforms.roughness.value = material.roughness;
  16042. if ( material.roughnessMap ) {
  16043. uniforms.roughnessMap.value = material.roughnessMap;
  16044. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16045. }
  16046. const envMap = properties.get( material ).envMap;
  16047. if ( envMap ) {
  16048. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16049. uniforms.envMapIntensity.value = material.envMapIntensity;
  16050. }
  16051. }
  16052. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16053. uniforms.ior.value = material.ior; // also part of uniforms common
  16054. if ( material.sheen > 0 ) {
  16055. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16056. uniforms.sheenRoughness.value = material.sheenRoughness;
  16057. if ( material.sheenColorMap ) {
  16058. uniforms.sheenColorMap.value = material.sheenColorMap;
  16059. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16060. }
  16061. if ( material.sheenRoughnessMap ) {
  16062. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16063. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16064. }
  16065. }
  16066. if ( material.clearcoat > 0 ) {
  16067. uniforms.clearcoat.value = material.clearcoat;
  16068. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16069. if ( material.clearcoatMap ) {
  16070. uniforms.clearcoatMap.value = material.clearcoatMap;
  16071. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16072. }
  16073. if ( material.clearcoatRoughnessMap ) {
  16074. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16075. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16076. }
  16077. if ( material.clearcoatNormalMap ) {
  16078. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16079. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16080. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16081. if ( material.side === BackSide ) {
  16082. uniforms.clearcoatNormalScale.value.negate();
  16083. }
  16084. }
  16085. }
  16086. if ( material.iridescence > 0 ) {
  16087. uniforms.iridescence.value = material.iridescence;
  16088. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16089. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16090. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16091. if ( material.iridescenceMap ) {
  16092. uniforms.iridescenceMap.value = material.iridescenceMap;
  16093. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16094. }
  16095. if ( material.iridescenceThicknessMap ) {
  16096. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16097. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16098. }
  16099. }
  16100. if ( material.transmission > 0 ) {
  16101. uniforms.transmission.value = material.transmission;
  16102. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16103. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16104. if ( material.transmissionMap ) {
  16105. uniforms.transmissionMap.value = material.transmissionMap;
  16106. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16107. }
  16108. uniforms.thickness.value = material.thickness;
  16109. if ( material.thicknessMap ) {
  16110. uniforms.thicknessMap.value = material.thicknessMap;
  16111. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16112. }
  16113. uniforms.attenuationDistance.value = material.attenuationDistance;
  16114. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16115. }
  16116. uniforms.specularIntensity.value = material.specularIntensity;
  16117. uniforms.specularColor.value.copy( material.specularColor );
  16118. if ( material.specularColorMap ) {
  16119. uniforms.specularColorMap.value = material.specularColorMap;
  16120. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16121. }
  16122. if ( material.specularIntensityMap ) {
  16123. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16124. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16125. }
  16126. }
  16127. function refreshUniformsMatcap( uniforms, material ) {
  16128. if ( material.matcap ) {
  16129. uniforms.matcap.value = material.matcap;
  16130. }
  16131. }
  16132. function refreshUniformsDistance( uniforms, material ) {
  16133. const light = properties.get( material ).light;
  16134. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16135. uniforms.nearDistance.value = light.shadow.camera.near;
  16136. uniforms.farDistance.value = light.shadow.camera.far;
  16137. }
  16138. return {
  16139. refreshFogUniforms: refreshFogUniforms,
  16140. refreshMaterialUniforms: refreshMaterialUniforms
  16141. };
  16142. }
  16143. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16144. let buffers = {};
  16145. let updateList = {};
  16146. let allocatedBindingPoints = [];
  16147. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( 35375 ) : 0; // binding points are global whereas block indices are per shader program
  16148. function bind( uniformsGroup, program ) {
  16149. const webglProgram = program.program;
  16150. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16151. }
  16152. function update( uniformsGroup, program ) {
  16153. let buffer = buffers[ uniformsGroup.id ];
  16154. if ( buffer === undefined ) {
  16155. prepareUniformsGroup( uniformsGroup );
  16156. buffer = createBuffer( uniformsGroup );
  16157. buffers[ uniformsGroup.id ] = buffer;
  16158. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16159. }
  16160. // ensure to update the binding points/block indices mapping for this program
  16161. const webglProgram = program.program;
  16162. state.updateUBOMapping( uniformsGroup, webglProgram );
  16163. // update UBO once per frame
  16164. const frame = info.render.frame;
  16165. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16166. updateBufferData( uniformsGroup );
  16167. updateList[ uniformsGroup.id ] = frame;
  16168. }
  16169. }
  16170. function createBuffer( uniformsGroup ) {
  16171. // the setup of an UBO is independent of a particular shader program but global
  16172. const bindingPointIndex = allocateBindingPointIndex();
  16173. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16174. const buffer = gl.createBuffer();
  16175. const size = uniformsGroup.__size;
  16176. const usage = uniformsGroup.usage;
  16177. gl.bindBuffer( 35345, buffer );
  16178. gl.bufferData( 35345, size, usage );
  16179. gl.bindBuffer( 35345, null );
  16180. gl.bindBufferBase( 35345, bindingPointIndex, buffer );
  16181. return buffer;
  16182. }
  16183. function allocateBindingPointIndex() {
  16184. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16185. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16186. allocatedBindingPoints.push( i );
  16187. return i;
  16188. }
  16189. }
  16190. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16191. return 0;
  16192. }
  16193. function updateBufferData( uniformsGroup ) {
  16194. const buffer = buffers[ uniformsGroup.id ];
  16195. const uniforms = uniformsGroup.uniforms;
  16196. const cache = uniformsGroup.__cache;
  16197. gl.bindBuffer( 35345, buffer );
  16198. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16199. const uniform = uniforms[ i ];
  16200. // partly update the buffer if necessary
  16201. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  16202. const offset = uniform.__offset;
  16203. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16204. let arrayOffset = 0;
  16205. for ( let i = 0; i < values.length; i ++ ) {
  16206. const value = values[ i ];
  16207. const info = getUniformSize( value );
  16208. if ( typeof value === 'number' ) {
  16209. uniform.__data[ 0 ] = value;
  16210. gl.bufferSubData( 35345, offset + arrayOffset, uniform.__data );
  16211. } else if ( value.isMatrix3 ) {
  16212. // manually converting 3x3 to 3x4
  16213. uniform.__data[ 0 ] = value.elements[ 0 ];
  16214. uniform.__data[ 1 ] = value.elements[ 1 ];
  16215. uniform.__data[ 2 ] = value.elements[ 2 ];
  16216. uniform.__data[ 3 ] = value.elements[ 0 ];
  16217. uniform.__data[ 4 ] = value.elements[ 3 ];
  16218. uniform.__data[ 5 ] = value.elements[ 4 ];
  16219. uniform.__data[ 6 ] = value.elements[ 5 ];
  16220. uniform.__data[ 7 ] = value.elements[ 0 ];
  16221. uniform.__data[ 8 ] = value.elements[ 6 ];
  16222. uniform.__data[ 9 ] = value.elements[ 7 ];
  16223. uniform.__data[ 10 ] = value.elements[ 8 ];
  16224. uniform.__data[ 11 ] = value.elements[ 0 ];
  16225. } else {
  16226. value.toArray( uniform.__data, arrayOffset );
  16227. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16228. }
  16229. }
  16230. gl.bufferSubData( 35345, offset, uniform.__data );
  16231. }
  16232. }
  16233. gl.bindBuffer( 35345, null );
  16234. }
  16235. function hasUniformChanged( uniform, index, cache ) {
  16236. const value = uniform.value;
  16237. if ( cache[ index ] === undefined ) {
  16238. // cache entry does not exist so far
  16239. if ( typeof value === 'number' ) {
  16240. cache[ index ] = value;
  16241. } else {
  16242. const values = Array.isArray( value ) ? value : [ value ];
  16243. const tempValues = [];
  16244. for ( let i = 0; i < values.length; i ++ ) {
  16245. tempValues.push( values[ i ].clone() );
  16246. }
  16247. cache[ index ] = tempValues;
  16248. }
  16249. return true;
  16250. } else {
  16251. // compare current value with cached entry
  16252. if ( typeof value === 'number' ) {
  16253. if ( cache[ index ] !== value ) {
  16254. cache[ index ] = value;
  16255. return true;
  16256. }
  16257. } else {
  16258. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  16259. const values = Array.isArray( value ) ? value : [ value ];
  16260. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  16261. const cachedObject = cachedObjects[ i ];
  16262. if ( cachedObject.equals( values[ i ] ) === false ) {
  16263. cachedObject.copy( values[ i ] );
  16264. return true;
  16265. }
  16266. }
  16267. }
  16268. }
  16269. return false;
  16270. }
  16271. function prepareUniformsGroup( uniformsGroup ) {
  16272. // determine total buffer size according to the STD140 layout
  16273. // Hint: STD140 is the only supported layout in WebGL 2
  16274. const uniforms = uniformsGroup.uniforms;
  16275. let offset = 0; // global buffer offset in bytes
  16276. const chunkSize = 16; // size of a chunk in bytes
  16277. let chunkOffset = 0; // offset within a single chunk in bytes
  16278. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16279. const uniform = uniforms[ i ];
  16280. const infos = {
  16281. boundary: 0, // bytes
  16282. storage: 0 // bytes
  16283. };
  16284. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16285. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  16286. const value = values[ j ];
  16287. const info = getUniformSize( value );
  16288. infos.boundary += info.boundary;
  16289. infos.storage += info.storage;
  16290. }
  16291. // the following two properties will be used for partial buffer updates
  16292. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16293. uniform.__offset = offset;
  16294. //
  16295. if ( i > 0 ) {
  16296. chunkOffset = offset % chunkSize;
  16297. const remainingSizeInChunk = chunkSize - chunkOffset;
  16298. // check for chunk overflow
  16299. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16300. // add padding and adjust offset
  16301. offset += ( chunkSize - chunkOffset );
  16302. uniform.__offset = offset;
  16303. }
  16304. }
  16305. offset += infos.storage;
  16306. }
  16307. // ensure correct final padding
  16308. chunkOffset = offset % chunkSize;
  16309. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16310. //
  16311. uniformsGroup.__size = offset;
  16312. uniformsGroup.__cache = {};
  16313. return this;
  16314. }
  16315. function getUniformSize( value ) {
  16316. const info = {
  16317. boundary: 0, // bytes
  16318. storage: 0 // bytes
  16319. };
  16320. // determine sizes according to STD140
  16321. if ( typeof value === 'number' ) {
  16322. // float/int
  16323. info.boundary = 4;
  16324. info.storage = 4;
  16325. } else if ( value.isVector2 ) {
  16326. // vec2
  16327. info.boundary = 8;
  16328. info.storage = 8;
  16329. } else if ( value.isVector3 || value.isColor ) {
  16330. // vec3
  16331. info.boundary = 16;
  16332. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16333. } else if ( value.isVector4 ) {
  16334. // vec4
  16335. info.boundary = 16;
  16336. info.storage = 16;
  16337. } else if ( value.isMatrix3 ) {
  16338. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16339. info.boundary = 48;
  16340. info.storage = 48;
  16341. } else if ( value.isMatrix4 ) {
  16342. // mat4
  16343. info.boundary = 64;
  16344. info.storage = 64;
  16345. } else if ( value.isTexture ) {
  16346. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16347. } else {
  16348. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16349. }
  16350. return info;
  16351. }
  16352. function onUniformsGroupsDispose( event ) {
  16353. const uniformsGroup = event.target;
  16354. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16355. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16356. allocatedBindingPoints.splice( index, 1 );
  16357. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16358. delete buffers[ uniformsGroup.id ];
  16359. delete updateList[ uniformsGroup.id ];
  16360. }
  16361. function dispose() {
  16362. for ( const id in buffers ) {
  16363. gl.deleteBuffer( buffers[ id ] );
  16364. }
  16365. allocatedBindingPoints = [];
  16366. buffers = {};
  16367. updateList = {};
  16368. }
  16369. return {
  16370. bind: bind,
  16371. update: update,
  16372. dispose: dispose
  16373. };
  16374. }
  16375. function createCanvasElement() {
  16376. const canvas = createElementNS( 'canvas' );
  16377. canvas.style.display = 'block';
  16378. return canvas;
  16379. }
  16380. class WebGLRenderer {
  16381. constructor( parameters = {} ) {
  16382. const {
  16383. canvas = createCanvasElement(),
  16384. context = null,
  16385. depth = true,
  16386. stencil = true,
  16387. alpha = false,
  16388. antialias = false,
  16389. premultipliedAlpha = true,
  16390. preserveDrawingBuffer = false,
  16391. powerPreference = 'default',
  16392. failIfMajorPerformanceCaveat = false,
  16393. } = parameters;
  16394. this.isWebGLRenderer = true;
  16395. let _alpha;
  16396. if ( context !== null ) {
  16397. _alpha = context.getContextAttributes().alpha;
  16398. } else {
  16399. _alpha = alpha;
  16400. }
  16401. let currentRenderList = null;
  16402. let currentRenderState = null;
  16403. // render() can be called from within a callback triggered by another render.
  16404. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16405. const renderListStack = [];
  16406. const renderStateStack = [];
  16407. // public properties
  16408. this.domElement = canvas;
  16409. // Debug configuration container
  16410. this.debug = {
  16411. /**
  16412. * Enables error checking and reporting when shader programs are being compiled
  16413. * @type {boolean}
  16414. */
  16415. checkShaderErrors: true,
  16416. /**
  16417. * Callback for custom error reporting.
  16418. * @type {?Function}
  16419. */
  16420. onShaderError: null
  16421. };
  16422. // clearing
  16423. this.autoClear = true;
  16424. this.autoClearColor = true;
  16425. this.autoClearDepth = true;
  16426. this.autoClearStencil = true;
  16427. // scene graph
  16428. this.sortObjects = true;
  16429. // user-defined clipping
  16430. this.clippingPlanes = [];
  16431. this.localClippingEnabled = false;
  16432. // physically based shading
  16433. this.outputEncoding = LinearEncoding;
  16434. // physical lights
  16435. this.useLegacyLights = true;
  16436. // tone mapping
  16437. this.toneMapping = NoToneMapping;
  16438. this.toneMappingExposure = 1.0;
  16439. // internal properties
  16440. const _this = this;
  16441. let _isContextLost = false;
  16442. // internal state cache
  16443. let _currentActiveCubeFace = 0;
  16444. let _currentActiveMipmapLevel = 0;
  16445. let _currentRenderTarget = null;
  16446. let _currentMaterialId = - 1;
  16447. let _currentCamera = null;
  16448. const _currentViewport = new Vector4();
  16449. const _currentScissor = new Vector4();
  16450. let _currentScissorTest = null;
  16451. //
  16452. let _width = canvas.width;
  16453. let _height = canvas.height;
  16454. let _pixelRatio = 1;
  16455. let _opaqueSort = null;
  16456. let _transparentSort = null;
  16457. const _viewport = new Vector4( 0, 0, _width, _height );
  16458. const _scissor = new Vector4( 0, 0, _width, _height );
  16459. let _scissorTest = false;
  16460. // frustum
  16461. const _frustum = new Frustum();
  16462. // clipping
  16463. let _clippingEnabled = false;
  16464. let _localClippingEnabled = false;
  16465. // transmission
  16466. let _transmissionRenderTarget = null;
  16467. // camera matrices cache
  16468. const _projScreenMatrix = new Matrix4();
  16469. const _vector3 = new Vector3();
  16470. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16471. function getTargetPixelRatio() {
  16472. return _currentRenderTarget === null ? _pixelRatio : 1;
  16473. }
  16474. // initialize
  16475. let _gl = context;
  16476. function getContext( contextNames, contextAttributes ) {
  16477. for ( let i = 0; i < contextNames.length; i ++ ) {
  16478. const contextName = contextNames[ i ];
  16479. const context = canvas.getContext( contextName, contextAttributes );
  16480. if ( context !== null ) return context;
  16481. }
  16482. return null;
  16483. }
  16484. try {
  16485. const contextAttributes = {
  16486. alpha: true,
  16487. depth,
  16488. stencil,
  16489. antialias,
  16490. premultipliedAlpha,
  16491. preserveDrawingBuffer,
  16492. powerPreference,
  16493. failIfMajorPerformanceCaveat,
  16494. };
  16495. // OffscreenCanvas does not have setAttribute, see #22811
  16496. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16497. // event listeners must be registered before WebGL context is created, see #12753
  16498. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16499. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16500. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16501. if ( _gl === null ) {
  16502. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16503. if ( _this.isWebGL1Renderer === true ) {
  16504. contextNames.shift();
  16505. }
  16506. _gl = getContext( contextNames, contextAttributes );
  16507. if ( _gl === null ) {
  16508. if ( getContext( contextNames ) ) {
  16509. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16510. } else {
  16511. throw new Error( 'Error creating WebGL context.' );
  16512. }
  16513. }
  16514. }
  16515. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16516. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16517. _gl.getShaderPrecisionFormat = function () {
  16518. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16519. };
  16520. }
  16521. } catch ( error ) {
  16522. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16523. throw error;
  16524. }
  16525. let extensions, capabilities, state, info;
  16526. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16527. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16528. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16529. let utils, bindingStates, uniformsGroups;
  16530. function initGLContext() {
  16531. extensions = new WebGLExtensions( _gl );
  16532. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16533. extensions.init( capabilities );
  16534. utils = new WebGLUtils( _gl, extensions, capabilities );
  16535. state = new WebGLState( _gl, extensions, capabilities );
  16536. info = new WebGLInfo();
  16537. properties = new WebGLProperties();
  16538. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16539. cubemaps = new WebGLCubeMaps( _this );
  16540. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16541. attributes = new WebGLAttributes( _gl, capabilities );
  16542. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16543. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16544. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16545. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16546. clipping = new WebGLClipping( properties );
  16547. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16548. materials = new WebGLMaterials( _this, properties );
  16549. renderLists = new WebGLRenderLists();
  16550. renderStates = new WebGLRenderStates( extensions, capabilities );
  16551. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  16552. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16553. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16554. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16555. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16556. info.programs = programCache.programs;
  16557. _this.capabilities = capabilities;
  16558. _this.extensions = extensions;
  16559. _this.properties = properties;
  16560. _this.renderLists = renderLists;
  16561. _this.shadowMap = shadowMap;
  16562. _this.state = state;
  16563. _this.info = info;
  16564. }
  16565. initGLContext();
  16566. // xr
  16567. const xr = new WebXRManager( _this, _gl );
  16568. this.xr = xr;
  16569. // API
  16570. this.getContext = function () {
  16571. return _gl;
  16572. };
  16573. this.getContextAttributes = function () {
  16574. return _gl.getContextAttributes();
  16575. };
  16576. this.forceContextLoss = function () {
  16577. const extension = extensions.get( 'WEBGL_lose_context' );
  16578. if ( extension ) extension.loseContext();
  16579. };
  16580. this.forceContextRestore = function () {
  16581. const extension = extensions.get( 'WEBGL_lose_context' );
  16582. if ( extension ) extension.restoreContext();
  16583. };
  16584. this.getPixelRatio = function () {
  16585. return _pixelRatio;
  16586. };
  16587. this.setPixelRatio = function ( value ) {
  16588. if ( value === undefined ) return;
  16589. _pixelRatio = value;
  16590. this.setSize( _width, _height, false );
  16591. };
  16592. this.getSize = function ( target ) {
  16593. return target.set( _width, _height );
  16594. };
  16595. this.setSize = function ( width, height, updateStyle = true ) {
  16596. if ( xr.isPresenting ) {
  16597. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16598. return;
  16599. }
  16600. _width = width;
  16601. _height = height;
  16602. canvas.width = Math.floor( width * _pixelRatio );
  16603. canvas.height = Math.floor( height * _pixelRatio );
  16604. if ( updateStyle === true ) {
  16605. canvas.style.width = width + 'px';
  16606. canvas.style.height = height + 'px';
  16607. }
  16608. this.setViewport( 0, 0, width, height );
  16609. };
  16610. this.getDrawingBufferSize = function ( target ) {
  16611. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16612. };
  16613. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16614. _width = width;
  16615. _height = height;
  16616. _pixelRatio = pixelRatio;
  16617. canvas.width = Math.floor( width * pixelRatio );
  16618. canvas.height = Math.floor( height * pixelRatio );
  16619. this.setViewport( 0, 0, width, height );
  16620. };
  16621. this.getCurrentViewport = function ( target ) {
  16622. return target.copy( _currentViewport );
  16623. };
  16624. this.getViewport = function ( target ) {
  16625. return target.copy( _viewport );
  16626. };
  16627. this.setViewport = function ( x, y, width, height ) {
  16628. if ( x.isVector4 ) {
  16629. _viewport.set( x.x, x.y, x.z, x.w );
  16630. } else {
  16631. _viewport.set( x, y, width, height );
  16632. }
  16633. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16634. };
  16635. this.getScissor = function ( target ) {
  16636. return target.copy( _scissor );
  16637. };
  16638. this.setScissor = function ( x, y, width, height ) {
  16639. if ( x.isVector4 ) {
  16640. _scissor.set( x.x, x.y, x.z, x.w );
  16641. } else {
  16642. _scissor.set( x, y, width, height );
  16643. }
  16644. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16645. };
  16646. this.getScissorTest = function () {
  16647. return _scissorTest;
  16648. };
  16649. this.setScissorTest = function ( boolean ) {
  16650. state.setScissorTest( _scissorTest = boolean );
  16651. };
  16652. this.setOpaqueSort = function ( method ) {
  16653. _opaqueSort = method;
  16654. };
  16655. this.setTransparentSort = function ( method ) {
  16656. _transparentSort = method;
  16657. };
  16658. // Clearing
  16659. this.getClearColor = function ( target ) {
  16660. return target.copy( background.getClearColor() );
  16661. };
  16662. this.setClearColor = function () {
  16663. background.setClearColor.apply( background, arguments );
  16664. };
  16665. this.getClearAlpha = function () {
  16666. return background.getClearAlpha();
  16667. };
  16668. this.setClearAlpha = function () {
  16669. background.setClearAlpha.apply( background, arguments );
  16670. };
  16671. this.clear = function ( color = true, depth = true, stencil = true ) {
  16672. let bits = 0;
  16673. if ( color ) bits |= 16384;
  16674. if ( depth ) bits |= 256;
  16675. if ( stencil ) bits |= 1024;
  16676. _gl.clear( bits );
  16677. };
  16678. this.clearColor = function () {
  16679. this.clear( true, false, false );
  16680. };
  16681. this.clearDepth = function () {
  16682. this.clear( false, true, false );
  16683. };
  16684. this.clearStencil = function () {
  16685. this.clear( false, false, true );
  16686. };
  16687. //
  16688. this.dispose = function () {
  16689. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16690. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16691. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16692. renderLists.dispose();
  16693. renderStates.dispose();
  16694. properties.dispose();
  16695. cubemaps.dispose();
  16696. cubeuvmaps.dispose();
  16697. objects.dispose();
  16698. bindingStates.dispose();
  16699. uniformsGroups.dispose();
  16700. programCache.dispose();
  16701. xr.dispose();
  16702. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16703. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16704. if ( _transmissionRenderTarget ) {
  16705. _transmissionRenderTarget.dispose();
  16706. _transmissionRenderTarget = null;
  16707. }
  16708. animation.stop();
  16709. };
  16710. // Events
  16711. function onContextLost( event ) {
  16712. event.preventDefault();
  16713. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16714. _isContextLost = true;
  16715. }
  16716. function onContextRestore( /* event */ ) {
  16717. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16718. _isContextLost = false;
  16719. const infoAutoReset = info.autoReset;
  16720. const shadowMapEnabled = shadowMap.enabled;
  16721. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16722. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16723. const shadowMapType = shadowMap.type;
  16724. initGLContext();
  16725. info.autoReset = infoAutoReset;
  16726. shadowMap.enabled = shadowMapEnabled;
  16727. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16728. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16729. shadowMap.type = shadowMapType;
  16730. }
  16731. function onContextCreationError( event ) {
  16732. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16733. }
  16734. function onMaterialDispose( event ) {
  16735. const material = event.target;
  16736. material.removeEventListener( 'dispose', onMaterialDispose );
  16737. deallocateMaterial( material );
  16738. }
  16739. // Buffer deallocation
  16740. function deallocateMaterial( material ) {
  16741. releaseMaterialProgramReferences( material );
  16742. properties.remove( material );
  16743. }
  16744. function releaseMaterialProgramReferences( material ) {
  16745. const programs = properties.get( material ).programs;
  16746. if ( programs !== undefined ) {
  16747. programs.forEach( function ( program ) {
  16748. programCache.releaseProgram( program );
  16749. } );
  16750. if ( material.isShaderMaterial ) {
  16751. programCache.releaseShaderCache( material );
  16752. }
  16753. }
  16754. }
  16755. // Buffer rendering
  16756. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16757. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16758. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16759. const program = setProgram( camera, scene, geometry, material, object );
  16760. state.setMaterial( material, frontFaceCW );
  16761. //
  16762. let index = geometry.index;
  16763. let rangeFactor = 1;
  16764. if ( material.wireframe === true ) {
  16765. index = geometries.getWireframeAttribute( geometry );
  16766. rangeFactor = 2;
  16767. }
  16768. //
  16769. const drawRange = geometry.drawRange;
  16770. const position = geometry.attributes.position;
  16771. let drawStart = drawRange.start * rangeFactor;
  16772. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  16773. if ( group !== null ) {
  16774. drawStart = Math.max( drawStart, group.start * rangeFactor );
  16775. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  16776. }
  16777. if ( index !== null ) {
  16778. drawStart = Math.max( drawStart, 0 );
  16779. drawEnd = Math.min( drawEnd, index.count );
  16780. } else if ( position !== undefined && position !== null ) {
  16781. drawStart = Math.max( drawStart, 0 );
  16782. drawEnd = Math.min( drawEnd, position.count );
  16783. }
  16784. const drawCount = drawEnd - drawStart;
  16785. if ( drawCount < 0 || drawCount === Infinity ) return;
  16786. //
  16787. bindingStates.setup( object, material, program, geometry, index );
  16788. let attribute;
  16789. let renderer = bufferRenderer;
  16790. if ( index !== null ) {
  16791. attribute = attributes.get( index );
  16792. renderer = indexedBufferRenderer;
  16793. renderer.setIndex( attribute );
  16794. }
  16795. //
  16796. if ( object.isMesh ) {
  16797. if ( material.wireframe === true ) {
  16798. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16799. renderer.setMode( 1 );
  16800. } else {
  16801. renderer.setMode( 4 );
  16802. }
  16803. } else if ( object.isLine ) {
  16804. let lineWidth = material.linewidth;
  16805. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16806. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16807. if ( object.isLineSegments ) {
  16808. renderer.setMode( 1 );
  16809. } else if ( object.isLineLoop ) {
  16810. renderer.setMode( 2 );
  16811. } else {
  16812. renderer.setMode( 3 );
  16813. }
  16814. } else if ( object.isPoints ) {
  16815. renderer.setMode( 0 );
  16816. } else if ( object.isSprite ) {
  16817. renderer.setMode( 4 );
  16818. }
  16819. if ( object.isInstancedMesh ) {
  16820. renderer.renderInstances( drawStart, drawCount, object.count );
  16821. } else if ( geometry.isInstancedBufferGeometry ) {
  16822. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  16823. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  16824. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16825. } else {
  16826. renderer.render( drawStart, drawCount );
  16827. }
  16828. };
  16829. // Compile
  16830. this.compile = function ( scene, camera ) {
  16831. function prepare( material, scene, object ) {
  16832. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16833. material.side = BackSide;
  16834. material.needsUpdate = true;
  16835. getProgram( material, scene, object );
  16836. material.side = FrontSide;
  16837. material.needsUpdate = true;
  16838. getProgram( material, scene, object );
  16839. material.side = DoubleSide;
  16840. } else {
  16841. getProgram( material, scene, object );
  16842. }
  16843. }
  16844. currentRenderState = renderStates.get( scene );
  16845. currentRenderState.init();
  16846. renderStateStack.push( currentRenderState );
  16847. scene.traverseVisible( function ( object ) {
  16848. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16849. currentRenderState.pushLight( object );
  16850. if ( object.castShadow ) {
  16851. currentRenderState.pushShadow( object );
  16852. }
  16853. }
  16854. } );
  16855. currentRenderState.setupLights( _this.useLegacyLights );
  16856. scene.traverse( function ( object ) {
  16857. const material = object.material;
  16858. if ( material ) {
  16859. if ( Array.isArray( material ) ) {
  16860. for ( let i = 0; i < material.length; i ++ ) {
  16861. const material2 = material[ i ];
  16862. prepare( material2, scene, object );
  16863. }
  16864. } else {
  16865. prepare( material, scene, object );
  16866. }
  16867. }
  16868. } );
  16869. renderStateStack.pop();
  16870. currentRenderState = null;
  16871. };
  16872. // Animation Loop
  16873. let onAnimationFrameCallback = null;
  16874. function onAnimationFrame( time ) {
  16875. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16876. }
  16877. function onXRSessionStart() {
  16878. animation.stop();
  16879. }
  16880. function onXRSessionEnd() {
  16881. animation.start();
  16882. }
  16883. const animation = new WebGLAnimation();
  16884. animation.setAnimationLoop( onAnimationFrame );
  16885. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16886. this.setAnimationLoop = function ( callback ) {
  16887. onAnimationFrameCallback = callback;
  16888. xr.setAnimationLoop( callback );
  16889. ( callback === null ) ? animation.stop() : animation.start();
  16890. };
  16891. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16892. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16893. // Rendering
  16894. this.render = function ( scene, camera ) {
  16895. if ( camera !== undefined && camera.isCamera !== true ) {
  16896. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16897. return;
  16898. }
  16899. if ( _isContextLost === true ) return;
  16900. // update scene graph
  16901. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16902. // update camera matrices and frustum
  16903. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16904. if ( xr.enabled === true && xr.isPresenting === true ) {
  16905. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16906. camera = xr.getCamera(); // use XR camera for rendering
  16907. }
  16908. //
  16909. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16910. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16911. currentRenderState.init();
  16912. renderStateStack.push( currentRenderState );
  16913. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16914. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16915. _localClippingEnabled = this.localClippingEnabled;
  16916. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  16917. currentRenderList = renderLists.get( scene, renderListStack.length );
  16918. currentRenderList.init();
  16919. renderListStack.push( currentRenderList );
  16920. projectObject( scene, camera, 0, _this.sortObjects );
  16921. currentRenderList.finish();
  16922. if ( _this.sortObjects === true ) {
  16923. currentRenderList.sort( _opaqueSort, _transparentSort );
  16924. }
  16925. //
  16926. if ( _clippingEnabled === true ) clipping.beginShadows();
  16927. const shadowsArray = currentRenderState.state.shadowsArray;
  16928. shadowMap.render( shadowsArray, scene, camera );
  16929. if ( _clippingEnabled === true ) clipping.endShadows();
  16930. //
  16931. if ( this.info.autoReset === true ) this.info.reset();
  16932. //
  16933. background.render( currentRenderList, scene );
  16934. // render scene
  16935. currentRenderState.setupLights( _this.useLegacyLights );
  16936. if ( camera.isArrayCamera ) {
  16937. const cameras = camera.cameras;
  16938. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16939. const camera2 = cameras[ i ];
  16940. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16941. }
  16942. } else {
  16943. renderScene( currentRenderList, scene, camera );
  16944. }
  16945. //
  16946. if ( _currentRenderTarget !== null ) {
  16947. // resolve multisample renderbuffers to a single-sample texture if necessary
  16948. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16949. // Generate mipmap if we're using any kind of mipmap filtering
  16950. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16951. }
  16952. //
  16953. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16954. // _gl.finish();
  16955. bindingStates.resetDefaultState();
  16956. _currentMaterialId = - 1;
  16957. _currentCamera = null;
  16958. renderStateStack.pop();
  16959. if ( renderStateStack.length > 0 ) {
  16960. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16961. } else {
  16962. currentRenderState = null;
  16963. }
  16964. renderListStack.pop();
  16965. if ( renderListStack.length > 0 ) {
  16966. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16967. } else {
  16968. currentRenderList = null;
  16969. }
  16970. };
  16971. function projectObject( object, camera, groupOrder, sortObjects ) {
  16972. if ( object.visible === false ) return;
  16973. const visible = object.layers.test( camera.layers );
  16974. if ( visible ) {
  16975. if ( object.isGroup ) {
  16976. groupOrder = object.renderOrder;
  16977. } else if ( object.isLOD ) {
  16978. if ( object.autoUpdate === true ) object.update( camera );
  16979. } else if ( object.isLight ) {
  16980. currentRenderState.pushLight( object );
  16981. if ( object.castShadow ) {
  16982. currentRenderState.pushShadow( object );
  16983. }
  16984. } else if ( object.isSprite ) {
  16985. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16986. if ( sortObjects ) {
  16987. _vector3.setFromMatrixPosition( object.matrixWorld )
  16988. .applyMatrix4( _projScreenMatrix );
  16989. }
  16990. const geometry = objects.update( object );
  16991. const material = object.material;
  16992. if ( material.visible ) {
  16993. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16994. }
  16995. }
  16996. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16997. if ( object.isSkinnedMesh ) {
  16998. // update skeleton only once in a frame
  16999. if ( object.skeleton.frame !== info.render.frame ) {
  17000. object.skeleton.update();
  17001. object.skeleton.frame = info.render.frame;
  17002. }
  17003. }
  17004. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17005. if ( sortObjects ) {
  17006. _vector3.setFromMatrixPosition( object.matrixWorld )
  17007. .applyMatrix4( _projScreenMatrix );
  17008. }
  17009. const geometry = objects.update( object );
  17010. const material = object.material;
  17011. if ( Array.isArray( material ) ) {
  17012. const groups = geometry.groups;
  17013. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17014. const group = groups[ i ];
  17015. const groupMaterial = material[ group.materialIndex ];
  17016. if ( groupMaterial && groupMaterial.visible ) {
  17017. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  17018. }
  17019. }
  17020. } else if ( material.visible ) {
  17021. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17022. }
  17023. }
  17024. }
  17025. }
  17026. const children = object.children;
  17027. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17028. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17029. }
  17030. }
  17031. function renderScene( currentRenderList, scene, camera, viewport ) {
  17032. const opaqueObjects = currentRenderList.opaque;
  17033. const transmissiveObjects = currentRenderList.transmissive;
  17034. const transparentObjects = currentRenderList.transparent;
  17035. currentRenderState.setupLightsView( camera );
  17036. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17037. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17038. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17039. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17040. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17041. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17042. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17043. state.buffers.depth.setTest( true );
  17044. state.buffers.depth.setMask( true );
  17045. state.buffers.color.setMask( true );
  17046. state.setPolygonOffset( false );
  17047. }
  17048. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17049. if ( _transmissionRenderTarget === null ) {
  17050. const isWebGL2 = capabilities.isWebGL2;
  17051. _transmissionRenderTarget = new WebGLRenderTarget( 1024, 1024, {
  17052. generateMipmaps: true,
  17053. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  17054. minFilter: LinearMipmapLinearFilter,
  17055. samples: ( isWebGL2 && antialias === true ) ? 4 : 0
  17056. } );
  17057. // debug
  17058. /*
  17059. const geometry = new PlaneGeometry();
  17060. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17061. const mesh = new Mesh( geometry, material );
  17062. scene.add( mesh );
  17063. */
  17064. }
  17065. //
  17066. const currentRenderTarget = _this.getRenderTarget();
  17067. _this.setRenderTarget( _transmissionRenderTarget );
  17068. _this.clear();
  17069. // Turn off the features which can affect the frag color for opaque objects pass.
  17070. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17071. const currentToneMapping = _this.toneMapping;
  17072. _this.toneMapping = NoToneMapping;
  17073. renderObjects( opaqueObjects, scene, camera );
  17074. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17075. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17076. let renderTargetNeedsUpdate = false;
  17077. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17078. const renderItem = transmissiveObjects[ i ];
  17079. const object = renderItem.object;
  17080. const geometry = renderItem.geometry;
  17081. const material = renderItem.material;
  17082. const group = renderItem.group;
  17083. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17084. const currentSide = material.side;
  17085. material.side = BackSide;
  17086. material.needsUpdate = true;
  17087. renderObject( object, scene, camera, geometry, material, group );
  17088. material.side = currentSide;
  17089. material.needsUpdate = true;
  17090. renderTargetNeedsUpdate = true;
  17091. }
  17092. }
  17093. if ( renderTargetNeedsUpdate === true ) {
  17094. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17095. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17096. }
  17097. _this.setRenderTarget( currentRenderTarget );
  17098. _this.toneMapping = currentToneMapping;
  17099. }
  17100. function renderObjects( renderList, scene, camera ) {
  17101. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17102. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17103. const renderItem = renderList[ i ];
  17104. const object = renderItem.object;
  17105. const geometry = renderItem.geometry;
  17106. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17107. const group = renderItem.group;
  17108. if ( object.layers.test( camera.layers ) ) {
  17109. renderObject( object, scene, camera, geometry, material, group );
  17110. }
  17111. }
  17112. }
  17113. function renderObject( object, scene, camera, geometry, material, group ) {
  17114. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17115. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17116. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17117. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17118. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17119. material.side = BackSide;
  17120. material.needsUpdate = true;
  17121. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17122. material.side = FrontSide;
  17123. material.needsUpdate = true;
  17124. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17125. material.side = DoubleSide;
  17126. } else {
  17127. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17128. }
  17129. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17130. }
  17131. function getProgram( material, scene, object ) {
  17132. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17133. const materialProperties = properties.get( material );
  17134. const lights = currentRenderState.state.lights;
  17135. const shadowsArray = currentRenderState.state.shadowsArray;
  17136. const lightsStateVersion = lights.state.version;
  17137. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17138. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17139. let programs = materialProperties.programs;
  17140. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17141. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17142. materialProperties.fog = scene.fog;
  17143. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17144. if ( programs === undefined ) {
  17145. // new material
  17146. material.addEventListener( 'dispose', onMaterialDispose );
  17147. programs = new Map();
  17148. materialProperties.programs = programs;
  17149. }
  17150. let program = programs.get( programCacheKey );
  17151. if ( program !== undefined ) {
  17152. // early out if program and light state is identical
  17153. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17154. updateCommonMaterialProperties( material, parameters );
  17155. return program;
  17156. }
  17157. } else {
  17158. parameters.uniforms = programCache.getUniforms( material );
  17159. material.onBuild( object, parameters, _this );
  17160. material.onBeforeCompile( parameters, _this );
  17161. program = programCache.acquireProgram( parameters, programCacheKey );
  17162. programs.set( programCacheKey, program );
  17163. materialProperties.uniforms = parameters.uniforms;
  17164. }
  17165. const uniforms = materialProperties.uniforms;
  17166. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17167. uniforms.clippingPlanes = clipping.uniform;
  17168. }
  17169. updateCommonMaterialProperties( material, parameters );
  17170. // store the light setup it was created for
  17171. materialProperties.needsLights = materialNeedsLights( material );
  17172. materialProperties.lightsStateVersion = lightsStateVersion;
  17173. if ( materialProperties.needsLights ) {
  17174. // wire up the material to this renderer's lighting state
  17175. uniforms.ambientLightColor.value = lights.state.ambient;
  17176. uniforms.lightProbe.value = lights.state.probe;
  17177. uniforms.directionalLights.value = lights.state.directional;
  17178. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17179. uniforms.spotLights.value = lights.state.spot;
  17180. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17181. uniforms.rectAreaLights.value = lights.state.rectArea;
  17182. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17183. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17184. uniforms.pointLights.value = lights.state.point;
  17185. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17186. uniforms.hemisphereLights.value = lights.state.hemi;
  17187. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17188. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17189. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17190. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17191. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17192. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17193. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17194. // TODO (abelnation): add area lights shadow info to uniforms
  17195. }
  17196. const progUniforms = program.getUniforms();
  17197. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17198. materialProperties.currentProgram = program;
  17199. materialProperties.uniformsList = uniformsList;
  17200. return program;
  17201. }
  17202. function updateCommonMaterialProperties( material, parameters ) {
  17203. const materialProperties = properties.get( material );
  17204. materialProperties.outputEncoding = parameters.outputEncoding;
  17205. materialProperties.instancing = parameters.instancing;
  17206. materialProperties.skinning = parameters.skinning;
  17207. materialProperties.morphTargets = parameters.morphTargets;
  17208. materialProperties.morphNormals = parameters.morphNormals;
  17209. materialProperties.morphColors = parameters.morphColors;
  17210. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17211. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17212. materialProperties.numIntersection = parameters.numClipIntersection;
  17213. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17214. materialProperties.vertexTangents = parameters.vertexTangents;
  17215. materialProperties.toneMapping = parameters.toneMapping;
  17216. }
  17217. function setProgram( camera, scene, geometry, material, object ) {
  17218. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17219. textures.resetTextureUnits();
  17220. const fog = scene.fog;
  17221. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17222. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  17223. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17224. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17225. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  17226. const morphTargets = !! geometry.morphAttributes.position;
  17227. const morphNormals = !! geometry.morphAttributes.normal;
  17228. const morphColors = !! geometry.morphAttributes.color;
  17229. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  17230. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17231. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  17232. const materialProperties = properties.get( material );
  17233. const lights = currentRenderState.state.lights;
  17234. if ( _clippingEnabled === true ) {
  17235. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17236. const useCache =
  17237. camera === _currentCamera &&
  17238. material.id === _currentMaterialId;
  17239. // we might want to call this function with some ClippingGroup
  17240. // object instead of the material, once it becomes feasible
  17241. // (#8465, #8379)
  17242. clipping.setState( material, camera, useCache );
  17243. }
  17244. }
  17245. //
  17246. let needsProgramChange = false;
  17247. if ( material.version === materialProperties.__version ) {
  17248. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17249. needsProgramChange = true;
  17250. } else if ( materialProperties.outputEncoding !== encoding ) {
  17251. needsProgramChange = true;
  17252. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17253. needsProgramChange = true;
  17254. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17255. needsProgramChange = true;
  17256. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17257. needsProgramChange = true;
  17258. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17259. needsProgramChange = true;
  17260. } else if ( materialProperties.envMap !== envMap ) {
  17261. needsProgramChange = true;
  17262. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17263. needsProgramChange = true;
  17264. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17265. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17266. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17267. needsProgramChange = true;
  17268. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17269. needsProgramChange = true;
  17270. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17271. needsProgramChange = true;
  17272. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17273. needsProgramChange = true;
  17274. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17275. needsProgramChange = true;
  17276. } else if ( materialProperties.morphColors !== morphColors ) {
  17277. needsProgramChange = true;
  17278. } else if ( materialProperties.toneMapping !== toneMapping ) {
  17279. needsProgramChange = true;
  17280. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  17281. needsProgramChange = true;
  17282. }
  17283. } else {
  17284. needsProgramChange = true;
  17285. materialProperties.__version = material.version;
  17286. }
  17287. //
  17288. let program = materialProperties.currentProgram;
  17289. if ( needsProgramChange === true ) {
  17290. program = getProgram( material, scene, object );
  17291. }
  17292. let refreshProgram = false;
  17293. let refreshMaterial = false;
  17294. let refreshLights = false;
  17295. const p_uniforms = program.getUniforms(),
  17296. m_uniforms = materialProperties.uniforms;
  17297. if ( state.useProgram( program.program ) ) {
  17298. refreshProgram = true;
  17299. refreshMaterial = true;
  17300. refreshLights = true;
  17301. }
  17302. if ( material.id !== _currentMaterialId ) {
  17303. _currentMaterialId = material.id;
  17304. refreshMaterial = true;
  17305. }
  17306. if ( refreshProgram || _currentCamera !== camera ) {
  17307. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17308. if ( capabilities.logarithmicDepthBuffer ) {
  17309. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17310. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17311. }
  17312. if ( _currentCamera !== camera ) {
  17313. _currentCamera = camera;
  17314. // lighting uniforms depend on the camera so enforce an update
  17315. // now, in case this material supports lights - or later, when
  17316. // the next material that does gets activated:
  17317. refreshMaterial = true; // set to true on material change
  17318. refreshLights = true; // remains set until update done
  17319. }
  17320. // load material specific uniforms
  17321. // (shader material also gets them for the sake of genericity)
  17322. if ( material.isShaderMaterial ||
  17323. material.isMeshPhongMaterial ||
  17324. material.isMeshToonMaterial ||
  17325. material.isMeshStandardMaterial ||
  17326. material.envMap ) {
  17327. const uCamPos = p_uniforms.map.cameraPosition;
  17328. if ( uCamPos !== undefined ) {
  17329. uCamPos.setValue( _gl,
  17330. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17331. }
  17332. }
  17333. if ( material.isMeshPhongMaterial ||
  17334. material.isMeshToonMaterial ||
  17335. material.isMeshLambertMaterial ||
  17336. material.isMeshBasicMaterial ||
  17337. material.isMeshStandardMaterial ||
  17338. material.isShaderMaterial ) {
  17339. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17340. }
  17341. if ( material.isMeshPhongMaterial ||
  17342. material.isMeshToonMaterial ||
  17343. material.isMeshLambertMaterial ||
  17344. material.isMeshBasicMaterial ||
  17345. material.isMeshStandardMaterial ||
  17346. material.isShaderMaterial ||
  17347. material.isShadowMaterial ||
  17348. object.isSkinnedMesh ) {
  17349. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17350. }
  17351. }
  17352. // skinning and morph target uniforms must be set even if material didn't change
  17353. // auto-setting of texture unit for bone and morph texture must go before other textures
  17354. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17355. if ( object.isSkinnedMesh ) {
  17356. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17357. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17358. const skeleton = object.skeleton;
  17359. if ( skeleton ) {
  17360. if ( capabilities.floatVertexTextures ) {
  17361. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17362. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17363. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17364. } else {
  17365. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17366. }
  17367. }
  17368. }
  17369. const morphAttributes = geometry.morphAttributes;
  17370. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17371. morphtargets.update( object, geometry, program );
  17372. }
  17373. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17374. materialProperties.receiveShadow = object.receiveShadow;
  17375. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17376. }
  17377. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17378. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17379. m_uniforms.envMap.value = envMap;
  17380. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17381. }
  17382. if ( refreshMaterial ) {
  17383. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17384. if ( materialProperties.needsLights ) {
  17385. // the current material requires lighting info
  17386. // note: all lighting uniforms are always set correctly
  17387. // they simply reference the renderer's state for their
  17388. // values
  17389. //
  17390. // use the current material's .needsUpdate flags to set
  17391. // the GL state when required
  17392. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17393. }
  17394. // refresh uniforms common to several materials
  17395. if ( fog && material.fog === true ) {
  17396. materials.refreshFogUniforms( m_uniforms, fog );
  17397. }
  17398. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17399. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17400. }
  17401. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17402. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17403. material.uniformsNeedUpdate = false;
  17404. }
  17405. if ( material.isSpriteMaterial ) {
  17406. p_uniforms.setValue( _gl, 'center', object.center );
  17407. }
  17408. // common matrices
  17409. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17410. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17411. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17412. // UBOs
  17413. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17414. const groups = material.uniformsGroups;
  17415. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17416. if ( capabilities.isWebGL2 ) {
  17417. const group = groups[ i ];
  17418. uniformsGroups.update( group, program );
  17419. uniformsGroups.bind( group, program );
  17420. } else {
  17421. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17422. }
  17423. }
  17424. }
  17425. return program;
  17426. }
  17427. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17428. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17429. uniforms.ambientLightColor.needsUpdate = value;
  17430. uniforms.lightProbe.needsUpdate = value;
  17431. uniforms.directionalLights.needsUpdate = value;
  17432. uniforms.directionalLightShadows.needsUpdate = value;
  17433. uniforms.pointLights.needsUpdate = value;
  17434. uniforms.pointLightShadows.needsUpdate = value;
  17435. uniforms.spotLights.needsUpdate = value;
  17436. uniforms.spotLightShadows.needsUpdate = value;
  17437. uniforms.rectAreaLights.needsUpdate = value;
  17438. uniforms.hemisphereLights.needsUpdate = value;
  17439. }
  17440. function materialNeedsLights( material ) {
  17441. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17442. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17443. ( material.isShaderMaterial && material.lights === true );
  17444. }
  17445. this.getActiveCubeFace = function () {
  17446. return _currentActiveCubeFace;
  17447. };
  17448. this.getActiveMipmapLevel = function () {
  17449. return _currentActiveMipmapLevel;
  17450. };
  17451. this.getRenderTarget = function () {
  17452. return _currentRenderTarget;
  17453. };
  17454. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17455. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17456. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17457. const renderTargetProperties = properties.get( renderTarget );
  17458. renderTargetProperties.__hasExternalTextures = true;
  17459. if ( renderTargetProperties.__hasExternalTextures ) {
  17460. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17461. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17462. // The multisample_render_to_texture extension doesn't work properly if there
  17463. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17464. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17465. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17466. renderTargetProperties.__useRenderToTexture = false;
  17467. }
  17468. }
  17469. }
  17470. };
  17471. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17472. const renderTargetProperties = properties.get( renderTarget );
  17473. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17474. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17475. };
  17476. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17477. _currentRenderTarget = renderTarget;
  17478. _currentActiveCubeFace = activeCubeFace;
  17479. _currentActiveMipmapLevel = activeMipmapLevel;
  17480. let useDefaultFramebuffer = true;
  17481. let framebuffer = null;
  17482. let isCube = false;
  17483. let isRenderTarget3D = false;
  17484. if ( renderTarget ) {
  17485. const renderTargetProperties = properties.get( renderTarget );
  17486. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17487. // We need to make sure to rebind the framebuffer.
  17488. state.bindFramebuffer( 36160, null );
  17489. useDefaultFramebuffer = false;
  17490. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17491. textures.setupRenderTarget( renderTarget );
  17492. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17493. // Color and depth texture must be rebound in order for the swapchain to update.
  17494. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17495. }
  17496. const texture = renderTarget.texture;
  17497. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17498. isRenderTarget3D = true;
  17499. }
  17500. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17501. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17502. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17503. isCube = true;
  17504. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17505. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17506. } else {
  17507. framebuffer = __webglFramebuffer;
  17508. }
  17509. _currentViewport.copy( renderTarget.viewport );
  17510. _currentScissor.copy( renderTarget.scissor );
  17511. _currentScissorTest = renderTarget.scissorTest;
  17512. } else {
  17513. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17514. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17515. _currentScissorTest = _scissorTest;
  17516. }
  17517. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  17518. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17519. state.drawBuffers( renderTarget, framebuffer );
  17520. }
  17521. state.viewport( _currentViewport );
  17522. state.scissor( _currentScissor );
  17523. state.setScissorTest( _currentScissorTest );
  17524. if ( isCube ) {
  17525. const textureProperties = properties.get( renderTarget.texture );
  17526. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17527. } else if ( isRenderTarget3D ) {
  17528. const textureProperties = properties.get( renderTarget.texture );
  17529. const layer = activeCubeFace || 0;
  17530. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17531. }
  17532. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17533. };
  17534. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17535. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17536. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17537. return;
  17538. }
  17539. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17540. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17541. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17542. }
  17543. if ( framebuffer ) {
  17544. state.bindFramebuffer( 36160, framebuffer );
  17545. try {
  17546. const texture = renderTarget.texture;
  17547. const textureFormat = texture.format;
  17548. const textureType = texture.type;
  17549. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  17550. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17551. return;
  17552. }
  17553. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17554. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  17555. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17556. ! halfFloatSupportedByExt ) {
  17557. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17558. return;
  17559. }
  17560. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17561. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17562. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17563. }
  17564. } finally {
  17565. // restore framebuffer of current render target if necessary
  17566. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17567. state.bindFramebuffer( 36160, framebuffer );
  17568. }
  17569. }
  17570. };
  17571. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17572. const levelScale = Math.pow( 2, - level );
  17573. const width = Math.floor( texture.image.width * levelScale );
  17574. const height = Math.floor( texture.image.height * levelScale );
  17575. textures.setTexture2D( texture, 0 );
  17576. _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height );
  17577. state.unbindTexture();
  17578. };
  17579. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17580. const width = srcTexture.image.width;
  17581. const height = srcTexture.image.height;
  17582. const glFormat = utils.convert( dstTexture.format );
  17583. const glType = utils.convert( dstTexture.type );
  17584. textures.setTexture2D( dstTexture, 0 );
  17585. // As another texture upload may have changed pixelStorei
  17586. // parameters, make sure they are correct for the dstTexture
  17587. _gl.pixelStorei( 37440, dstTexture.flipY );
  17588. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17589. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17590. if ( srcTexture.isDataTexture ) {
  17591. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17592. } else {
  17593. if ( srcTexture.isCompressedTexture ) {
  17594. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17595. } else {
  17596. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17597. }
  17598. }
  17599. // Generate mipmaps only when copying level 0
  17600. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  17601. state.unbindTexture();
  17602. };
  17603. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17604. if ( _this.isWebGL1Renderer ) {
  17605. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17606. return;
  17607. }
  17608. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17609. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17610. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17611. const glFormat = utils.convert( dstTexture.format );
  17612. const glType = utils.convert( dstTexture.type );
  17613. let glTarget;
  17614. if ( dstTexture.isData3DTexture ) {
  17615. textures.setTexture3D( dstTexture, 0 );
  17616. glTarget = 32879;
  17617. } else if ( dstTexture.isDataArrayTexture ) {
  17618. textures.setTexture2DArray( dstTexture, 0 );
  17619. glTarget = 35866;
  17620. } else {
  17621. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17622. return;
  17623. }
  17624. _gl.pixelStorei( 37440, dstTexture.flipY );
  17625. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17626. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17627. const unpackRowLen = _gl.getParameter( 3314 );
  17628. const unpackImageHeight = _gl.getParameter( 32878 );
  17629. const unpackSkipPixels = _gl.getParameter( 3316 );
  17630. const unpackSkipRows = _gl.getParameter( 3315 );
  17631. const unpackSkipImages = _gl.getParameter( 32877 );
  17632. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17633. _gl.pixelStorei( 3314, image.width );
  17634. _gl.pixelStorei( 32878, image.height );
  17635. _gl.pixelStorei( 3316, sourceBox.min.x );
  17636. _gl.pixelStorei( 3315, sourceBox.min.y );
  17637. _gl.pixelStorei( 32877, sourceBox.min.z );
  17638. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17639. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17640. } else {
  17641. if ( srcTexture.isCompressedArrayTexture ) {
  17642. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17643. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17644. } else {
  17645. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17646. }
  17647. }
  17648. _gl.pixelStorei( 3314, unpackRowLen );
  17649. _gl.pixelStorei( 32878, unpackImageHeight );
  17650. _gl.pixelStorei( 3316, unpackSkipPixels );
  17651. _gl.pixelStorei( 3315, unpackSkipRows );
  17652. _gl.pixelStorei( 32877, unpackSkipImages );
  17653. // Generate mipmaps only when copying level 0
  17654. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17655. state.unbindTexture();
  17656. };
  17657. this.initTexture = function ( texture ) {
  17658. if ( texture.isCubeTexture ) {
  17659. textures.setTextureCube( texture, 0 );
  17660. } else if ( texture.isData3DTexture ) {
  17661. textures.setTexture3D( texture, 0 );
  17662. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17663. textures.setTexture2DArray( texture, 0 );
  17664. } else {
  17665. textures.setTexture2D( texture, 0 );
  17666. }
  17667. state.unbindTexture();
  17668. };
  17669. this.resetState = function () {
  17670. _currentActiveCubeFace = 0;
  17671. _currentActiveMipmapLevel = 0;
  17672. _currentRenderTarget = null;
  17673. state.reset();
  17674. bindingStates.reset();
  17675. };
  17676. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17677. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17678. }
  17679. }
  17680. get physicallyCorrectLights() { // @deprecated, r150
  17681. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17682. return ! this.useLegacyLights;
  17683. }
  17684. set physicallyCorrectLights( value ) { // @deprecated, r150
  17685. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17686. this.useLegacyLights = ! value;
  17687. }
  17688. }
  17689. class WebGL1Renderer extends WebGLRenderer {}
  17690. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17691. class FogExp2 {
  17692. constructor( color, density = 0.00025 ) {
  17693. this.isFogExp2 = true;
  17694. this.name = '';
  17695. this.color = new Color( color );
  17696. this.density = density;
  17697. }
  17698. clone() {
  17699. return new FogExp2( this.color, this.density );
  17700. }
  17701. toJSON( /* meta */ ) {
  17702. return {
  17703. type: 'FogExp2',
  17704. color: this.color.getHex(),
  17705. density: this.density
  17706. };
  17707. }
  17708. }
  17709. class Fog {
  17710. constructor( color, near = 1, far = 1000 ) {
  17711. this.isFog = true;
  17712. this.name = '';
  17713. this.color = new Color( color );
  17714. this.near = near;
  17715. this.far = far;
  17716. }
  17717. clone() {
  17718. return new Fog( this.color, this.near, this.far );
  17719. }
  17720. toJSON( /* meta */ ) {
  17721. return {
  17722. type: 'Fog',
  17723. color: this.color.getHex(),
  17724. near: this.near,
  17725. far: this.far
  17726. };
  17727. }
  17728. }
  17729. class Scene extends Object3D {
  17730. constructor() {
  17731. super();
  17732. this.isScene = true;
  17733. this.type = 'Scene';
  17734. this.background = null;
  17735. this.environment = null;
  17736. this.fog = null;
  17737. this.backgroundBlurriness = 0;
  17738. this.backgroundIntensity = 1;
  17739. this.overrideMaterial = null;
  17740. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17741. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17742. }
  17743. }
  17744. copy( source, recursive ) {
  17745. super.copy( source, recursive );
  17746. if ( source.background !== null ) this.background = source.background.clone();
  17747. if ( source.environment !== null ) this.environment = source.environment.clone();
  17748. if ( source.fog !== null ) this.fog = source.fog.clone();
  17749. this.backgroundBlurriness = source.backgroundBlurriness;
  17750. this.backgroundIntensity = source.backgroundIntensity;
  17751. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17752. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17753. return this;
  17754. }
  17755. toJSON( meta ) {
  17756. const data = super.toJSON( meta );
  17757. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17758. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17759. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17760. return data;
  17761. }
  17762. get autoUpdate() { // @deprecated, r144
  17763. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17764. return this.matrixWorldAutoUpdate;
  17765. }
  17766. set autoUpdate( value ) { // @deprecated, r144
  17767. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17768. this.matrixWorldAutoUpdate = value;
  17769. }
  17770. }
  17771. class InterleavedBuffer {
  17772. constructor( array, stride ) {
  17773. this.isInterleavedBuffer = true;
  17774. this.array = array;
  17775. this.stride = stride;
  17776. this.count = array !== undefined ? array.length / stride : 0;
  17777. this.usage = StaticDrawUsage;
  17778. this.updateRange = { offset: 0, count: - 1 };
  17779. this.version = 0;
  17780. this.uuid = generateUUID();
  17781. }
  17782. onUploadCallback() {}
  17783. set needsUpdate( value ) {
  17784. if ( value === true ) this.version ++;
  17785. }
  17786. setUsage( value ) {
  17787. this.usage = value;
  17788. return this;
  17789. }
  17790. copy( source ) {
  17791. this.array = new source.array.constructor( source.array );
  17792. this.count = source.count;
  17793. this.stride = source.stride;
  17794. this.usage = source.usage;
  17795. return this;
  17796. }
  17797. copyAt( index1, attribute, index2 ) {
  17798. index1 *= this.stride;
  17799. index2 *= attribute.stride;
  17800. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17801. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17802. }
  17803. return this;
  17804. }
  17805. set( value, offset = 0 ) {
  17806. this.array.set( value, offset );
  17807. return this;
  17808. }
  17809. clone( data ) {
  17810. if ( data.arrayBuffers === undefined ) {
  17811. data.arrayBuffers = {};
  17812. }
  17813. if ( this.array.buffer._uuid === undefined ) {
  17814. this.array.buffer._uuid = generateUUID();
  17815. }
  17816. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17817. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17818. }
  17819. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17820. const ib = new this.constructor( array, this.stride );
  17821. ib.setUsage( this.usage );
  17822. return ib;
  17823. }
  17824. onUpload( callback ) {
  17825. this.onUploadCallback = callback;
  17826. return this;
  17827. }
  17828. toJSON( data ) {
  17829. if ( data.arrayBuffers === undefined ) {
  17830. data.arrayBuffers = {};
  17831. }
  17832. // generate UUID for array buffer if necessary
  17833. if ( this.array.buffer._uuid === undefined ) {
  17834. this.array.buffer._uuid = generateUUID();
  17835. }
  17836. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17837. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17838. }
  17839. //
  17840. return {
  17841. uuid: this.uuid,
  17842. buffer: this.array.buffer._uuid,
  17843. type: this.array.constructor.name,
  17844. stride: this.stride
  17845. };
  17846. }
  17847. }
  17848. const _vector$5 = /*@__PURE__*/ new Vector3();
  17849. class InterleavedBufferAttribute {
  17850. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17851. this.isInterleavedBufferAttribute = true;
  17852. this.name = '';
  17853. this.data = interleavedBuffer;
  17854. this.itemSize = itemSize;
  17855. this.offset = offset;
  17856. this.normalized = normalized;
  17857. }
  17858. get count() {
  17859. return this.data.count;
  17860. }
  17861. get array() {
  17862. return this.data.array;
  17863. }
  17864. set needsUpdate( value ) {
  17865. this.data.needsUpdate = value;
  17866. }
  17867. applyMatrix4( m ) {
  17868. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17869. _vector$5.fromBufferAttribute( this, i );
  17870. _vector$5.applyMatrix4( m );
  17871. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  17872. }
  17873. return this;
  17874. }
  17875. applyNormalMatrix( m ) {
  17876. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17877. _vector$5.fromBufferAttribute( this, i );
  17878. _vector$5.applyNormalMatrix( m );
  17879. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  17880. }
  17881. return this;
  17882. }
  17883. transformDirection( m ) {
  17884. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17885. _vector$5.fromBufferAttribute( this, i );
  17886. _vector$5.transformDirection( m );
  17887. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  17888. }
  17889. return this;
  17890. }
  17891. setX( index, x ) {
  17892. if ( this.normalized ) x = normalize( x, this.array );
  17893. this.data.array[ index * this.data.stride + this.offset ] = x;
  17894. return this;
  17895. }
  17896. setY( index, y ) {
  17897. if ( this.normalized ) y = normalize( y, this.array );
  17898. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17899. return this;
  17900. }
  17901. setZ( index, z ) {
  17902. if ( this.normalized ) z = normalize( z, this.array );
  17903. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17904. return this;
  17905. }
  17906. setW( index, w ) {
  17907. if ( this.normalized ) w = normalize( w, this.array );
  17908. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17909. return this;
  17910. }
  17911. getX( index ) {
  17912. let x = this.data.array[ index * this.data.stride + this.offset ];
  17913. if ( this.normalized ) x = denormalize( x, this.array );
  17914. return x;
  17915. }
  17916. getY( index ) {
  17917. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17918. if ( this.normalized ) y = denormalize( y, this.array );
  17919. return y;
  17920. }
  17921. getZ( index ) {
  17922. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17923. if ( this.normalized ) z = denormalize( z, this.array );
  17924. return z;
  17925. }
  17926. getW( index ) {
  17927. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17928. if ( this.normalized ) w = denormalize( w, this.array );
  17929. return w;
  17930. }
  17931. setXY( index, x, y ) {
  17932. index = index * this.data.stride + this.offset;
  17933. if ( this.normalized ) {
  17934. x = normalize( x, this.array );
  17935. y = normalize( y, this.array );
  17936. }
  17937. this.data.array[ index + 0 ] = x;
  17938. this.data.array[ index + 1 ] = y;
  17939. return this;
  17940. }
  17941. setXYZ( index, x, y, z ) {
  17942. index = index * this.data.stride + this.offset;
  17943. if ( this.normalized ) {
  17944. x = normalize( x, this.array );
  17945. y = normalize( y, this.array );
  17946. z = normalize( z, this.array );
  17947. }
  17948. this.data.array[ index + 0 ] = x;
  17949. this.data.array[ index + 1 ] = y;
  17950. this.data.array[ index + 2 ] = z;
  17951. return this;
  17952. }
  17953. setXYZW( index, x, y, z, w ) {
  17954. index = index * this.data.stride + this.offset;
  17955. if ( this.normalized ) {
  17956. x = normalize( x, this.array );
  17957. y = normalize( y, this.array );
  17958. z = normalize( z, this.array );
  17959. w = normalize( w, this.array );
  17960. }
  17961. this.data.array[ index + 0 ] = x;
  17962. this.data.array[ index + 1 ] = y;
  17963. this.data.array[ index + 2 ] = z;
  17964. this.data.array[ index + 3 ] = w;
  17965. return this;
  17966. }
  17967. clone( data ) {
  17968. if ( data === undefined ) {
  17969. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17970. const array = [];
  17971. for ( let i = 0; i < this.count; i ++ ) {
  17972. const index = i * this.data.stride + this.offset;
  17973. for ( let j = 0; j < this.itemSize; j ++ ) {
  17974. array.push( this.data.array[ index + j ] );
  17975. }
  17976. }
  17977. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17978. } else {
  17979. if ( data.interleavedBuffers === undefined ) {
  17980. data.interleavedBuffers = {};
  17981. }
  17982. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17983. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17984. }
  17985. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17986. }
  17987. }
  17988. toJSON( data ) {
  17989. if ( data === undefined ) {
  17990. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17991. const array = [];
  17992. for ( let i = 0; i < this.count; i ++ ) {
  17993. const index = i * this.data.stride + this.offset;
  17994. for ( let j = 0; j < this.itemSize; j ++ ) {
  17995. array.push( this.data.array[ index + j ] );
  17996. }
  17997. }
  17998. // de-interleave data and save it as an ordinary buffer attribute for now
  17999. return {
  18000. itemSize: this.itemSize,
  18001. type: this.array.constructor.name,
  18002. array: array,
  18003. normalized: this.normalized
  18004. };
  18005. } else {
  18006. // save as true interleaved attribute
  18007. if ( data.interleavedBuffers === undefined ) {
  18008. data.interleavedBuffers = {};
  18009. }
  18010. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18011. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18012. }
  18013. return {
  18014. isInterleavedBufferAttribute: true,
  18015. itemSize: this.itemSize,
  18016. data: this.data.uuid,
  18017. offset: this.offset,
  18018. normalized: this.normalized
  18019. };
  18020. }
  18021. }
  18022. }
  18023. class SpriteMaterial extends Material {
  18024. constructor( parameters ) {
  18025. super();
  18026. this.isSpriteMaterial = true;
  18027. this.type = 'SpriteMaterial';
  18028. this.color = new Color( 0xffffff );
  18029. this.map = null;
  18030. this.alphaMap = null;
  18031. this.rotation = 0;
  18032. this.sizeAttenuation = true;
  18033. this.transparent = true;
  18034. this.fog = true;
  18035. this.setValues( parameters );
  18036. }
  18037. copy( source ) {
  18038. super.copy( source );
  18039. this.color.copy( source.color );
  18040. this.map = source.map;
  18041. this.alphaMap = source.alphaMap;
  18042. this.rotation = source.rotation;
  18043. this.sizeAttenuation = source.sizeAttenuation;
  18044. this.fog = source.fog;
  18045. return this;
  18046. }
  18047. }
  18048. let _geometry;
  18049. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18050. const _worldScale = /*@__PURE__*/ new Vector3();
  18051. const _mvPosition = /*@__PURE__*/ new Vector3();
  18052. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18053. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18054. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18055. const _vA = /*@__PURE__*/ new Vector3();
  18056. const _vB = /*@__PURE__*/ new Vector3();
  18057. const _vC = /*@__PURE__*/ new Vector3();
  18058. const _uvA = /*@__PURE__*/ new Vector2();
  18059. const _uvB = /*@__PURE__*/ new Vector2();
  18060. const _uvC = /*@__PURE__*/ new Vector2();
  18061. class Sprite extends Object3D {
  18062. constructor( material ) {
  18063. super();
  18064. this.isSprite = true;
  18065. this.type = 'Sprite';
  18066. if ( _geometry === undefined ) {
  18067. _geometry = new BufferGeometry();
  18068. const float32Array = new Float32Array( [
  18069. - 0.5, - 0.5, 0, 0, 0,
  18070. 0.5, - 0.5, 0, 1, 0,
  18071. 0.5, 0.5, 0, 1, 1,
  18072. - 0.5, 0.5, 0, 0, 1
  18073. ] );
  18074. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18075. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18076. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18077. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18078. }
  18079. this.geometry = _geometry;
  18080. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18081. this.center = new Vector2( 0.5, 0.5 );
  18082. }
  18083. raycast( raycaster, intersects ) {
  18084. if ( raycaster.camera === null ) {
  18085. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18086. }
  18087. _worldScale.setFromMatrixScale( this.matrixWorld );
  18088. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18089. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18090. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18091. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18092. _worldScale.multiplyScalar( - _mvPosition.z );
  18093. }
  18094. const rotation = this.material.rotation;
  18095. let sin, cos;
  18096. if ( rotation !== 0 ) {
  18097. cos = Math.cos( rotation );
  18098. sin = Math.sin( rotation );
  18099. }
  18100. const center = this.center;
  18101. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18102. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18103. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18104. _uvA.set( 0, 0 );
  18105. _uvB.set( 1, 0 );
  18106. _uvC.set( 1, 1 );
  18107. // check first triangle
  18108. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18109. if ( intersect === null ) {
  18110. // check second triangle
  18111. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18112. _uvB.set( 0, 1 );
  18113. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18114. if ( intersect === null ) {
  18115. return;
  18116. }
  18117. }
  18118. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18119. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18120. intersects.push( {
  18121. distance: distance,
  18122. point: _intersectPoint.clone(),
  18123. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18124. face: null,
  18125. object: this
  18126. } );
  18127. }
  18128. copy( source, recursive ) {
  18129. super.copy( source, recursive );
  18130. if ( source.center !== undefined ) this.center.copy( source.center );
  18131. this.material = source.material;
  18132. return this;
  18133. }
  18134. }
  18135. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18136. // compute position in camera space
  18137. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18138. // to check if rotation is not zero
  18139. if ( sin !== undefined ) {
  18140. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18141. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18142. } else {
  18143. _rotatedPosition.copy( _alignedPosition );
  18144. }
  18145. vertexPosition.copy( mvPosition );
  18146. vertexPosition.x += _rotatedPosition.x;
  18147. vertexPosition.y += _rotatedPosition.y;
  18148. // transform to world space
  18149. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18150. }
  18151. const _v1$2 = /*@__PURE__*/ new Vector3();
  18152. const _v2$1 = /*@__PURE__*/ new Vector3();
  18153. class LOD extends Object3D {
  18154. constructor() {
  18155. super();
  18156. this._currentLevel = 0;
  18157. this.type = 'LOD';
  18158. Object.defineProperties( this, {
  18159. levels: {
  18160. enumerable: true,
  18161. value: []
  18162. },
  18163. isLOD: {
  18164. value: true,
  18165. }
  18166. } );
  18167. this.autoUpdate = true;
  18168. }
  18169. copy( source ) {
  18170. super.copy( source, false );
  18171. const levels = source.levels;
  18172. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18173. const level = levels[ i ];
  18174. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18175. }
  18176. this.autoUpdate = source.autoUpdate;
  18177. return this;
  18178. }
  18179. addLevel( object, distance = 0, hysteresis = 0 ) {
  18180. distance = Math.abs( distance );
  18181. const levels = this.levels;
  18182. let l;
  18183. for ( l = 0; l < levels.length; l ++ ) {
  18184. if ( distance < levels[ l ].distance ) {
  18185. break;
  18186. }
  18187. }
  18188. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18189. this.add( object );
  18190. return this;
  18191. }
  18192. getCurrentLevel() {
  18193. return this._currentLevel;
  18194. }
  18195. getObjectForDistance( distance ) {
  18196. const levels = this.levels;
  18197. if ( levels.length > 0 ) {
  18198. let i, l;
  18199. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18200. let levelDistance = levels[ i ].distance;
  18201. if ( levels[ i ].object.visible ) {
  18202. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18203. }
  18204. if ( distance < levelDistance ) {
  18205. break;
  18206. }
  18207. }
  18208. return levels[ i - 1 ].object;
  18209. }
  18210. return null;
  18211. }
  18212. raycast( raycaster, intersects ) {
  18213. const levels = this.levels;
  18214. if ( levels.length > 0 ) {
  18215. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18216. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18217. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18218. }
  18219. }
  18220. update( camera ) {
  18221. const levels = this.levels;
  18222. if ( levels.length > 1 ) {
  18223. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18224. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18225. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18226. levels[ 0 ].object.visible = true;
  18227. let i, l;
  18228. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18229. let levelDistance = levels[ i ].distance;
  18230. if ( levels[ i ].object.visible ) {
  18231. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18232. }
  18233. if ( distance >= levelDistance ) {
  18234. levels[ i - 1 ].object.visible = false;
  18235. levels[ i ].object.visible = true;
  18236. } else {
  18237. break;
  18238. }
  18239. }
  18240. this._currentLevel = i - 1;
  18241. for ( ; i < l; i ++ ) {
  18242. levels[ i ].object.visible = false;
  18243. }
  18244. }
  18245. }
  18246. toJSON( meta ) {
  18247. const data = super.toJSON( meta );
  18248. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18249. data.object.levels = [];
  18250. const levels = this.levels;
  18251. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18252. const level = levels[ i ];
  18253. data.object.levels.push( {
  18254. object: level.object.uuid,
  18255. distance: level.distance,
  18256. hysteresis: level.hysteresis
  18257. } );
  18258. }
  18259. return data;
  18260. }
  18261. }
  18262. const _basePosition = /*@__PURE__*/ new Vector3();
  18263. const _skinIndex = /*@__PURE__*/ new Vector4();
  18264. const _skinWeight = /*@__PURE__*/ new Vector4();
  18265. const _vector3 = /*@__PURE__*/ new Vector3();
  18266. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18267. const _vertex = /*@__PURE__*/ new Vector3();
  18268. class SkinnedMesh extends Mesh {
  18269. constructor( geometry, material ) {
  18270. super( geometry, material );
  18271. this.isSkinnedMesh = true;
  18272. this.type = 'SkinnedMesh';
  18273. this.bindMode = 'attached';
  18274. this.bindMatrix = new Matrix4();
  18275. this.bindMatrixInverse = new Matrix4();
  18276. this.boundingBox = null;
  18277. this.boundingSphere = null;
  18278. }
  18279. computeBoundingBox() {
  18280. const geometry = this.geometry;
  18281. if ( this.boundingBox === null ) {
  18282. this.boundingBox = new Box3();
  18283. }
  18284. this.boundingBox.makeEmpty();
  18285. const positionAttribute = geometry.getAttribute( 'position' );
  18286. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18287. _vertex.fromBufferAttribute( positionAttribute, i );
  18288. this.applyBoneTransform( i, _vertex );
  18289. this.boundingBox.expandByPoint( _vertex );
  18290. }
  18291. }
  18292. computeBoundingSphere() {
  18293. const geometry = this.geometry;
  18294. if ( this.boundingSphere === null ) {
  18295. this.boundingSphere = new Sphere();
  18296. }
  18297. this.boundingSphere.makeEmpty();
  18298. const positionAttribute = geometry.getAttribute( 'position' );
  18299. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18300. _vertex.fromBufferAttribute( positionAttribute, i );
  18301. this.applyBoneTransform( i, _vertex );
  18302. this.boundingSphere.expandByPoint( _vertex );
  18303. }
  18304. }
  18305. copy( source, recursive ) {
  18306. super.copy( source, recursive );
  18307. this.bindMode = source.bindMode;
  18308. this.bindMatrix.copy( source.bindMatrix );
  18309. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18310. this.skeleton = source.skeleton;
  18311. return this;
  18312. }
  18313. bind( skeleton, bindMatrix ) {
  18314. this.skeleton = skeleton;
  18315. if ( bindMatrix === undefined ) {
  18316. this.updateMatrixWorld( true );
  18317. this.skeleton.calculateInverses();
  18318. bindMatrix = this.matrixWorld;
  18319. }
  18320. this.bindMatrix.copy( bindMatrix );
  18321. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18322. }
  18323. pose() {
  18324. this.skeleton.pose();
  18325. }
  18326. normalizeSkinWeights() {
  18327. const vector = new Vector4();
  18328. const skinWeight = this.geometry.attributes.skinWeight;
  18329. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18330. vector.fromBufferAttribute( skinWeight, i );
  18331. const scale = 1.0 / vector.manhattanLength();
  18332. if ( scale !== Infinity ) {
  18333. vector.multiplyScalar( scale );
  18334. } else {
  18335. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18336. }
  18337. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18338. }
  18339. }
  18340. updateMatrixWorld( force ) {
  18341. super.updateMatrixWorld( force );
  18342. if ( this.bindMode === 'attached' ) {
  18343. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18344. } else if ( this.bindMode === 'detached' ) {
  18345. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18346. } else {
  18347. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18348. }
  18349. }
  18350. applyBoneTransform( index, vector ) {
  18351. const skeleton = this.skeleton;
  18352. const geometry = this.geometry;
  18353. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18354. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18355. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  18356. vector.set( 0, 0, 0 );
  18357. for ( let i = 0; i < 4; i ++ ) {
  18358. const weight = _skinWeight.getComponent( i );
  18359. if ( weight !== 0 ) {
  18360. const boneIndex = _skinIndex.getComponent( i );
  18361. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18362. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18363. }
  18364. }
  18365. return vector.applyMatrix4( this.bindMatrixInverse );
  18366. }
  18367. boneTransform( index, vector ) { // @deprecated, r151
  18368. console.warn( 'THREE.SkinnedMesh: .boneTransform() was renamed to .applyBoneTransform() in r151.' );
  18369. return this.applyBoneTransform( index, vector );
  18370. }
  18371. }
  18372. class Bone extends Object3D {
  18373. constructor() {
  18374. super();
  18375. this.isBone = true;
  18376. this.type = 'Bone';
  18377. }
  18378. }
  18379. class DataTexture extends Texture {
  18380. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  18381. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18382. this.isDataTexture = true;
  18383. this.image = { data: data, width: width, height: height };
  18384. this.generateMipmaps = false;
  18385. this.flipY = false;
  18386. this.unpackAlignment = 1;
  18387. }
  18388. }
  18389. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18390. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18391. class Skeleton {
  18392. constructor( bones = [], boneInverses = [] ) {
  18393. this.uuid = generateUUID();
  18394. this.bones = bones.slice( 0 );
  18395. this.boneInverses = boneInverses;
  18396. this.boneMatrices = null;
  18397. this.boneTexture = null;
  18398. this.boneTextureSize = 0;
  18399. this.frame = - 1;
  18400. this.init();
  18401. }
  18402. init() {
  18403. const bones = this.bones;
  18404. const boneInverses = this.boneInverses;
  18405. this.boneMatrices = new Float32Array( bones.length * 16 );
  18406. // calculate inverse bone matrices if necessary
  18407. if ( boneInverses.length === 0 ) {
  18408. this.calculateInverses();
  18409. } else {
  18410. // handle special case
  18411. if ( bones.length !== boneInverses.length ) {
  18412. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18413. this.boneInverses = [];
  18414. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18415. this.boneInverses.push( new Matrix4() );
  18416. }
  18417. }
  18418. }
  18419. }
  18420. calculateInverses() {
  18421. this.boneInverses.length = 0;
  18422. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18423. const inverse = new Matrix4();
  18424. if ( this.bones[ i ] ) {
  18425. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18426. }
  18427. this.boneInverses.push( inverse );
  18428. }
  18429. }
  18430. pose() {
  18431. // recover the bind-time world matrices
  18432. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18433. const bone = this.bones[ i ];
  18434. if ( bone ) {
  18435. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18436. }
  18437. }
  18438. // compute the local matrices, positions, rotations and scales
  18439. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18440. const bone = this.bones[ i ];
  18441. if ( bone ) {
  18442. if ( bone.parent && bone.parent.isBone ) {
  18443. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18444. bone.matrix.multiply( bone.matrixWorld );
  18445. } else {
  18446. bone.matrix.copy( bone.matrixWorld );
  18447. }
  18448. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18449. }
  18450. }
  18451. }
  18452. update() {
  18453. const bones = this.bones;
  18454. const boneInverses = this.boneInverses;
  18455. const boneMatrices = this.boneMatrices;
  18456. const boneTexture = this.boneTexture;
  18457. // flatten bone matrices to array
  18458. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18459. // compute the offset between the current and the original transform
  18460. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18461. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18462. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18463. }
  18464. if ( boneTexture !== null ) {
  18465. boneTexture.needsUpdate = true;
  18466. }
  18467. }
  18468. clone() {
  18469. return new Skeleton( this.bones, this.boneInverses );
  18470. }
  18471. computeBoneTexture() {
  18472. // layout (1 matrix = 4 pixels)
  18473. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18474. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18475. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18476. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18477. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18478. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18479. size = ceilPowerOfTwo( size );
  18480. size = Math.max( size, 4 );
  18481. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18482. boneMatrices.set( this.boneMatrices ); // copy current values
  18483. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18484. boneTexture.needsUpdate = true;
  18485. this.boneMatrices = boneMatrices;
  18486. this.boneTexture = boneTexture;
  18487. this.boneTextureSize = size;
  18488. return this;
  18489. }
  18490. getBoneByName( name ) {
  18491. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18492. const bone = this.bones[ i ];
  18493. if ( bone.name === name ) {
  18494. return bone;
  18495. }
  18496. }
  18497. return undefined;
  18498. }
  18499. dispose( ) {
  18500. if ( this.boneTexture !== null ) {
  18501. this.boneTexture.dispose();
  18502. this.boneTexture = null;
  18503. }
  18504. }
  18505. fromJSON( json, bones ) {
  18506. this.uuid = json.uuid;
  18507. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18508. const uuid = json.bones[ i ];
  18509. let bone = bones[ uuid ];
  18510. if ( bone === undefined ) {
  18511. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18512. bone = new Bone();
  18513. }
  18514. this.bones.push( bone );
  18515. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18516. }
  18517. this.init();
  18518. return this;
  18519. }
  18520. toJSON() {
  18521. const data = {
  18522. metadata: {
  18523. version: 4.5,
  18524. type: 'Skeleton',
  18525. generator: 'Skeleton.toJSON'
  18526. },
  18527. bones: [],
  18528. boneInverses: []
  18529. };
  18530. data.uuid = this.uuid;
  18531. const bones = this.bones;
  18532. const boneInverses = this.boneInverses;
  18533. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18534. const bone = bones[ i ];
  18535. data.bones.push( bone.uuid );
  18536. const boneInverse = boneInverses[ i ];
  18537. data.boneInverses.push( boneInverse.toArray() );
  18538. }
  18539. return data;
  18540. }
  18541. }
  18542. class InstancedBufferAttribute extends BufferAttribute {
  18543. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18544. super( array, itemSize, normalized );
  18545. this.isInstancedBufferAttribute = true;
  18546. this.meshPerAttribute = meshPerAttribute;
  18547. }
  18548. copy( source ) {
  18549. super.copy( source );
  18550. this.meshPerAttribute = source.meshPerAttribute;
  18551. return this;
  18552. }
  18553. toJSON() {
  18554. const data = super.toJSON();
  18555. data.meshPerAttribute = this.meshPerAttribute;
  18556. data.isInstancedBufferAttribute = true;
  18557. return data;
  18558. }
  18559. }
  18560. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18561. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18562. const _instanceIntersects = [];
  18563. const _box3 = /*@__PURE__*/ new Box3();
  18564. const _identity = /*@__PURE__*/ new Matrix4();
  18565. const _mesh = /*@__PURE__*/ new Mesh();
  18566. const _sphere$2 = /*@__PURE__*/ new Sphere();
  18567. class InstancedMesh extends Mesh {
  18568. constructor( geometry, material, count ) {
  18569. super( geometry, material );
  18570. this.isInstancedMesh = true;
  18571. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18572. this.instanceColor = null;
  18573. this.count = count;
  18574. this.boundingBox = null;
  18575. this.boundingSphere = null;
  18576. for ( let i = 0; i < count; i ++ ) {
  18577. this.setMatrixAt( i, _identity );
  18578. }
  18579. }
  18580. computeBoundingBox() {
  18581. const geometry = this.geometry;
  18582. const count = this.count;
  18583. if ( this.boundingBox === null ) {
  18584. this.boundingBox = new Box3();
  18585. }
  18586. if ( geometry.boundingBox === null ) {
  18587. geometry.computeBoundingBox();
  18588. }
  18589. this.boundingBox.makeEmpty();
  18590. for ( let i = 0; i < count; i ++ ) {
  18591. this.getMatrixAt( i, _instanceLocalMatrix );
  18592. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18593. this.boundingBox.union( _box3 );
  18594. }
  18595. }
  18596. computeBoundingSphere() {
  18597. const geometry = this.geometry;
  18598. const count = this.count;
  18599. if ( this.boundingSphere === null ) {
  18600. this.boundingSphere = new Sphere();
  18601. }
  18602. if ( geometry.boundingSphere === null ) {
  18603. geometry.computeBoundingSphere();
  18604. }
  18605. this.boundingSphere.makeEmpty();
  18606. for ( let i = 0; i < count; i ++ ) {
  18607. this.getMatrixAt( i, _instanceLocalMatrix );
  18608. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18609. this.boundingSphere.union( _sphere$2 );
  18610. }
  18611. }
  18612. copy( source, recursive ) {
  18613. super.copy( source, recursive );
  18614. this.instanceMatrix.copy( source.instanceMatrix );
  18615. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18616. this.count = source.count;
  18617. return this;
  18618. }
  18619. getColorAt( index, color ) {
  18620. color.fromArray( this.instanceColor.array, index * 3 );
  18621. }
  18622. getMatrixAt( index, matrix ) {
  18623. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18624. }
  18625. raycast( raycaster, intersects ) {
  18626. const matrixWorld = this.matrixWorld;
  18627. const raycastTimes = this.count;
  18628. _mesh.geometry = this.geometry;
  18629. _mesh.material = this.material;
  18630. if ( _mesh.material === undefined ) return;
  18631. // test with bounding sphere first
  18632. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18633. _sphere$2.copy( this.boundingSphere );
  18634. _sphere$2.applyMatrix4( matrixWorld );
  18635. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
  18636. // now test each instance
  18637. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18638. // calculate the world matrix for each instance
  18639. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18640. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18641. // the mesh represents this single instance
  18642. _mesh.matrixWorld = _instanceWorldMatrix;
  18643. _mesh.raycast( raycaster, _instanceIntersects );
  18644. // process the result of raycast
  18645. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18646. const intersect = _instanceIntersects[ i ];
  18647. intersect.instanceId = instanceId;
  18648. intersect.object = this;
  18649. intersects.push( intersect );
  18650. }
  18651. _instanceIntersects.length = 0;
  18652. }
  18653. }
  18654. setColorAt( index, color ) {
  18655. if ( this.instanceColor === null ) {
  18656. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18657. }
  18658. color.toArray( this.instanceColor.array, index * 3 );
  18659. }
  18660. setMatrixAt( index, matrix ) {
  18661. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18662. }
  18663. updateMorphTargets() {
  18664. }
  18665. dispose() {
  18666. this.dispatchEvent( { type: 'dispose' } );
  18667. }
  18668. }
  18669. class LineBasicMaterial extends Material {
  18670. constructor( parameters ) {
  18671. super();
  18672. this.isLineBasicMaterial = true;
  18673. this.type = 'LineBasicMaterial';
  18674. this.color = new Color( 0xffffff );
  18675. this.map = null;
  18676. this.linewidth = 1;
  18677. this.linecap = 'round';
  18678. this.linejoin = 'round';
  18679. this.fog = true;
  18680. this.setValues( parameters );
  18681. }
  18682. copy( source ) {
  18683. super.copy( source );
  18684. this.color.copy( source.color );
  18685. this.map = source.map;
  18686. this.linewidth = source.linewidth;
  18687. this.linecap = source.linecap;
  18688. this.linejoin = source.linejoin;
  18689. this.fog = source.fog;
  18690. return this;
  18691. }
  18692. }
  18693. const _start$1 = /*@__PURE__*/ new Vector3();
  18694. const _end$1 = /*@__PURE__*/ new Vector3();
  18695. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18696. const _ray$1 = /*@__PURE__*/ new Ray();
  18697. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18698. class Line extends Object3D {
  18699. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18700. super();
  18701. this.isLine = true;
  18702. this.type = 'Line';
  18703. this.geometry = geometry;
  18704. this.material = material;
  18705. this.updateMorphTargets();
  18706. }
  18707. copy( source, recursive ) {
  18708. super.copy( source, recursive );
  18709. this.material = source.material;
  18710. this.geometry = source.geometry;
  18711. return this;
  18712. }
  18713. computeLineDistances() {
  18714. const geometry = this.geometry;
  18715. // we assume non-indexed geometry
  18716. if ( geometry.index === null ) {
  18717. const positionAttribute = geometry.attributes.position;
  18718. const lineDistances = [ 0 ];
  18719. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18720. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18721. _end$1.fromBufferAttribute( positionAttribute, i );
  18722. lineDistances[ i ] = lineDistances[ i - 1 ];
  18723. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18724. }
  18725. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18726. } else {
  18727. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18728. }
  18729. return this;
  18730. }
  18731. raycast( raycaster, intersects ) {
  18732. const geometry = this.geometry;
  18733. const matrixWorld = this.matrixWorld;
  18734. const threshold = raycaster.params.Line.threshold;
  18735. const drawRange = geometry.drawRange;
  18736. // Checking boundingSphere distance to ray
  18737. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18738. _sphere$1.copy( geometry.boundingSphere );
  18739. _sphere$1.applyMatrix4( matrixWorld );
  18740. _sphere$1.radius += threshold;
  18741. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18742. //
  18743. _inverseMatrix$1.copy( matrixWorld ).invert();
  18744. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18745. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18746. const localThresholdSq = localThreshold * localThreshold;
  18747. const vStart = new Vector3();
  18748. const vEnd = new Vector3();
  18749. const interSegment = new Vector3();
  18750. const interRay = new Vector3();
  18751. const step = this.isLineSegments ? 2 : 1;
  18752. const index = geometry.index;
  18753. const attributes = geometry.attributes;
  18754. const positionAttribute = attributes.position;
  18755. if ( index !== null ) {
  18756. const start = Math.max( 0, drawRange.start );
  18757. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18758. for ( let i = start, l = end - 1; i < l; i += step ) {
  18759. const a = index.getX( i );
  18760. const b = index.getX( i + 1 );
  18761. vStart.fromBufferAttribute( positionAttribute, a );
  18762. vEnd.fromBufferAttribute( positionAttribute, b );
  18763. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18764. if ( distSq > localThresholdSq ) continue;
  18765. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18766. const distance = raycaster.ray.origin.distanceTo( interRay );
  18767. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18768. intersects.push( {
  18769. distance: distance,
  18770. // What do we want? intersection point on the ray or on the segment??
  18771. // point: raycaster.ray.at( distance ),
  18772. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18773. index: i,
  18774. face: null,
  18775. faceIndex: null,
  18776. object: this
  18777. } );
  18778. }
  18779. } else {
  18780. const start = Math.max( 0, drawRange.start );
  18781. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18782. for ( let i = start, l = end - 1; i < l; i += step ) {
  18783. vStart.fromBufferAttribute( positionAttribute, i );
  18784. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18785. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18786. if ( distSq > localThresholdSq ) continue;
  18787. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18788. const distance = raycaster.ray.origin.distanceTo( interRay );
  18789. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18790. intersects.push( {
  18791. distance: distance,
  18792. // What do we want? intersection point on the ray or on the segment??
  18793. // point: raycaster.ray.at( distance ),
  18794. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18795. index: i,
  18796. face: null,
  18797. faceIndex: null,
  18798. object: this
  18799. } );
  18800. }
  18801. }
  18802. }
  18803. updateMorphTargets() {
  18804. const geometry = this.geometry;
  18805. const morphAttributes = geometry.morphAttributes;
  18806. const keys = Object.keys( morphAttributes );
  18807. if ( keys.length > 0 ) {
  18808. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18809. if ( morphAttribute !== undefined ) {
  18810. this.morphTargetInfluences = [];
  18811. this.morphTargetDictionary = {};
  18812. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18813. const name = morphAttribute[ m ].name || String( m );
  18814. this.morphTargetInfluences.push( 0 );
  18815. this.morphTargetDictionary[ name ] = m;
  18816. }
  18817. }
  18818. }
  18819. }
  18820. }
  18821. const _start = /*@__PURE__*/ new Vector3();
  18822. const _end = /*@__PURE__*/ new Vector3();
  18823. class LineSegments extends Line {
  18824. constructor( geometry, material ) {
  18825. super( geometry, material );
  18826. this.isLineSegments = true;
  18827. this.type = 'LineSegments';
  18828. }
  18829. computeLineDistances() {
  18830. const geometry = this.geometry;
  18831. // we assume non-indexed geometry
  18832. if ( geometry.index === null ) {
  18833. const positionAttribute = geometry.attributes.position;
  18834. const lineDistances = [];
  18835. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18836. _start.fromBufferAttribute( positionAttribute, i );
  18837. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18838. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18839. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18840. }
  18841. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18842. } else {
  18843. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18844. }
  18845. return this;
  18846. }
  18847. }
  18848. class LineLoop extends Line {
  18849. constructor( geometry, material ) {
  18850. super( geometry, material );
  18851. this.isLineLoop = true;
  18852. this.type = 'LineLoop';
  18853. }
  18854. }
  18855. class PointsMaterial extends Material {
  18856. constructor( parameters ) {
  18857. super();
  18858. this.isPointsMaterial = true;
  18859. this.type = 'PointsMaterial';
  18860. this.color = new Color( 0xffffff );
  18861. this.map = null;
  18862. this.alphaMap = null;
  18863. this.size = 1;
  18864. this.sizeAttenuation = true;
  18865. this.fog = true;
  18866. this.setValues( parameters );
  18867. }
  18868. copy( source ) {
  18869. super.copy( source );
  18870. this.color.copy( source.color );
  18871. this.map = source.map;
  18872. this.alphaMap = source.alphaMap;
  18873. this.size = source.size;
  18874. this.sizeAttenuation = source.sizeAttenuation;
  18875. this.fog = source.fog;
  18876. return this;
  18877. }
  18878. }
  18879. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18880. const _ray = /*@__PURE__*/ new Ray();
  18881. const _sphere = /*@__PURE__*/ new Sphere();
  18882. const _position$2 = /*@__PURE__*/ new Vector3();
  18883. class Points extends Object3D {
  18884. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18885. super();
  18886. this.isPoints = true;
  18887. this.type = 'Points';
  18888. this.geometry = geometry;
  18889. this.material = material;
  18890. this.updateMorphTargets();
  18891. }
  18892. copy( source, recursive ) {
  18893. super.copy( source, recursive );
  18894. this.material = source.material;
  18895. this.geometry = source.geometry;
  18896. return this;
  18897. }
  18898. raycast( raycaster, intersects ) {
  18899. const geometry = this.geometry;
  18900. const matrixWorld = this.matrixWorld;
  18901. const threshold = raycaster.params.Points.threshold;
  18902. const drawRange = geometry.drawRange;
  18903. // Checking boundingSphere distance to ray
  18904. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18905. _sphere.copy( geometry.boundingSphere );
  18906. _sphere.applyMatrix4( matrixWorld );
  18907. _sphere.radius += threshold;
  18908. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18909. //
  18910. _inverseMatrix.copy( matrixWorld ).invert();
  18911. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18912. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18913. const localThresholdSq = localThreshold * localThreshold;
  18914. const index = geometry.index;
  18915. const attributes = geometry.attributes;
  18916. const positionAttribute = attributes.position;
  18917. if ( index !== null ) {
  18918. const start = Math.max( 0, drawRange.start );
  18919. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18920. for ( let i = start, il = end; i < il; i ++ ) {
  18921. const a = index.getX( i );
  18922. _position$2.fromBufferAttribute( positionAttribute, a );
  18923. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18924. }
  18925. } else {
  18926. const start = Math.max( 0, drawRange.start );
  18927. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18928. for ( let i = start, l = end; i < l; i ++ ) {
  18929. _position$2.fromBufferAttribute( positionAttribute, i );
  18930. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18931. }
  18932. }
  18933. }
  18934. updateMorphTargets() {
  18935. const geometry = this.geometry;
  18936. const morphAttributes = geometry.morphAttributes;
  18937. const keys = Object.keys( morphAttributes );
  18938. if ( keys.length > 0 ) {
  18939. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18940. if ( morphAttribute !== undefined ) {
  18941. this.morphTargetInfluences = [];
  18942. this.morphTargetDictionary = {};
  18943. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18944. const name = morphAttribute[ m ].name || String( m );
  18945. this.morphTargetInfluences.push( 0 );
  18946. this.morphTargetDictionary[ name ] = m;
  18947. }
  18948. }
  18949. }
  18950. }
  18951. }
  18952. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18953. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18954. if ( rayPointDistanceSq < localThresholdSq ) {
  18955. const intersectPoint = new Vector3();
  18956. _ray.closestPointToPoint( point, intersectPoint );
  18957. intersectPoint.applyMatrix4( matrixWorld );
  18958. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18959. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18960. intersects.push( {
  18961. distance: distance,
  18962. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18963. point: intersectPoint,
  18964. index: index,
  18965. face: null,
  18966. object: object
  18967. } );
  18968. }
  18969. }
  18970. class VideoTexture extends Texture {
  18971. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18972. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18973. this.isVideoTexture = true;
  18974. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18975. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18976. this.generateMipmaps = false;
  18977. const scope = this;
  18978. function updateVideo() {
  18979. scope.needsUpdate = true;
  18980. video.requestVideoFrameCallback( updateVideo );
  18981. }
  18982. if ( 'requestVideoFrameCallback' in video ) {
  18983. video.requestVideoFrameCallback( updateVideo );
  18984. }
  18985. }
  18986. clone() {
  18987. return new this.constructor( this.image ).copy( this );
  18988. }
  18989. update() {
  18990. const video = this.image;
  18991. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18992. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18993. this.needsUpdate = true;
  18994. }
  18995. }
  18996. }
  18997. class FramebufferTexture extends Texture {
  18998. constructor( width, height, format ) {
  18999. super( { width, height } );
  19000. this.isFramebufferTexture = true;
  19001. this.format = format;
  19002. this.magFilter = NearestFilter;
  19003. this.minFilter = NearestFilter;
  19004. this.generateMipmaps = false;
  19005. this.needsUpdate = true;
  19006. }
  19007. }
  19008. class CompressedTexture extends Texture {
  19009. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  19010. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  19011. this.isCompressedTexture = true;
  19012. this.image = { width: width, height: height };
  19013. this.mipmaps = mipmaps;
  19014. // no flipping for cube textures
  19015. // (also flipping doesn't work for compressed textures )
  19016. this.flipY = false;
  19017. // can't generate mipmaps for compressed textures
  19018. // mips must be embedded in DDS files
  19019. this.generateMipmaps = false;
  19020. }
  19021. }
  19022. class CompressedArrayTexture extends CompressedTexture {
  19023. constructor( mipmaps, width, height, depth, format, type ) {
  19024. super( mipmaps, width, height, format, type );
  19025. this.isCompressedArrayTexture = true;
  19026. this.image.depth = depth;
  19027. this.wrapR = ClampToEdgeWrapping;
  19028. }
  19029. }
  19030. class CanvasTexture extends Texture {
  19031. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19032. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19033. this.isCanvasTexture = true;
  19034. this.needsUpdate = true;
  19035. }
  19036. }
  19037. /**
  19038. * Extensible curve object.
  19039. *
  19040. * Some common of curve methods:
  19041. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  19042. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  19043. * .getPoints(), .getSpacedPoints()
  19044. * .getLength()
  19045. * .updateArcLengths()
  19046. *
  19047. * This following curves inherit from THREE.Curve:
  19048. *
  19049. * -- 2D curves --
  19050. * THREE.ArcCurve
  19051. * THREE.CubicBezierCurve
  19052. * THREE.EllipseCurve
  19053. * THREE.LineCurve
  19054. * THREE.QuadraticBezierCurve
  19055. * THREE.SplineCurve
  19056. *
  19057. * -- 3D curves --
  19058. * THREE.CatmullRomCurve3
  19059. * THREE.CubicBezierCurve3
  19060. * THREE.LineCurve3
  19061. * THREE.QuadraticBezierCurve3
  19062. *
  19063. * A series of curves can be represented as a THREE.CurvePath.
  19064. *
  19065. **/
  19066. class Curve {
  19067. constructor() {
  19068. this.type = 'Curve';
  19069. this.arcLengthDivisions = 200;
  19070. }
  19071. // Virtual base class method to overwrite and implement in subclasses
  19072. // - t [0 .. 1]
  19073. getPoint( /* t, optionalTarget */ ) {
  19074. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  19075. return null;
  19076. }
  19077. // Get point at relative position in curve according to arc length
  19078. // - u [0 .. 1]
  19079. getPointAt( u, optionalTarget ) {
  19080. const t = this.getUtoTmapping( u );
  19081. return this.getPoint( t, optionalTarget );
  19082. }
  19083. // Get sequence of points using getPoint( t )
  19084. getPoints( divisions = 5 ) {
  19085. const points = [];
  19086. for ( let d = 0; d <= divisions; d ++ ) {
  19087. points.push( this.getPoint( d / divisions ) );
  19088. }
  19089. return points;
  19090. }
  19091. // Get sequence of points using getPointAt( u )
  19092. getSpacedPoints( divisions = 5 ) {
  19093. const points = [];
  19094. for ( let d = 0; d <= divisions; d ++ ) {
  19095. points.push( this.getPointAt( d / divisions ) );
  19096. }
  19097. return points;
  19098. }
  19099. // Get total curve arc length
  19100. getLength() {
  19101. const lengths = this.getLengths();
  19102. return lengths[ lengths.length - 1 ];
  19103. }
  19104. // Get list of cumulative segment lengths
  19105. getLengths( divisions = this.arcLengthDivisions ) {
  19106. if ( this.cacheArcLengths &&
  19107. ( this.cacheArcLengths.length === divisions + 1 ) &&
  19108. ! this.needsUpdate ) {
  19109. return this.cacheArcLengths;
  19110. }
  19111. this.needsUpdate = false;
  19112. const cache = [];
  19113. let current, last = this.getPoint( 0 );
  19114. let sum = 0;
  19115. cache.push( 0 );
  19116. for ( let p = 1; p <= divisions; p ++ ) {
  19117. current = this.getPoint( p / divisions );
  19118. sum += current.distanceTo( last );
  19119. cache.push( sum );
  19120. last = current;
  19121. }
  19122. this.cacheArcLengths = cache;
  19123. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  19124. }
  19125. updateArcLengths() {
  19126. this.needsUpdate = true;
  19127. this.getLengths();
  19128. }
  19129. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19130. getUtoTmapping( u, distance ) {
  19131. const arcLengths = this.getLengths();
  19132. let i = 0;
  19133. const il = arcLengths.length;
  19134. let targetArcLength; // The targeted u distance value to get
  19135. if ( distance ) {
  19136. targetArcLength = distance;
  19137. } else {
  19138. targetArcLength = u * arcLengths[ il - 1 ];
  19139. }
  19140. // binary search for the index with largest value smaller than target u distance
  19141. let low = 0, high = il - 1, comparison;
  19142. while ( low <= high ) {
  19143. 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
  19144. comparison = arcLengths[ i ] - targetArcLength;
  19145. if ( comparison < 0 ) {
  19146. low = i + 1;
  19147. } else if ( comparison > 0 ) {
  19148. high = i - 1;
  19149. } else {
  19150. high = i;
  19151. break;
  19152. // DONE
  19153. }
  19154. }
  19155. i = high;
  19156. if ( arcLengths[ i ] === targetArcLength ) {
  19157. return i / ( il - 1 );
  19158. }
  19159. // we could get finer grain at lengths, or use simple interpolation between two points
  19160. const lengthBefore = arcLengths[ i ];
  19161. const lengthAfter = arcLengths[ i + 1 ];
  19162. const segmentLength = lengthAfter - lengthBefore;
  19163. // determine where we are between the 'before' and 'after' points
  19164. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  19165. // add that fractional amount to t
  19166. const t = ( i + segmentFraction ) / ( il - 1 );
  19167. return t;
  19168. }
  19169. // Returns a unit vector tangent at t
  19170. // In case any sub curve does not implement its tangent derivation,
  19171. // 2 points a small delta apart will be used to find its gradient
  19172. // which seems to give a reasonable approximation
  19173. getTangent( t, optionalTarget ) {
  19174. const delta = 0.0001;
  19175. let t1 = t - delta;
  19176. let t2 = t + delta;
  19177. // Capping in case of danger
  19178. if ( t1 < 0 ) t1 = 0;
  19179. if ( t2 > 1 ) t2 = 1;
  19180. const pt1 = this.getPoint( t1 );
  19181. const pt2 = this.getPoint( t2 );
  19182. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  19183. tangent.copy( pt2 ).sub( pt1 ).normalize();
  19184. return tangent;
  19185. }
  19186. getTangentAt( u, optionalTarget ) {
  19187. const t = this.getUtoTmapping( u );
  19188. return this.getTangent( t, optionalTarget );
  19189. }
  19190. computeFrenetFrames( segments, closed ) {
  19191. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19192. const normal = new Vector3();
  19193. const tangents = [];
  19194. const normals = [];
  19195. const binormals = [];
  19196. const vec = new Vector3();
  19197. const mat = new Matrix4();
  19198. // compute the tangent vectors for each segment on the curve
  19199. for ( let i = 0; i <= segments; i ++ ) {
  19200. const u = i / segments;
  19201. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  19202. }
  19203. // select an initial normal vector perpendicular to the first tangent vector,
  19204. // and in the direction of the minimum tangent xyz component
  19205. normals[ 0 ] = new Vector3();
  19206. binormals[ 0 ] = new Vector3();
  19207. let min = Number.MAX_VALUE;
  19208. const tx = Math.abs( tangents[ 0 ].x );
  19209. const ty = Math.abs( tangents[ 0 ].y );
  19210. const tz = Math.abs( tangents[ 0 ].z );
  19211. if ( tx <= min ) {
  19212. min = tx;
  19213. normal.set( 1, 0, 0 );
  19214. }
  19215. if ( ty <= min ) {
  19216. min = ty;
  19217. normal.set( 0, 1, 0 );
  19218. }
  19219. if ( tz <= min ) {
  19220. normal.set( 0, 0, 1 );
  19221. }
  19222. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19223. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19224. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19225. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  19226. for ( let i = 1; i <= segments; i ++ ) {
  19227. normals[ i ] = normals[ i - 1 ].clone();
  19228. binormals[ i ] = binormals[ i - 1 ].clone();
  19229. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19230. if ( vec.length() > Number.EPSILON ) {
  19231. vec.normalize();
  19232. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19233. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19234. }
  19235. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19236. }
  19237. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19238. if ( closed === true ) {
  19239. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  19240. theta /= segments;
  19241. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  19242. theta = - theta;
  19243. }
  19244. for ( let i = 1; i <= segments; i ++ ) {
  19245. // twist a little...
  19246. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19247. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19248. }
  19249. }
  19250. return {
  19251. tangents: tangents,
  19252. normals: normals,
  19253. binormals: binormals
  19254. };
  19255. }
  19256. clone() {
  19257. return new this.constructor().copy( this );
  19258. }
  19259. copy( source ) {
  19260. this.arcLengthDivisions = source.arcLengthDivisions;
  19261. return this;
  19262. }
  19263. toJSON() {
  19264. const data = {
  19265. metadata: {
  19266. version: 4.5,
  19267. type: 'Curve',
  19268. generator: 'Curve.toJSON'
  19269. }
  19270. };
  19271. data.arcLengthDivisions = this.arcLengthDivisions;
  19272. data.type = this.type;
  19273. return data;
  19274. }
  19275. fromJSON( json ) {
  19276. this.arcLengthDivisions = json.arcLengthDivisions;
  19277. return this;
  19278. }
  19279. }
  19280. class EllipseCurve extends Curve {
  19281. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  19282. super();
  19283. this.isEllipseCurve = true;
  19284. this.type = 'EllipseCurve';
  19285. this.aX = aX;
  19286. this.aY = aY;
  19287. this.xRadius = xRadius;
  19288. this.yRadius = yRadius;
  19289. this.aStartAngle = aStartAngle;
  19290. this.aEndAngle = aEndAngle;
  19291. this.aClockwise = aClockwise;
  19292. this.aRotation = aRotation;
  19293. }
  19294. getPoint( t, optionalTarget ) {
  19295. const point = optionalTarget || new Vector2();
  19296. const twoPi = Math.PI * 2;
  19297. let deltaAngle = this.aEndAngle - this.aStartAngle;
  19298. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  19299. // ensures that deltaAngle is 0 .. 2 PI
  19300. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  19301. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  19302. if ( deltaAngle < Number.EPSILON ) {
  19303. if ( samePoints ) {
  19304. deltaAngle = 0;
  19305. } else {
  19306. deltaAngle = twoPi;
  19307. }
  19308. }
  19309. if ( this.aClockwise === true && ! samePoints ) {
  19310. if ( deltaAngle === twoPi ) {
  19311. deltaAngle = - twoPi;
  19312. } else {
  19313. deltaAngle = deltaAngle - twoPi;
  19314. }
  19315. }
  19316. const angle = this.aStartAngle + t * deltaAngle;
  19317. let x = this.aX + this.xRadius * Math.cos( angle );
  19318. let y = this.aY + this.yRadius * Math.sin( angle );
  19319. if ( this.aRotation !== 0 ) {
  19320. const cos = Math.cos( this.aRotation );
  19321. const sin = Math.sin( this.aRotation );
  19322. const tx = x - this.aX;
  19323. const ty = y - this.aY;
  19324. // Rotate the point about the center of the ellipse.
  19325. x = tx * cos - ty * sin + this.aX;
  19326. y = tx * sin + ty * cos + this.aY;
  19327. }
  19328. return point.set( x, y );
  19329. }
  19330. copy( source ) {
  19331. super.copy( source );
  19332. this.aX = source.aX;
  19333. this.aY = source.aY;
  19334. this.xRadius = source.xRadius;
  19335. this.yRadius = source.yRadius;
  19336. this.aStartAngle = source.aStartAngle;
  19337. this.aEndAngle = source.aEndAngle;
  19338. this.aClockwise = source.aClockwise;
  19339. this.aRotation = source.aRotation;
  19340. return this;
  19341. }
  19342. toJSON() {
  19343. const data = super.toJSON();
  19344. data.aX = this.aX;
  19345. data.aY = this.aY;
  19346. data.xRadius = this.xRadius;
  19347. data.yRadius = this.yRadius;
  19348. data.aStartAngle = this.aStartAngle;
  19349. data.aEndAngle = this.aEndAngle;
  19350. data.aClockwise = this.aClockwise;
  19351. data.aRotation = this.aRotation;
  19352. return data;
  19353. }
  19354. fromJSON( json ) {
  19355. super.fromJSON( json );
  19356. this.aX = json.aX;
  19357. this.aY = json.aY;
  19358. this.xRadius = json.xRadius;
  19359. this.yRadius = json.yRadius;
  19360. this.aStartAngle = json.aStartAngle;
  19361. this.aEndAngle = json.aEndAngle;
  19362. this.aClockwise = json.aClockwise;
  19363. this.aRotation = json.aRotation;
  19364. return this;
  19365. }
  19366. }
  19367. class ArcCurve extends EllipseCurve {
  19368. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19369. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19370. this.isArcCurve = true;
  19371. this.type = 'ArcCurve';
  19372. }
  19373. }
  19374. /**
  19375. * Centripetal CatmullRom Curve - which is useful for avoiding
  19376. * cusps and self-intersections in non-uniform catmull rom curves.
  19377. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19378. *
  19379. * curve.type accepts centripetal(default), chordal and catmullrom
  19380. * curve.tension is used for catmullrom which defaults to 0.5
  19381. */
  19382. /*
  19383. Based on an optimized c++ solution in
  19384. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19385. - http://ideone.com/NoEbVM
  19386. This CubicPoly class could be used for reusing some variables and calculations,
  19387. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19388. which can be placed in CurveUtils.
  19389. */
  19390. function CubicPoly() {
  19391. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  19392. /*
  19393. * Compute coefficients for a cubic polynomial
  19394. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19395. * such that
  19396. * p(0) = x0, p(1) = x1
  19397. * and
  19398. * p'(0) = t0, p'(1) = t1.
  19399. */
  19400. function init( x0, x1, t0, t1 ) {
  19401. c0 = x0;
  19402. c1 = t0;
  19403. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19404. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19405. }
  19406. return {
  19407. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19408. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19409. },
  19410. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19411. // compute tangents when parameterized in [t1,t2]
  19412. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19413. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19414. // rescale tangents for parametrization in [0,1]
  19415. t1 *= dt1;
  19416. t2 *= dt1;
  19417. init( x1, x2, t1, t2 );
  19418. },
  19419. calc: function ( t ) {
  19420. const t2 = t * t;
  19421. const t3 = t2 * t;
  19422. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19423. }
  19424. };
  19425. }
  19426. //
  19427. const tmp = /*@__PURE__*/ new Vector3();
  19428. const px = /*@__PURE__*/ new CubicPoly();
  19429. const py = /*@__PURE__*/ new CubicPoly();
  19430. const pz = /*@__PURE__*/ new CubicPoly();
  19431. class CatmullRomCurve3 extends Curve {
  19432. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19433. super();
  19434. this.isCatmullRomCurve3 = true;
  19435. this.type = 'CatmullRomCurve3';
  19436. this.points = points;
  19437. this.closed = closed;
  19438. this.curveType = curveType;
  19439. this.tension = tension;
  19440. }
  19441. getPoint( t, optionalTarget = new Vector3() ) {
  19442. const point = optionalTarget;
  19443. const points = this.points;
  19444. const l = points.length;
  19445. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19446. let intPoint = Math.floor( p );
  19447. let weight = p - intPoint;
  19448. if ( this.closed ) {
  19449. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19450. } else if ( weight === 0 && intPoint === l - 1 ) {
  19451. intPoint = l - 2;
  19452. weight = 1;
  19453. }
  19454. let p0, p3; // 4 points (p1 & p2 defined below)
  19455. if ( this.closed || intPoint > 0 ) {
  19456. p0 = points[ ( intPoint - 1 ) % l ];
  19457. } else {
  19458. // extrapolate first point
  19459. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19460. p0 = tmp;
  19461. }
  19462. const p1 = points[ intPoint % l ];
  19463. const p2 = points[ ( intPoint + 1 ) % l ];
  19464. if ( this.closed || intPoint + 2 < l ) {
  19465. p3 = points[ ( intPoint + 2 ) % l ];
  19466. } else {
  19467. // extrapolate last point
  19468. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19469. p3 = tmp;
  19470. }
  19471. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19472. // init Centripetal / Chordal Catmull-Rom
  19473. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19474. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19475. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19476. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19477. // safety check for repeated points
  19478. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19479. if ( dt0 < 1e-4 ) dt0 = dt1;
  19480. if ( dt2 < 1e-4 ) dt2 = dt1;
  19481. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19482. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19483. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19484. } else if ( this.curveType === 'catmullrom' ) {
  19485. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19486. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19487. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19488. }
  19489. point.set(
  19490. px.calc( weight ),
  19491. py.calc( weight ),
  19492. pz.calc( weight )
  19493. );
  19494. return point;
  19495. }
  19496. copy( source ) {
  19497. super.copy( source );
  19498. this.points = [];
  19499. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19500. const point = source.points[ i ];
  19501. this.points.push( point.clone() );
  19502. }
  19503. this.closed = source.closed;
  19504. this.curveType = source.curveType;
  19505. this.tension = source.tension;
  19506. return this;
  19507. }
  19508. toJSON() {
  19509. const data = super.toJSON();
  19510. data.points = [];
  19511. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19512. const point = this.points[ i ];
  19513. data.points.push( point.toArray() );
  19514. }
  19515. data.closed = this.closed;
  19516. data.curveType = this.curveType;
  19517. data.tension = this.tension;
  19518. return data;
  19519. }
  19520. fromJSON( json ) {
  19521. super.fromJSON( json );
  19522. this.points = [];
  19523. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19524. const point = json.points[ i ];
  19525. this.points.push( new Vector3().fromArray( point ) );
  19526. }
  19527. this.closed = json.closed;
  19528. this.curveType = json.curveType;
  19529. this.tension = json.tension;
  19530. return this;
  19531. }
  19532. }
  19533. /**
  19534. * Bezier Curves formulas obtained from
  19535. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19536. */
  19537. function CatmullRom( t, p0, p1, p2, p3 ) {
  19538. const v0 = ( p2 - p0 ) * 0.5;
  19539. const v1 = ( p3 - p1 ) * 0.5;
  19540. const t2 = t * t;
  19541. const t3 = t * t2;
  19542. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19543. }
  19544. //
  19545. function QuadraticBezierP0( t, p ) {
  19546. const k = 1 - t;
  19547. return k * k * p;
  19548. }
  19549. function QuadraticBezierP1( t, p ) {
  19550. return 2 * ( 1 - t ) * t * p;
  19551. }
  19552. function QuadraticBezierP2( t, p ) {
  19553. return t * t * p;
  19554. }
  19555. function QuadraticBezier( t, p0, p1, p2 ) {
  19556. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19557. QuadraticBezierP2( t, p2 );
  19558. }
  19559. //
  19560. function CubicBezierP0( t, p ) {
  19561. const k = 1 - t;
  19562. return k * k * k * p;
  19563. }
  19564. function CubicBezierP1( t, p ) {
  19565. const k = 1 - t;
  19566. return 3 * k * k * t * p;
  19567. }
  19568. function CubicBezierP2( t, p ) {
  19569. return 3 * ( 1 - t ) * t * t * p;
  19570. }
  19571. function CubicBezierP3( t, p ) {
  19572. return t * t * t * p;
  19573. }
  19574. function CubicBezier( t, p0, p1, p2, p3 ) {
  19575. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19576. CubicBezierP3( t, p3 );
  19577. }
  19578. class CubicBezierCurve extends Curve {
  19579. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19580. super();
  19581. this.isCubicBezierCurve = true;
  19582. this.type = 'CubicBezierCurve';
  19583. this.v0 = v0;
  19584. this.v1 = v1;
  19585. this.v2 = v2;
  19586. this.v3 = v3;
  19587. }
  19588. getPoint( t, optionalTarget = new Vector2() ) {
  19589. const point = optionalTarget;
  19590. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19591. point.set(
  19592. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19593. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19594. );
  19595. return point;
  19596. }
  19597. copy( source ) {
  19598. super.copy( source );
  19599. this.v0.copy( source.v0 );
  19600. this.v1.copy( source.v1 );
  19601. this.v2.copy( source.v2 );
  19602. this.v3.copy( source.v3 );
  19603. return this;
  19604. }
  19605. toJSON() {
  19606. const data = super.toJSON();
  19607. data.v0 = this.v0.toArray();
  19608. data.v1 = this.v1.toArray();
  19609. data.v2 = this.v2.toArray();
  19610. data.v3 = this.v3.toArray();
  19611. return data;
  19612. }
  19613. fromJSON( json ) {
  19614. super.fromJSON( json );
  19615. this.v0.fromArray( json.v0 );
  19616. this.v1.fromArray( json.v1 );
  19617. this.v2.fromArray( json.v2 );
  19618. this.v3.fromArray( json.v3 );
  19619. return this;
  19620. }
  19621. }
  19622. class CubicBezierCurve3 extends Curve {
  19623. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19624. super();
  19625. this.isCubicBezierCurve3 = true;
  19626. this.type = 'CubicBezierCurve3';
  19627. this.v0 = v0;
  19628. this.v1 = v1;
  19629. this.v2 = v2;
  19630. this.v3 = v3;
  19631. }
  19632. getPoint( t, optionalTarget = new Vector3() ) {
  19633. const point = optionalTarget;
  19634. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19635. point.set(
  19636. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19637. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19638. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19639. );
  19640. return point;
  19641. }
  19642. copy( source ) {
  19643. super.copy( source );
  19644. this.v0.copy( source.v0 );
  19645. this.v1.copy( source.v1 );
  19646. this.v2.copy( source.v2 );
  19647. this.v3.copy( source.v3 );
  19648. return this;
  19649. }
  19650. toJSON() {
  19651. const data = super.toJSON();
  19652. data.v0 = this.v0.toArray();
  19653. data.v1 = this.v1.toArray();
  19654. data.v2 = this.v2.toArray();
  19655. data.v3 = this.v3.toArray();
  19656. return data;
  19657. }
  19658. fromJSON( json ) {
  19659. super.fromJSON( json );
  19660. this.v0.fromArray( json.v0 );
  19661. this.v1.fromArray( json.v1 );
  19662. this.v2.fromArray( json.v2 );
  19663. this.v3.fromArray( json.v3 );
  19664. return this;
  19665. }
  19666. }
  19667. class LineCurve extends Curve {
  19668. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19669. super();
  19670. this.isLineCurve = true;
  19671. this.type = 'LineCurve';
  19672. this.v1 = v1;
  19673. this.v2 = v2;
  19674. }
  19675. getPoint( t, optionalTarget = new Vector2() ) {
  19676. const point = optionalTarget;
  19677. if ( t === 1 ) {
  19678. point.copy( this.v2 );
  19679. } else {
  19680. point.copy( this.v2 ).sub( this.v1 );
  19681. point.multiplyScalar( t ).add( this.v1 );
  19682. }
  19683. return point;
  19684. }
  19685. // Line curve is linear, so we can overwrite default getPointAt
  19686. getPointAt( u, optionalTarget ) {
  19687. return this.getPoint( u, optionalTarget );
  19688. }
  19689. getTangent( t, optionalTarget = new Vector2() ) {
  19690. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  19691. }
  19692. getTangentAt( u, optionalTarget ) {
  19693. return this.getTangent( u, optionalTarget );
  19694. }
  19695. copy( source ) {
  19696. super.copy( source );
  19697. this.v1.copy( source.v1 );
  19698. this.v2.copy( source.v2 );
  19699. return this;
  19700. }
  19701. toJSON() {
  19702. const data = super.toJSON();
  19703. data.v1 = this.v1.toArray();
  19704. data.v2 = this.v2.toArray();
  19705. return data;
  19706. }
  19707. fromJSON( json ) {
  19708. super.fromJSON( json );
  19709. this.v1.fromArray( json.v1 );
  19710. this.v2.fromArray( json.v2 );
  19711. return this;
  19712. }
  19713. }
  19714. class LineCurve3 extends Curve {
  19715. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19716. super();
  19717. this.isLineCurve3 = true;
  19718. this.type = 'LineCurve3';
  19719. this.v1 = v1;
  19720. this.v2 = v2;
  19721. }
  19722. getPoint( t, optionalTarget = new Vector3() ) {
  19723. const point = optionalTarget;
  19724. if ( t === 1 ) {
  19725. point.copy( this.v2 );
  19726. } else {
  19727. point.copy( this.v2 ).sub( this.v1 );
  19728. point.multiplyScalar( t ).add( this.v1 );
  19729. }
  19730. return point;
  19731. }
  19732. // Line curve is linear, so we can overwrite default getPointAt
  19733. getPointAt( u, optionalTarget ) {
  19734. return this.getPoint( u, optionalTarget );
  19735. }
  19736. getTangent( t, optionalTarget = new Vector3() ) {
  19737. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  19738. }
  19739. getTangentAt( u, optionalTarget ) {
  19740. return this.getTangent( u, optionalTarget );
  19741. }
  19742. copy( source ) {
  19743. super.copy( source );
  19744. this.v1.copy( source.v1 );
  19745. this.v2.copy( source.v2 );
  19746. return this;
  19747. }
  19748. toJSON() {
  19749. const data = super.toJSON();
  19750. data.v1 = this.v1.toArray();
  19751. data.v2 = this.v2.toArray();
  19752. return data;
  19753. }
  19754. fromJSON( json ) {
  19755. super.fromJSON( json );
  19756. this.v1.fromArray( json.v1 );
  19757. this.v2.fromArray( json.v2 );
  19758. return this;
  19759. }
  19760. }
  19761. class QuadraticBezierCurve extends Curve {
  19762. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19763. super();
  19764. this.isQuadraticBezierCurve = true;
  19765. this.type = 'QuadraticBezierCurve';
  19766. this.v0 = v0;
  19767. this.v1 = v1;
  19768. this.v2 = v2;
  19769. }
  19770. getPoint( t, optionalTarget = new Vector2() ) {
  19771. const point = optionalTarget;
  19772. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19773. point.set(
  19774. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19775. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19776. );
  19777. return point;
  19778. }
  19779. copy( source ) {
  19780. super.copy( source );
  19781. this.v0.copy( source.v0 );
  19782. this.v1.copy( source.v1 );
  19783. this.v2.copy( source.v2 );
  19784. return this;
  19785. }
  19786. toJSON() {
  19787. const data = super.toJSON();
  19788. data.v0 = this.v0.toArray();
  19789. data.v1 = this.v1.toArray();
  19790. data.v2 = this.v2.toArray();
  19791. return data;
  19792. }
  19793. fromJSON( json ) {
  19794. super.fromJSON( json );
  19795. this.v0.fromArray( json.v0 );
  19796. this.v1.fromArray( json.v1 );
  19797. this.v2.fromArray( json.v2 );
  19798. return this;
  19799. }
  19800. }
  19801. class QuadraticBezierCurve3 extends Curve {
  19802. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19803. super();
  19804. this.isQuadraticBezierCurve3 = true;
  19805. this.type = 'QuadraticBezierCurve3';
  19806. this.v0 = v0;
  19807. this.v1 = v1;
  19808. this.v2 = v2;
  19809. }
  19810. getPoint( t, optionalTarget = new Vector3() ) {
  19811. const point = optionalTarget;
  19812. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19813. point.set(
  19814. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19815. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19816. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19817. );
  19818. return point;
  19819. }
  19820. copy( source ) {
  19821. super.copy( source );
  19822. this.v0.copy( source.v0 );
  19823. this.v1.copy( source.v1 );
  19824. this.v2.copy( source.v2 );
  19825. return this;
  19826. }
  19827. toJSON() {
  19828. const data = super.toJSON();
  19829. data.v0 = this.v0.toArray();
  19830. data.v1 = this.v1.toArray();
  19831. data.v2 = this.v2.toArray();
  19832. return data;
  19833. }
  19834. fromJSON( json ) {
  19835. super.fromJSON( json );
  19836. this.v0.fromArray( json.v0 );
  19837. this.v1.fromArray( json.v1 );
  19838. this.v2.fromArray( json.v2 );
  19839. return this;
  19840. }
  19841. }
  19842. class SplineCurve extends Curve {
  19843. constructor( points = [] ) {
  19844. super();
  19845. this.isSplineCurve = true;
  19846. this.type = 'SplineCurve';
  19847. this.points = points;
  19848. }
  19849. getPoint( t, optionalTarget = new Vector2() ) {
  19850. const point = optionalTarget;
  19851. const points = this.points;
  19852. const p = ( points.length - 1 ) * t;
  19853. const intPoint = Math.floor( p );
  19854. const weight = p - intPoint;
  19855. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19856. const p1 = points[ intPoint ];
  19857. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19858. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19859. point.set(
  19860. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19861. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19862. );
  19863. return point;
  19864. }
  19865. copy( source ) {
  19866. super.copy( source );
  19867. this.points = [];
  19868. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19869. const point = source.points[ i ];
  19870. this.points.push( point.clone() );
  19871. }
  19872. return this;
  19873. }
  19874. toJSON() {
  19875. const data = super.toJSON();
  19876. data.points = [];
  19877. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19878. const point = this.points[ i ];
  19879. data.points.push( point.toArray() );
  19880. }
  19881. return data;
  19882. }
  19883. fromJSON( json ) {
  19884. super.fromJSON( json );
  19885. this.points = [];
  19886. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19887. const point = json.points[ i ];
  19888. this.points.push( new Vector2().fromArray( point ) );
  19889. }
  19890. return this;
  19891. }
  19892. }
  19893. var Curves = /*#__PURE__*/Object.freeze({
  19894. __proto__: null,
  19895. ArcCurve: ArcCurve,
  19896. CatmullRomCurve3: CatmullRomCurve3,
  19897. CubicBezierCurve: CubicBezierCurve,
  19898. CubicBezierCurve3: CubicBezierCurve3,
  19899. EllipseCurve: EllipseCurve,
  19900. LineCurve: LineCurve,
  19901. LineCurve3: LineCurve3,
  19902. QuadraticBezierCurve: QuadraticBezierCurve,
  19903. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19904. SplineCurve: SplineCurve
  19905. });
  19906. /**************************************************************
  19907. * Curved Path - a curve path is simply a array of connected
  19908. * curves, but retains the api of a curve
  19909. **************************************************************/
  19910. class CurvePath extends Curve {
  19911. constructor() {
  19912. super();
  19913. this.type = 'CurvePath';
  19914. this.curves = [];
  19915. this.autoClose = false; // Automatically closes the path
  19916. }
  19917. add( curve ) {
  19918. this.curves.push( curve );
  19919. }
  19920. closePath() {
  19921. // Add a line curve if start and end of lines are not connected
  19922. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19923. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19924. if ( ! startPoint.equals( endPoint ) ) {
  19925. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19926. }
  19927. }
  19928. // To get accurate point with reference to
  19929. // entire path distance at time t,
  19930. // following has to be done:
  19931. // 1. Length of each sub path have to be known
  19932. // 2. Locate and identify type of curve
  19933. // 3. Get t for the curve
  19934. // 4. Return curve.getPointAt(t')
  19935. getPoint( t, optionalTarget ) {
  19936. const d = t * this.getLength();
  19937. const curveLengths = this.getCurveLengths();
  19938. let i = 0;
  19939. // To think about boundaries points.
  19940. while ( i < curveLengths.length ) {
  19941. if ( curveLengths[ i ] >= d ) {
  19942. const diff = curveLengths[ i ] - d;
  19943. const curve = this.curves[ i ];
  19944. const segmentLength = curve.getLength();
  19945. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19946. return curve.getPointAt( u, optionalTarget );
  19947. }
  19948. i ++;
  19949. }
  19950. return null;
  19951. // loop where sum != 0, sum > d , sum+1 <d
  19952. }
  19953. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19954. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19955. // getPoint() depends on getLength
  19956. getLength() {
  19957. const lens = this.getCurveLengths();
  19958. return lens[ lens.length - 1 ];
  19959. }
  19960. // cacheLengths must be recalculated.
  19961. updateArcLengths() {
  19962. this.needsUpdate = true;
  19963. this.cacheLengths = null;
  19964. this.getCurveLengths();
  19965. }
  19966. // Compute lengths and cache them
  19967. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19968. getCurveLengths() {
  19969. // We use cache values if curves and cache array are same length
  19970. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19971. return this.cacheLengths;
  19972. }
  19973. // Get length of sub-curve
  19974. // Push sums into cached array
  19975. const lengths = [];
  19976. let sums = 0;
  19977. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19978. sums += this.curves[ i ].getLength();
  19979. lengths.push( sums );
  19980. }
  19981. this.cacheLengths = lengths;
  19982. return lengths;
  19983. }
  19984. getSpacedPoints( divisions = 40 ) {
  19985. const points = [];
  19986. for ( let i = 0; i <= divisions; i ++ ) {
  19987. points.push( this.getPoint( i / divisions ) );
  19988. }
  19989. if ( this.autoClose ) {
  19990. points.push( points[ 0 ] );
  19991. }
  19992. return points;
  19993. }
  19994. getPoints( divisions = 12 ) {
  19995. const points = [];
  19996. let last;
  19997. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19998. const curve = curves[ i ];
  19999. const resolution = curve.isEllipseCurve ? divisions * 2
  20000. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  20001. : curve.isSplineCurve ? divisions * curve.points.length
  20002. : divisions;
  20003. const pts = curve.getPoints( resolution );
  20004. for ( let j = 0; j < pts.length; j ++ ) {
  20005. const point = pts[ j ];
  20006. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20007. points.push( point );
  20008. last = point;
  20009. }
  20010. }
  20011. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20012. points.push( points[ 0 ] );
  20013. }
  20014. return points;
  20015. }
  20016. copy( source ) {
  20017. super.copy( source );
  20018. this.curves = [];
  20019. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  20020. const curve = source.curves[ i ];
  20021. this.curves.push( curve.clone() );
  20022. }
  20023. this.autoClose = source.autoClose;
  20024. return this;
  20025. }
  20026. toJSON() {
  20027. const data = super.toJSON();
  20028. data.autoClose = this.autoClose;
  20029. data.curves = [];
  20030. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  20031. const curve = this.curves[ i ];
  20032. data.curves.push( curve.toJSON() );
  20033. }
  20034. return data;
  20035. }
  20036. fromJSON( json ) {
  20037. super.fromJSON( json );
  20038. this.autoClose = json.autoClose;
  20039. this.curves = [];
  20040. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  20041. const curve = json.curves[ i ];
  20042. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  20043. }
  20044. return this;
  20045. }
  20046. }
  20047. class Path extends CurvePath {
  20048. constructor( points ) {
  20049. super();
  20050. this.type = 'Path';
  20051. this.currentPoint = new Vector2();
  20052. if ( points ) {
  20053. this.setFromPoints( points );
  20054. }
  20055. }
  20056. setFromPoints( points ) {
  20057. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  20058. for ( let i = 1, l = points.length; i < l; i ++ ) {
  20059. this.lineTo( points[ i ].x, points[ i ].y );
  20060. }
  20061. return this;
  20062. }
  20063. moveTo( x, y ) {
  20064. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  20065. return this;
  20066. }
  20067. lineTo( x, y ) {
  20068. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  20069. this.curves.push( curve );
  20070. this.currentPoint.set( x, y );
  20071. return this;
  20072. }
  20073. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  20074. const curve = new QuadraticBezierCurve(
  20075. this.currentPoint.clone(),
  20076. new Vector2( aCPx, aCPy ),
  20077. new Vector2( aX, aY )
  20078. );
  20079. this.curves.push( curve );
  20080. this.currentPoint.set( aX, aY );
  20081. return this;
  20082. }
  20083. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20084. const curve = new CubicBezierCurve(
  20085. this.currentPoint.clone(),
  20086. new Vector2( aCP1x, aCP1y ),
  20087. new Vector2( aCP2x, aCP2y ),
  20088. new Vector2( aX, aY )
  20089. );
  20090. this.curves.push( curve );
  20091. this.currentPoint.set( aX, aY );
  20092. return this;
  20093. }
  20094. splineThru( pts /*Array of Vector*/ ) {
  20095. const npts = [ this.currentPoint.clone() ].concat( pts );
  20096. const curve = new SplineCurve( npts );
  20097. this.curves.push( curve );
  20098. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20099. return this;
  20100. }
  20101. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20102. const x0 = this.currentPoint.x;
  20103. const y0 = this.currentPoint.y;
  20104. this.absarc( aX + x0, aY + y0, aRadius,
  20105. aStartAngle, aEndAngle, aClockwise );
  20106. return this;
  20107. }
  20108. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20109. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20110. return this;
  20111. }
  20112. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20113. const x0 = this.currentPoint.x;
  20114. const y0 = this.currentPoint.y;
  20115. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20116. return this;
  20117. }
  20118. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20119. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20120. if ( this.curves.length > 0 ) {
  20121. // if a previous curve is present, attempt to join
  20122. const firstPoint = curve.getPoint( 0 );
  20123. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20124. this.lineTo( firstPoint.x, firstPoint.y );
  20125. }
  20126. }
  20127. this.curves.push( curve );
  20128. const lastPoint = curve.getPoint( 1 );
  20129. this.currentPoint.copy( lastPoint );
  20130. return this;
  20131. }
  20132. copy( source ) {
  20133. super.copy( source );
  20134. this.currentPoint.copy( source.currentPoint );
  20135. return this;
  20136. }
  20137. toJSON() {
  20138. const data = super.toJSON();
  20139. data.currentPoint = this.currentPoint.toArray();
  20140. return data;
  20141. }
  20142. fromJSON( json ) {
  20143. super.fromJSON( json );
  20144. this.currentPoint.fromArray( json.currentPoint );
  20145. return this;
  20146. }
  20147. }
  20148. class LatheGeometry extends BufferGeometry {
  20149. 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 ) {
  20150. super();
  20151. this.type = 'LatheGeometry';
  20152. this.parameters = {
  20153. points: points,
  20154. segments: segments,
  20155. phiStart: phiStart,
  20156. phiLength: phiLength
  20157. };
  20158. segments = Math.floor( segments );
  20159. // clamp phiLength so it's in range of [ 0, 2PI ]
  20160. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  20161. // buffers
  20162. const indices = [];
  20163. const vertices = [];
  20164. const uvs = [];
  20165. const initNormals = [];
  20166. const normals = [];
  20167. // helper variables
  20168. const inverseSegments = 1.0 / segments;
  20169. const vertex = new Vector3();
  20170. const uv = new Vector2();
  20171. const normal = new Vector3();
  20172. const curNormal = new Vector3();
  20173. const prevNormal = new Vector3();
  20174. let dx = 0;
  20175. let dy = 0;
  20176. // pre-compute normals for initial "meridian"
  20177. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20178. switch ( j ) {
  20179. case 0: // special handling for 1st vertex on path
  20180. dx = points[ j + 1 ].x - points[ j ].x;
  20181. dy = points[ j + 1 ].y - points[ j ].y;
  20182. normal.x = dy * 1.0;
  20183. normal.y = - dx;
  20184. normal.z = dy * 0.0;
  20185. prevNormal.copy( normal );
  20186. normal.normalize();
  20187. initNormals.push( normal.x, normal.y, normal.z );
  20188. break;
  20189. case ( points.length - 1 ): // special handling for last Vertex on path
  20190. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  20191. break;
  20192. default: // default handling for all vertices in between
  20193. dx = points[ j + 1 ].x - points[ j ].x;
  20194. dy = points[ j + 1 ].y - points[ j ].y;
  20195. normal.x = dy * 1.0;
  20196. normal.y = - dx;
  20197. normal.z = dy * 0.0;
  20198. curNormal.copy( normal );
  20199. normal.x += prevNormal.x;
  20200. normal.y += prevNormal.y;
  20201. normal.z += prevNormal.z;
  20202. normal.normalize();
  20203. initNormals.push( normal.x, normal.y, normal.z );
  20204. prevNormal.copy( curNormal );
  20205. }
  20206. }
  20207. // generate vertices, uvs and normals
  20208. for ( let i = 0; i <= segments; i ++ ) {
  20209. const phi = phiStart + i * inverseSegments * phiLength;
  20210. const sin = Math.sin( phi );
  20211. const cos = Math.cos( phi );
  20212. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20213. // vertex
  20214. vertex.x = points[ j ].x * sin;
  20215. vertex.y = points[ j ].y;
  20216. vertex.z = points[ j ].x * cos;
  20217. vertices.push( vertex.x, vertex.y, vertex.z );
  20218. // uv
  20219. uv.x = i / segments;
  20220. uv.y = j / ( points.length - 1 );
  20221. uvs.push( uv.x, uv.y );
  20222. // normal
  20223. const x = initNormals[ 3 * j + 0 ] * sin;
  20224. const y = initNormals[ 3 * j + 1 ];
  20225. const z = initNormals[ 3 * j + 0 ] * cos;
  20226. normals.push( x, y, z );
  20227. }
  20228. }
  20229. // indices
  20230. for ( let i = 0; i < segments; i ++ ) {
  20231. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  20232. const base = j + i * points.length;
  20233. const a = base;
  20234. const b = base + points.length;
  20235. const c = base + points.length + 1;
  20236. const d = base + 1;
  20237. // faces
  20238. indices.push( a, b, d );
  20239. indices.push( c, d, b );
  20240. }
  20241. }
  20242. // build geometry
  20243. this.setIndex( indices );
  20244. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20245. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20246. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20247. }
  20248. copy( source ) {
  20249. super.copy( source );
  20250. this.parameters = Object.assign( {}, source.parameters );
  20251. return this;
  20252. }
  20253. static fromJSON( data ) {
  20254. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  20255. }
  20256. }
  20257. class CapsuleGeometry extends LatheGeometry {
  20258. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  20259. const path = new Path();
  20260. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  20261. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  20262. super( path.getPoints( capSegments ), radialSegments );
  20263. this.type = 'CapsuleGeometry';
  20264. this.parameters = {
  20265. radius: radius,
  20266. height: length,
  20267. capSegments: capSegments,
  20268. radialSegments: radialSegments,
  20269. };
  20270. }
  20271. static fromJSON( data ) {
  20272. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  20273. }
  20274. }
  20275. class CircleGeometry extends BufferGeometry {
  20276. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20277. super();
  20278. this.type = 'CircleGeometry';
  20279. this.parameters = {
  20280. radius: radius,
  20281. segments: segments,
  20282. thetaStart: thetaStart,
  20283. thetaLength: thetaLength
  20284. };
  20285. segments = Math.max( 3, segments );
  20286. // buffers
  20287. const indices = [];
  20288. const vertices = [];
  20289. const normals = [];
  20290. const uvs = [];
  20291. // helper variables
  20292. const vertex = new Vector3();
  20293. const uv = new Vector2();
  20294. // center point
  20295. vertices.push( 0, 0, 0 );
  20296. normals.push( 0, 0, 1 );
  20297. uvs.push( 0.5, 0.5 );
  20298. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  20299. const segment = thetaStart + s / segments * thetaLength;
  20300. // vertex
  20301. vertex.x = radius * Math.cos( segment );
  20302. vertex.y = radius * Math.sin( segment );
  20303. vertices.push( vertex.x, vertex.y, vertex.z );
  20304. // normal
  20305. normals.push( 0, 0, 1 );
  20306. // uvs
  20307. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  20308. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  20309. uvs.push( uv.x, uv.y );
  20310. }
  20311. // indices
  20312. for ( let i = 1; i <= segments; i ++ ) {
  20313. indices.push( i, i + 1, 0 );
  20314. }
  20315. // build geometry
  20316. this.setIndex( indices );
  20317. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20318. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20319. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20320. }
  20321. copy( source ) {
  20322. super.copy( source );
  20323. this.parameters = Object.assign( {}, source.parameters );
  20324. return this;
  20325. }
  20326. static fromJSON( data ) {
  20327. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  20328. }
  20329. }
  20330. class CylinderGeometry extends BufferGeometry {
  20331. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20332. super();
  20333. this.type = 'CylinderGeometry';
  20334. this.parameters = {
  20335. radiusTop: radiusTop,
  20336. radiusBottom: radiusBottom,
  20337. height: height,
  20338. radialSegments: radialSegments,
  20339. heightSegments: heightSegments,
  20340. openEnded: openEnded,
  20341. thetaStart: thetaStart,
  20342. thetaLength: thetaLength
  20343. };
  20344. const scope = this;
  20345. radialSegments = Math.floor( radialSegments );
  20346. heightSegments = Math.floor( heightSegments );
  20347. // buffers
  20348. const indices = [];
  20349. const vertices = [];
  20350. const normals = [];
  20351. const uvs = [];
  20352. // helper variables
  20353. let index = 0;
  20354. const indexArray = [];
  20355. const halfHeight = height / 2;
  20356. let groupStart = 0;
  20357. // generate geometry
  20358. generateTorso();
  20359. if ( openEnded === false ) {
  20360. if ( radiusTop > 0 ) generateCap( true );
  20361. if ( radiusBottom > 0 ) generateCap( false );
  20362. }
  20363. // build geometry
  20364. this.setIndex( indices );
  20365. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20366. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20367. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20368. function generateTorso() {
  20369. const normal = new Vector3();
  20370. const vertex = new Vector3();
  20371. let groupCount = 0;
  20372. // this will be used to calculate the normal
  20373. const slope = ( radiusBottom - radiusTop ) / height;
  20374. // generate vertices, normals and uvs
  20375. for ( let y = 0; y <= heightSegments; y ++ ) {
  20376. const indexRow = [];
  20377. const v = y / heightSegments;
  20378. // calculate the radius of the current row
  20379. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20380. for ( let x = 0; x <= radialSegments; x ++ ) {
  20381. const u = x / radialSegments;
  20382. const theta = u * thetaLength + thetaStart;
  20383. const sinTheta = Math.sin( theta );
  20384. const cosTheta = Math.cos( theta );
  20385. // vertex
  20386. vertex.x = radius * sinTheta;
  20387. vertex.y = - v * height + halfHeight;
  20388. vertex.z = radius * cosTheta;
  20389. vertices.push( vertex.x, vertex.y, vertex.z );
  20390. // normal
  20391. normal.set( sinTheta, slope, cosTheta ).normalize();
  20392. normals.push( normal.x, normal.y, normal.z );
  20393. // uv
  20394. uvs.push( u, 1 - v );
  20395. // save index of vertex in respective row
  20396. indexRow.push( index ++ );
  20397. }
  20398. // now save vertices of the row in our index array
  20399. indexArray.push( indexRow );
  20400. }
  20401. // generate indices
  20402. for ( let x = 0; x < radialSegments; x ++ ) {
  20403. for ( let y = 0; y < heightSegments; y ++ ) {
  20404. // we use the index array to access the correct indices
  20405. const a = indexArray[ y ][ x ];
  20406. const b = indexArray[ y + 1 ][ x ];
  20407. const c = indexArray[ y + 1 ][ x + 1 ];
  20408. const d = indexArray[ y ][ x + 1 ];
  20409. // faces
  20410. indices.push( a, b, d );
  20411. indices.push( b, c, d );
  20412. // update group counter
  20413. groupCount += 6;
  20414. }
  20415. }
  20416. // add a group to the geometry. this will ensure multi material support
  20417. scope.addGroup( groupStart, groupCount, 0 );
  20418. // calculate new start value for groups
  20419. groupStart += groupCount;
  20420. }
  20421. function generateCap( top ) {
  20422. // save the index of the first center vertex
  20423. const centerIndexStart = index;
  20424. const uv = new Vector2();
  20425. const vertex = new Vector3();
  20426. let groupCount = 0;
  20427. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20428. const sign = ( top === true ) ? 1 : - 1;
  20429. // first we generate the center vertex data of the cap.
  20430. // because the geometry needs one set of uvs per face,
  20431. // we must generate a center vertex per face/segment
  20432. for ( let x = 1; x <= radialSegments; x ++ ) {
  20433. // vertex
  20434. vertices.push( 0, halfHeight * sign, 0 );
  20435. // normal
  20436. normals.push( 0, sign, 0 );
  20437. // uv
  20438. uvs.push( 0.5, 0.5 );
  20439. // increase index
  20440. index ++;
  20441. }
  20442. // save the index of the last center vertex
  20443. const centerIndexEnd = index;
  20444. // now we generate the surrounding vertices, normals and uvs
  20445. for ( let x = 0; x <= radialSegments; x ++ ) {
  20446. const u = x / radialSegments;
  20447. const theta = u * thetaLength + thetaStart;
  20448. const cosTheta = Math.cos( theta );
  20449. const sinTheta = Math.sin( theta );
  20450. // vertex
  20451. vertex.x = radius * sinTheta;
  20452. vertex.y = halfHeight * sign;
  20453. vertex.z = radius * cosTheta;
  20454. vertices.push( vertex.x, vertex.y, vertex.z );
  20455. // normal
  20456. normals.push( 0, sign, 0 );
  20457. // uv
  20458. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20459. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20460. uvs.push( uv.x, uv.y );
  20461. // increase index
  20462. index ++;
  20463. }
  20464. // generate indices
  20465. for ( let x = 0; x < radialSegments; x ++ ) {
  20466. const c = centerIndexStart + x;
  20467. const i = centerIndexEnd + x;
  20468. if ( top === true ) {
  20469. // face top
  20470. indices.push( i, i + 1, c );
  20471. } else {
  20472. // face bottom
  20473. indices.push( i + 1, i, c );
  20474. }
  20475. groupCount += 3;
  20476. }
  20477. // add a group to the geometry. this will ensure multi material support
  20478. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20479. // calculate new start value for groups
  20480. groupStart += groupCount;
  20481. }
  20482. }
  20483. copy( source ) {
  20484. super.copy( source );
  20485. this.parameters = Object.assign( {}, source.parameters );
  20486. return this;
  20487. }
  20488. static fromJSON( data ) {
  20489. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20490. }
  20491. }
  20492. class ConeGeometry extends CylinderGeometry {
  20493. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20494. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20495. this.type = 'ConeGeometry';
  20496. this.parameters = {
  20497. radius: radius,
  20498. height: height,
  20499. radialSegments: radialSegments,
  20500. heightSegments: heightSegments,
  20501. openEnded: openEnded,
  20502. thetaStart: thetaStart,
  20503. thetaLength: thetaLength
  20504. };
  20505. }
  20506. static fromJSON( data ) {
  20507. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20508. }
  20509. }
  20510. class PolyhedronGeometry extends BufferGeometry {
  20511. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20512. super();
  20513. this.type = 'PolyhedronGeometry';
  20514. this.parameters = {
  20515. vertices: vertices,
  20516. indices: indices,
  20517. radius: radius,
  20518. detail: detail
  20519. };
  20520. // default buffer data
  20521. const vertexBuffer = [];
  20522. const uvBuffer = [];
  20523. // the subdivision creates the vertex buffer data
  20524. subdivide( detail );
  20525. // all vertices should lie on a conceptual sphere with a given radius
  20526. applyRadius( radius );
  20527. // finally, create the uv data
  20528. generateUVs();
  20529. // build non-indexed geometry
  20530. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20531. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20532. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20533. if ( detail === 0 ) {
  20534. this.computeVertexNormals(); // flat normals
  20535. } else {
  20536. this.normalizeNormals(); // smooth normals
  20537. }
  20538. // helper functions
  20539. function subdivide( detail ) {
  20540. const a = new Vector3();
  20541. const b = new Vector3();
  20542. const c = new Vector3();
  20543. // iterate over all faces and apply a subdivision with the given detail value
  20544. for ( let i = 0; i < indices.length; i += 3 ) {
  20545. // get the vertices of the face
  20546. getVertexByIndex( indices[ i + 0 ], a );
  20547. getVertexByIndex( indices[ i + 1 ], b );
  20548. getVertexByIndex( indices[ i + 2 ], c );
  20549. // perform subdivision
  20550. subdivideFace( a, b, c, detail );
  20551. }
  20552. }
  20553. function subdivideFace( a, b, c, detail ) {
  20554. const cols = detail + 1;
  20555. // we use this multidimensional array as a data structure for creating the subdivision
  20556. const v = [];
  20557. // construct all of the vertices for this subdivision
  20558. for ( let i = 0; i <= cols; i ++ ) {
  20559. v[ i ] = [];
  20560. const aj = a.clone().lerp( c, i / cols );
  20561. const bj = b.clone().lerp( c, i / cols );
  20562. const rows = cols - i;
  20563. for ( let j = 0; j <= rows; j ++ ) {
  20564. if ( j === 0 && i === cols ) {
  20565. v[ i ][ j ] = aj;
  20566. } else {
  20567. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20568. }
  20569. }
  20570. }
  20571. // construct all of the faces
  20572. for ( let i = 0; i < cols; i ++ ) {
  20573. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20574. const k = Math.floor( j / 2 );
  20575. if ( j % 2 === 0 ) {
  20576. pushVertex( v[ i ][ k + 1 ] );
  20577. pushVertex( v[ i + 1 ][ k ] );
  20578. pushVertex( v[ i ][ k ] );
  20579. } else {
  20580. pushVertex( v[ i ][ k + 1 ] );
  20581. pushVertex( v[ i + 1 ][ k + 1 ] );
  20582. pushVertex( v[ i + 1 ][ k ] );
  20583. }
  20584. }
  20585. }
  20586. }
  20587. function applyRadius( radius ) {
  20588. const vertex = new Vector3();
  20589. // iterate over the entire buffer and apply the radius to each vertex
  20590. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20591. vertex.x = vertexBuffer[ i + 0 ];
  20592. vertex.y = vertexBuffer[ i + 1 ];
  20593. vertex.z = vertexBuffer[ i + 2 ];
  20594. vertex.normalize().multiplyScalar( radius );
  20595. vertexBuffer[ i + 0 ] = vertex.x;
  20596. vertexBuffer[ i + 1 ] = vertex.y;
  20597. vertexBuffer[ i + 2 ] = vertex.z;
  20598. }
  20599. }
  20600. function generateUVs() {
  20601. const vertex = new Vector3();
  20602. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20603. vertex.x = vertexBuffer[ i + 0 ];
  20604. vertex.y = vertexBuffer[ i + 1 ];
  20605. vertex.z = vertexBuffer[ i + 2 ];
  20606. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20607. const v = inclination( vertex ) / Math.PI + 0.5;
  20608. uvBuffer.push( u, 1 - v );
  20609. }
  20610. correctUVs();
  20611. correctSeam();
  20612. }
  20613. function correctSeam() {
  20614. // handle case when face straddles the seam, see #3269
  20615. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20616. // uv data of a single face
  20617. const x0 = uvBuffer[ i + 0 ];
  20618. const x1 = uvBuffer[ i + 2 ];
  20619. const x2 = uvBuffer[ i + 4 ];
  20620. const max = Math.max( x0, x1, x2 );
  20621. const min = Math.min( x0, x1, x2 );
  20622. // 0.9 is somewhat arbitrary
  20623. if ( max > 0.9 && min < 0.1 ) {
  20624. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20625. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20626. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20627. }
  20628. }
  20629. }
  20630. function pushVertex( vertex ) {
  20631. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20632. }
  20633. function getVertexByIndex( index, vertex ) {
  20634. const stride = index * 3;
  20635. vertex.x = vertices[ stride + 0 ];
  20636. vertex.y = vertices[ stride + 1 ];
  20637. vertex.z = vertices[ stride + 2 ];
  20638. }
  20639. function correctUVs() {
  20640. const a = new Vector3();
  20641. const b = new Vector3();
  20642. const c = new Vector3();
  20643. const centroid = new Vector3();
  20644. const uvA = new Vector2();
  20645. const uvB = new Vector2();
  20646. const uvC = new Vector2();
  20647. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20648. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20649. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20650. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20651. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20652. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20653. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20654. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20655. const azi = azimuth( centroid );
  20656. correctUV( uvA, j + 0, a, azi );
  20657. correctUV( uvB, j + 2, b, azi );
  20658. correctUV( uvC, j + 4, c, azi );
  20659. }
  20660. }
  20661. function correctUV( uv, stride, vector, azimuth ) {
  20662. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20663. uvBuffer[ stride ] = uv.x - 1;
  20664. }
  20665. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20666. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20667. }
  20668. }
  20669. // Angle around the Y axis, counter-clockwise when looking from above.
  20670. function azimuth( vector ) {
  20671. return Math.atan2( vector.z, - vector.x );
  20672. }
  20673. // Angle above the XZ plane.
  20674. function inclination( vector ) {
  20675. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20676. }
  20677. }
  20678. copy( source ) {
  20679. super.copy( source );
  20680. this.parameters = Object.assign( {}, source.parameters );
  20681. return this;
  20682. }
  20683. static fromJSON( data ) {
  20684. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20685. }
  20686. }
  20687. class DodecahedronGeometry extends PolyhedronGeometry {
  20688. constructor( radius = 1, detail = 0 ) {
  20689. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20690. const r = 1 / t;
  20691. const vertices = [
  20692. // (±1, ±1, ±1)
  20693. - 1, - 1, - 1, - 1, - 1, 1,
  20694. - 1, 1, - 1, - 1, 1, 1,
  20695. 1, - 1, - 1, 1, - 1, 1,
  20696. 1, 1, - 1, 1, 1, 1,
  20697. // (0, ±1/φ, ±φ)
  20698. 0, - r, - t, 0, - r, t,
  20699. 0, r, - t, 0, r, t,
  20700. // (±1/φ, ±φ, 0)
  20701. - r, - t, 0, - r, t, 0,
  20702. r, - t, 0, r, t, 0,
  20703. // (±φ, 0, ±1/φ)
  20704. - t, 0, - r, t, 0, - r,
  20705. - t, 0, r, t, 0, r
  20706. ];
  20707. const indices = [
  20708. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20709. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20710. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20711. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20712. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20713. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20714. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20715. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20716. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20717. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20718. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20719. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20720. ];
  20721. super( vertices, indices, radius, detail );
  20722. this.type = 'DodecahedronGeometry';
  20723. this.parameters = {
  20724. radius: radius,
  20725. detail: detail
  20726. };
  20727. }
  20728. static fromJSON( data ) {
  20729. return new DodecahedronGeometry( data.radius, data.detail );
  20730. }
  20731. }
  20732. const _v0 = /*@__PURE__*/ new Vector3();
  20733. const _v1$1 = /*@__PURE__*/ new Vector3();
  20734. const _normal = /*@__PURE__*/ new Vector3();
  20735. const _triangle = /*@__PURE__*/ new Triangle();
  20736. class EdgesGeometry extends BufferGeometry {
  20737. constructor( geometry = null, thresholdAngle = 1 ) {
  20738. super();
  20739. this.type = 'EdgesGeometry';
  20740. this.parameters = {
  20741. geometry: geometry,
  20742. thresholdAngle: thresholdAngle
  20743. };
  20744. if ( geometry !== null ) {
  20745. const precisionPoints = 4;
  20746. const precision = Math.pow( 10, precisionPoints );
  20747. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20748. const indexAttr = geometry.getIndex();
  20749. const positionAttr = geometry.getAttribute( 'position' );
  20750. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20751. const indexArr = [ 0, 0, 0 ];
  20752. const vertKeys = [ 'a', 'b', 'c' ];
  20753. const hashes = new Array( 3 );
  20754. const edgeData = {};
  20755. const vertices = [];
  20756. for ( let i = 0; i < indexCount; i += 3 ) {
  20757. if ( indexAttr ) {
  20758. indexArr[ 0 ] = indexAttr.getX( i );
  20759. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20760. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20761. } else {
  20762. indexArr[ 0 ] = i;
  20763. indexArr[ 1 ] = i + 1;
  20764. indexArr[ 2 ] = i + 2;
  20765. }
  20766. const { a, b, c } = _triangle;
  20767. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20768. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20769. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20770. _triangle.getNormal( _normal );
  20771. // create hashes for the edge from the vertices
  20772. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20773. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20774. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20775. // skip degenerate triangles
  20776. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20777. continue;
  20778. }
  20779. // iterate over every edge
  20780. for ( let j = 0; j < 3; j ++ ) {
  20781. // get the first and next vertex making up the edge
  20782. const jNext = ( j + 1 ) % 3;
  20783. const vecHash0 = hashes[ j ];
  20784. const vecHash1 = hashes[ jNext ];
  20785. const v0 = _triangle[ vertKeys[ j ] ];
  20786. const v1 = _triangle[ vertKeys[ jNext ] ];
  20787. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20788. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20789. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20790. // if we found a sibling edge add it into the vertex array if
  20791. // it meets the angle threshold and delete the edge from the map.
  20792. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20793. vertices.push( v0.x, v0.y, v0.z );
  20794. vertices.push( v1.x, v1.y, v1.z );
  20795. }
  20796. edgeData[ reverseHash ] = null;
  20797. } else if ( ! ( hash in edgeData ) ) {
  20798. // if we've already got an edge here then skip adding a new one
  20799. edgeData[ hash ] = {
  20800. index0: indexArr[ j ],
  20801. index1: indexArr[ jNext ],
  20802. normal: _normal.clone(),
  20803. };
  20804. }
  20805. }
  20806. }
  20807. // iterate over all remaining, unmatched edges and add them to the vertex array
  20808. for ( const key in edgeData ) {
  20809. if ( edgeData[ key ] ) {
  20810. const { index0, index1 } = edgeData[ key ];
  20811. _v0.fromBufferAttribute( positionAttr, index0 );
  20812. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20813. vertices.push( _v0.x, _v0.y, _v0.z );
  20814. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20815. }
  20816. }
  20817. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20818. }
  20819. }
  20820. copy( source ) {
  20821. super.copy( source );
  20822. this.parameters = Object.assign( {}, source.parameters );
  20823. return this;
  20824. }
  20825. }
  20826. class Shape extends Path {
  20827. constructor( points ) {
  20828. super( points );
  20829. this.uuid = generateUUID();
  20830. this.type = 'Shape';
  20831. this.holes = [];
  20832. }
  20833. getPointsHoles( divisions ) {
  20834. const holesPts = [];
  20835. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20836. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20837. }
  20838. return holesPts;
  20839. }
  20840. // get points of shape and holes (keypoints based on segments parameter)
  20841. extractPoints( divisions ) {
  20842. return {
  20843. shape: this.getPoints( divisions ),
  20844. holes: this.getPointsHoles( divisions )
  20845. };
  20846. }
  20847. copy( source ) {
  20848. super.copy( source );
  20849. this.holes = [];
  20850. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20851. const hole = source.holes[ i ];
  20852. this.holes.push( hole.clone() );
  20853. }
  20854. return this;
  20855. }
  20856. toJSON() {
  20857. const data = super.toJSON();
  20858. data.uuid = this.uuid;
  20859. data.holes = [];
  20860. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20861. const hole = this.holes[ i ];
  20862. data.holes.push( hole.toJSON() );
  20863. }
  20864. return data;
  20865. }
  20866. fromJSON( json ) {
  20867. super.fromJSON( json );
  20868. this.uuid = json.uuid;
  20869. this.holes = [];
  20870. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20871. const hole = json.holes[ i ];
  20872. this.holes.push( new Path().fromJSON( hole ) );
  20873. }
  20874. return this;
  20875. }
  20876. }
  20877. /**
  20878. * Port from https://github.com/mapbox/earcut (v2.2.4)
  20879. */
  20880. const Earcut = {
  20881. triangulate: function ( data, holeIndices, dim = 2 ) {
  20882. const hasHoles = holeIndices && holeIndices.length;
  20883. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20884. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20885. const triangles = [];
  20886. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20887. let minX, minY, maxX, maxY, x, y, invSize;
  20888. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20889. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20890. if ( data.length > 80 * dim ) {
  20891. minX = maxX = data[ 0 ];
  20892. minY = maxY = data[ 1 ];
  20893. for ( let i = dim; i < outerLen; i += dim ) {
  20894. x = data[ i ];
  20895. y = data[ i + 1 ];
  20896. if ( x < minX ) minX = x;
  20897. if ( y < minY ) minY = y;
  20898. if ( x > maxX ) maxX = x;
  20899. if ( y > maxY ) maxY = y;
  20900. }
  20901. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20902. invSize = Math.max( maxX - minX, maxY - minY );
  20903. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20904. }
  20905. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  20906. return triangles;
  20907. }
  20908. };
  20909. // create a circular doubly linked list from polygon points in the specified winding order
  20910. function linkedList( data, start, end, dim, clockwise ) {
  20911. let i, last;
  20912. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20913. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20914. } else {
  20915. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20916. }
  20917. if ( last && equals( last, last.next ) ) {
  20918. removeNode( last );
  20919. last = last.next;
  20920. }
  20921. return last;
  20922. }
  20923. // eliminate colinear or duplicate points
  20924. function filterPoints( start, end ) {
  20925. if ( ! start ) return start;
  20926. if ( ! end ) end = start;
  20927. let p = start,
  20928. again;
  20929. do {
  20930. again = false;
  20931. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20932. removeNode( p );
  20933. p = end = p.prev;
  20934. if ( p === p.next ) break;
  20935. again = true;
  20936. } else {
  20937. p = p.next;
  20938. }
  20939. } while ( again || p !== end );
  20940. return end;
  20941. }
  20942. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20943. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20944. if ( ! ear ) return;
  20945. // interlink polygon nodes in z-order
  20946. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20947. let stop = ear,
  20948. prev, next;
  20949. // iterate through ears, slicing them one by one
  20950. while ( ear.prev !== ear.next ) {
  20951. prev = ear.prev;
  20952. next = ear.next;
  20953. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20954. // cut off the triangle
  20955. triangles.push( prev.i / dim | 0 );
  20956. triangles.push( ear.i / dim | 0 );
  20957. triangles.push( next.i / dim | 0 );
  20958. removeNode( ear );
  20959. // skipping the next vertex leads to less sliver triangles
  20960. ear = next.next;
  20961. stop = next.next;
  20962. continue;
  20963. }
  20964. ear = next;
  20965. // if we looped through the whole remaining polygon and can't find any more ears
  20966. if ( ear === stop ) {
  20967. // try filtering points and slicing again
  20968. if ( ! pass ) {
  20969. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20970. // if this didn't work, try curing all small self-intersections locally
  20971. } else if ( pass === 1 ) {
  20972. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20973. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20974. // as a last resort, try splitting the remaining polygon into two
  20975. } else if ( pass === 2 ) {
  20976. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20977. }
  20978. break;
  20979. }
  20980. }
  20981. }
  20982. // check whether a polygon node forms a valid ear with adjacent nodes
  20983. function isEar( ear ) {
  20984. const a = ear.prev,
  20985. b = ear,
  20986. c = ear.next;
  20987. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20988. // now make sure we don't have other points inside the potential ear
  20989. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20990. // triangle bbox; min & max are calculated like this for speed
  20991. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20992. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20993. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20994. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20995. let p = c.next;
  20996. while ( p !== a ) {
  20997. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  20998. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  20999. area( p.prev, p, p.next ) >= 0 ) return false;
  21000. p = p.next;
  21001. }
  21002. return true;
  21003. }
  21004. function isEarHashed( ear, minX, minY, invSize ) {
  21005. const a = ear.prev,
  21006. b = ear,
  21007. c = ear.next;
  21008. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21009. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  21010. // triangle bbox; min & max are calculated like this for speed
  21011. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  21012. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  21013. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  21014. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  21015. // z-order range for the current triangle bbox;
  21016. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  21017. maxZ = zOrder( x1, y1, minX, minY, invSize );
  21018. let p = ear.prevZ,
  21019. n = ear.nextZ;
  21020. // look for points inside the triangle in both directions
  21021. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  21022. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  21023. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  21024. p = p.prevZ;
  21025. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  21026. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  21027. n = n.nextZ;
  21028. }
  21029. // look for remaining points in decreasing z-order
  21030. while ( p && p.z >= minZ ) {
  21031. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  21032. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  21033. p = p.prevZ;
  21034. }
  21035. // look for remaining points in increasing z-order
  21036. while ( n && n.z <= maxZ ) {
  21037. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  21038. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  21039. n = n.nextZ;
  21040. }
  21041. return true;
  21042. }
  21043. // go through all polygon nodes and cure small local self-intersections
  21044. function cureLocalIntersections( start, triangles, dim ) {
  21045. let p = start;
  21046. do {
  21047. const a = p.prev,
  21048. b = p.next.next;
  21049. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  21050. triangles.push( a.i / dim | 0 );
  21051. triangles.push( p.i / dim | 0 );
  21052. triangles.push( b.i / dim | 0 );
  21053. // remove two nodes involved
  21054. removeNode( p );
  21055. removeNode( p.next );
  21056. p = start = b;
  21057. }
  21058. p = p.next;
  21059. } while ( p !== start );
  21060. return filterPoints( p );
  21061. }
  21062. // try splitting polygon into two and triangulate them independently
  21063. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  21064. // look for a valid diagonal that divides the polygon into two
  21065. let a = start;
  21066. do {
  21067. let b = a.next.next;
  21068. while ( b !== a.prev ) {
  21069. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  21070. // split the polygon in two by the diagonal
  21071. let c = splitPolygon( a, b );
  21072. // filter colinear points around the cuts
  21073. a = filterPoints( a, a.next );
  21074. c = filterPoints( c, c.next );
  21075. // run earcut on each half
  21076. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  21077. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  21078. return;
  21079. }
  21080. b = b.next;
  21081. }
  21082. a = a.next;
  21083. } while ( a !== start );
  21084. }
  21085. // link every hole into the outer loop, producing a single-ring polygon without holes
  21086. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  21087. const queue = [];
  21088. let i, len, start, end, list;
  21089. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  21090. start = holeIndices[ i ] * dim;
  21091. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  21092. list = linkedList( data, start, end, dim, false );
  21093. if ( list === list.next ) list.steiner = true;
  21094. queue.push( getLeftmost( list ) );
  21095. }
  21096. queue.sort( compareX );
  21097. // process holes from left to right
  21098. for ( i = 0; i < queue.length; i ++ ) {
  21099. outerNode = eliminateHole( queue[ i ], outerNode );
  21100. }
  21101. return outerNode;
  21102. }
  21103. function compareX( a, b ) {
  21104. return a.x - b.x;
  21105. }
  21106. // find a bridge between vertices that connects hole with an outer ring and link it
  21107. function eliminateHole( hole, outerNode ) {
  21108. const bridge = findHoleBridge( hole, outerNode );
  21109. if ( ! bridge ) {
  21110. return outerNode;
  21111. }
  21112. const bridgeReverse = splitPolygon( bridge, hole );
  21113. // filter collinear points around the cuts
  21114. filterPoints( bridgeReverse, bridgeReverse.next );
  21115. return filterPoints( bridge, bridge.next );
  21116. }
  21117. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  21118. function findHoleBridge( hole, outerNode ) {
  21119. let p = outerNode,
  21120. qx = - Infinity,
  21121. m;
  21122. const hx = hole.x, hy = hole.y;
  21123. // find a segment intersected by a ray from the hole's leftmost point to the left;
  21124. // segment's endpoint with lesser x will be potential connection point
  21125. do {
  21126. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  21127. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  21128. if ( x <= hx && x > qx ) {
  21129. qx = x;
  21130. m = p.x < p.next.x ? p : p.next;
  21131. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  21132. }
  21133. }
  21134. p = p.next;
  21135. } while ( p !== outerNode );
  21136. if ( ! m ) return null;
  21137. // look for points inside the triangle of hole point, segment intersection and endpoint;
  21138. // if there are no points found, we have a valid connection;
  21139. // otherwise choose the point of the minimum angle with the ray as connection point
  21140. const stop = m,
  21141. mx = m.x,
  21142. my = m.y;
  21143. let tanMin = Infinity, tan;
  21144. p = m;
  21145. do {
  21146. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  21147. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  21148. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  21149. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  21150. m = p;
  21151. tanMin = tan;
  21152. }
  21153. }
  21154. p = p.next;
  21155. } while ( p !== stop );
  21156. return m;
  21157. }
  21158. // whether sector in vertex m contains sector in vertex p in the same coordinates
  21159. function sectorContainsSector( m, p ) {
  21160. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  21161. }
  21162. // interlink polygon nodes in z-order
  21163. function indexCurve( start, minX, minY, invSize ) {
  21164. let p = start;
  21165. do {
  21166. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  21167. p.prevZ = p.prev;
  21168. p.nextZ = p.next;
  21169. p = p.next;
  21170. } while ( p !== start );
  21171. p.prevZ.nextZ = null;
  21172. p.prevZ = null;
  21173. sortLinked( p );
  21174. }
  21175. // Simon Tatham's linked list merge sort algorithm
  21176. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  21177. function sortLinked( list ) {
  21178. let i, p, q, e, tail, numMerges, pSize, qSize,
  21179. inSize = 1;
  21180. do {
  21181. p = list;
  21182. list = null;
  21183. tail = null;
  21184. numMerges = 0;
  21185. while ( p ) {
  21186. numMerges ++;
  21187. q = p;
  21188. pSize = 0;
  21189. for ( i = 0; i < inSize; i ++ ) {
  21190. pSize ++;
  21191. q = q.nextZ;
  21192. if ( ! q ) break;
  21193. }
  21194. qSize = inSize;
  21195. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  21196. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  21197. e = p;
  21198. p = p.nextZ;
  21199. pSize --;
  21200. } else {
  21201. e = q;
  21202. q = q.nextZ;
  21203. qSize --;
  21204. }
  21205. if ( tail ) tail.nextZ = e;
  21206. else list = e;
  21207. e.prevZ = tail;
  21208. tail = e;
  21209. }
  21210. p = q;
  21211. }
  21212. tail.nextZ = null;
  21213. inSize *= 2;
  21214. } while ( numMerges > 1 );
  21215. return list;
  21216. }
  21217. // z-order of a point given coords and inverse of the longer side of data bbox
  21218. function zOrder( x, y, minX, minY, invSize ) {
  21219. // coords are transformed into non-negative 15-bit integer range
  21220. x = ( x - minX ) * invSize | 0;
  21221. y = ( y - minY ) * invSize | 0;
  21222. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  21223. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  21224. x = ( x | ( x << 2 ) ) & 0x33333333;
  21225. x = ( x | ( x << 1 ) ) & 0x55555555;
  21226. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  21227. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  21228. y = ( y | ( y << 2 ) ) & 0x33333333;
  21229. y = ( y | ( y << 1 ) ) & 0x55555555;
  21230. return x | ( y << 1 );
  21231. }
  21232. // find the leftmost node of a polygon ring
  21233. function getLeftmost( start ) {
  21234. let p = start,
  21235. leftmost = start;
  21236. do {
  21237. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  21238. p = p.next;
  21239. } while ( p !== start );
  21240. return leftmost;
  21241. }
  21242. // check if a point lies within a convex triangle
  21243. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  21244. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  21245. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  21246. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  21247. }
  21248. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  21249. function isValidDiagonal( a, b ) {
  21250. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  21251. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  21252. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  21253. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  21254. }
  21255. // signed area of a triangle
  21256. function area( p, q, r ) {
  21257. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  21258. }
  21259. // check if two points are equal
  21260. function equals( p1, p2 ) {
  21261. return p1.x === p2.x && p1.y === p2.y;
  21262. }
  21263. // check if two segments intersect
  21264. function intersects( p1, q1, p2, q2 ) {
  21265. const o1 = sign( area( p1, q1, p2 ) );
  21266. const o2 = sign( area( p1, q1, q2 ) );
  21267. const o3 = sign( area( p2, q2, p1 ) );
  21268. const o4 = sign( area( p2, q2, q1 ) );
  21269. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  21270. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  21271. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  21272. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  21273. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  21274. return false;
  21275. }
  21276. // for collinear points p, q, r, check if point q lies on segment pr
  21277. function onSegment( p, q, r ) {
  21278. 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 );
  21279. }
  21280. function sign( num ) {
  21281. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  21282. }
  21283. // check if a polygon diagonal intersects any polygon segments
  21284. function intersectsPolygon( a, b ) {
  21285. let p = a;
  21286. do {
  21287. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  21288. intersects( p, p.next, a, b ) ) return true;
  21289. p = p.next;
  21290. } while ( p !== a );
  21291. return false;
  21292. }
  21293. // check if a polygon diagonal is locally inside the polygon
  21294. function locallyInside( a, b ) {
  21295. return area( a.prev, a, a.next ) < 0 ?
  21296. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  21297. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  21298. }
  21299. // check if the middle point of a polygon diagonal is inside the polygon
  21300. function middleInside( a, b ) {
  21301. let p = a,
  21302. inside = false;
  21303. const px = ( a.x + b.x ) / 2,
  21304. py = ( a.y + b.y ) / 2;
  21305. do {
  21306. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  21307. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  21308. inside = ! inside;
  21309. p = p.next;
  21310. } while ( p !== a );
  21311. return inside;
  21312. }
  21313. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  21314. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  21315. function splitPolygon( a, b ) {
  21316. const a2 = new Node( a.i, a.x, a.y ),
  21317. b2 = new Node( b.i, b.x, b.y ),
  21318. an = a.next,
  21319. bp = b.prev;
  21320. a.next = b;
  21321. b.prev = a;
  21322. a2.next = an;
  21323. an.prev = a2;
  21324. b2.next = a2;
  21325. a2.prev = b2;
  21326. bp.next = b2;
  21327. b2.prev = bp;
  21328. return b2;
  21329. }
  21330. // create a node and optionally link it with previous one (in a circular doubly linked list)
  21331. function insertNode( i, x, y, last ) {
  21332. const p = new Node( i, x, y );
  21333. if ( ! last ) {
  21334. p.prev = p;
  21335. p.next = p;
  21336. } else {
  21337. p.next = last.next;
  21338. p.prev = last;
  21339. last.next.prev = p;
  21340. last.next = p;
  21341. }
  21342. return p;
  21343. }
  21344. function removeNode( p ) {
  21345. p.next.prev = p.prev;
  21346. p.prev.next = p.next;
  21347. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  21348. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  21349. }
  21350. function Node( i, x, y ) {
  21351. // vertex index in coordinates array
  21352. this.i = i;
  21353. // vertex coordinates
  21354. this.x = x;
  21355. this.y = y;
  21356. // previous and next vertex nodes in a polygon ring
  21357. this.prev = null;
  21358. this.next = null;
  21359. // z-order curve value
  21360. this.z = 0;
  21361. // previous and next nodes in z-order
  21362. this.prevZ = null;
  21363. this.nextZ = null;
  21364. // indicates whether this is a steiner point
  21365. this.steiner = false;
  21366. }
  21367. function signedArea( data, start, end, dim ) {
  21368. let sum = 0;
  21369. for ( let i = start, j = end - dim; i < end; i += dim ) {
  21370. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  21371. j = i;
  21372. }
  21373. return sum;
  21374. }
  21375. class ShapeUtils {
  21376. // calculate area of the contour polygon
  21377. static area( contour ) {
  21378. const n = contour.length;
  21379. let a = 0.0;
  21380. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  21381. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  21382. }
  21383. return a * 0.5;
  21384. }
  21385. static isClockWise( pts ) {
  21386. return ShapeUtils.area( pts ) < 0;
  21387. }
  21388. static triangulateShape( contour, holes ) {
  21389. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  21390. const holeIndices = []; // array of hole indices
  21391. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  21392. removeDupEndPts( contour );
  21393. addContour( vertices, contour );
  21394. //
  21395. let holeIndex = contour.length;
  21396. holes.forEach( removeDupEndPts );
  21397. for ( let i = 0; i < holes.length; i ++ ) {
  21398. holeIndices.push( holeIndex );
  21399. holeIndex += holes[ i ].length;
  21400. addContour( vertices, holes[ i ] );
  21401. }
  21402. //
  21403. const triangles = Earcut.triangulate( vertices, holeIndices );
  21404. //
  21405. for ( let i = 0; i < triangles.length; i += 3 ) {
  21406. faces.push( triangles.slice( i, i + 3 ) );
  21407. }
  21408. return faces;
  21409. }
  21410. }
  21411. function removeDupEndPts( points ) {
  21412. const l = points.length;
  21413. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  21414. points.pop();
  21415. }
  21416. }
  21417. function addContour( vertices, contour ) {
  21418. for ( let i = 0; i < contour.length; i ++ ) {
  21419. vertices.push( contour[ i ].x );
  21420. vertices.push( contour[ i ].y );
  21421. }
  21422. }
  21423. /**
  21424. * Creates extruded geometry from a path shape.
  21425. *
  21426. * parameters = {
  21427. *
  21428. * curveSegments: <int>, // number of points on the curves
  21429. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21430. * depth: <float>, // Depth to extrude the shape
  21431. *
  21432. * bevelEnabled: <bool>, // turn on bevel
  21433. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21434. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21435. * bevelOffset: <float>, // how far from shape outline does bevel start
  21436. * bevelSegments: <int>, // number of bevel layers
  21437. *
  21438. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21439. *
  21440. * UVGenerator: <Object> // object that provides UV generator functions
  21441. *
  21442. * }
  21443. */
  21444. class ExtrudeGeometry extends BufferGeometry {
  21445. 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 = {} ) {
  21446. super();
  21447. this.type = 'ExtrudeGeometry';
  21448. this.parameters = {
  21449. shapes: shapes,
  21450. options: options
  21451. };
  21452. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21453. const scope = this;
  21454. const verticesArray = [];
  21455. const uvArray = [];
  21456. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21457. const shape = shapes[ i ];
  21458. addShape( shape );
  21459. }
  21460. // build geometry
  21461. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21462. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21463. this.computeVertexNormals();
  21464. // functions
  21465. function addShape( shape ) {
  21466. const placeholder = [];
  21467. // options
  21468. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21469. const steps = options.steps !== undefined ? options.steps : 1;
  21470. const depth = options.depth !== undefined ? options.depth : 1;
  21471. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21472. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21473. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21474. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21475. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21476. const extrudePath = options.extrudePath;
  21477. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21478. //
  21479. let extrudePts, extrudeByPath = false;
  21480. let splineTube, binormal, normal, position2;
  21481. if ( extrudePath ) {
  21482. extrudePts = extrudePath.getSpacedPoints( steps );
  21483. extrudeByPath = true;
  21484. bevelEnabled = false; // bevels not supported for path extrusion
  21485. // SETUP TNB variables
  21486. // TODO1 - have a .isClosed in spline?
  21487. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21488. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21489. binormal = new Vector3();
  21490. normal = new Vector3();
  21491. position2 = new Vector3();
  21492. }
  21493. // Safeguards if bevels are not enabled
  21494. if ( ! bevelEnabled ) {
  21495. bevelSegments = 0;
  21496. bevelThickness = 0;
  21497. bevelSize = 0;
  21498. bevelOffset = 0;
  21499. }
  21500. // Variables initialization
  21501. const shapePoints = shape.extractPoints( curveSegments );
  21502. let vertices = shapePoints.shape;
  21503. const holes = shapePoints.holes;
  21504. const reverse = ! ShapeUtils.isClockWise( vertices );
  21505. if ( reverse ) {
  21506. vertices = vertices.reverse();
  21507. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21508. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21509. const ahole = holes[ h ];
  21510. if ( ShapeUtils.isClockWise( ahole ) ) {
  21511. holes[ h ] = ahole.reverse();
  21512. }
  21513. }
  21514. }
  21515. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21516. /* Vertices */
  21517. const contour = vertices; // vertices has all points but contour has only points of circumference
  21518. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21519. const ahole = holes[ h ];
  21520. vertices = vertices.concat( ahole );
  21521. }
  21522. function scalePt2( pt, vec, size ) {
  21523. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21524. return pt.clone().addScaledVector( vec, size );
  21525. }
  21526. const vlen = vertices.length, flen = faces.length;
  21527. // Find directions for point movement
  21528. function getBevelVec( inPt, inPrev, inNext ) {
  21529. // computes for inPt the corresponding point inPt' on a new contour
  21530. // shifted by 1 unit (length of normalized vector) to the left
  21531. // if we walk along contour clockwise, this new contour is outside the old one
  21532. //
  21533. // inPt' is the intersection of the two lines parallel to the two
  21534. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21535. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21536. // good reading for geometry algorithms (here: line-line intersection)
  21537. // http://geomalgorithms.com/a05-_intersect-1.html
  21538. const v_prev_x = inPt.x - inPrev.x,
  21539. v_prev_y = inPt.y - inPrev.y;
  21540. const v_next_x = inNext.x - inPt.x,
  21541. v_next_y = inNext.y - inPt.y;
  21542. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21543. // check for collinear edges
  21544. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21545. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21546. // not collinear
  21547. // length of vectors for normalizing
  21548. const v_prev_len = Math.sqrt( v_prev_lensq );
  21549. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21550. // shift adjacent points by unit vectors to the left
  21551. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21552. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21553. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21554. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21555. // scaling factor for v_prev to intersection point
  21556. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21557. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21558. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21559. // vector from inPt to intersection point
  21560. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21561. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21562. // Don't normalize!, otherwise sharp corners become ugly
  21563. // but prevent crazy spikes
  21564. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21565. if ( v_trans_lensq <= 2 ) {
  21566. return new Vector2( v_trans_x, v_trans_y );
  21567. } else {
  21568. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21569. }
  21570. } else {
  21571. // handle special case of collinear edges
  21572. let direction_eq = false; // assumes: opposite
  21573. if ( v_prev_x > Number.EPSILON ) {
  21574. if ( v_next_x > Number.EPSILON ) {
  21575. direction_eq = true;
  21576. }
  21577. } else {
  21578. if ( v_prev_x < - Number.EPSILON ) {
  21579. if ( v_next_x < - Number.EPSILON ) {
  21580. direction_eq = true;
  21581. }
  21582. } else {
  21583. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21584. direction_eq = true;
  21585. }
  21586. }
  21587. }
  21588. if ( direction_eq ) {
  21589. // console.log("Warning: lines are a straight sequence");
  21590. v_trans_x = - v_prev_y;
  21591. v_trans_y = v_prev_x;
  21592. shrink_by = Math.sqrt( v_prev_lensq );
  21593. } else {
  21594. // console.log("Warning: lines are a straight spike");
  21595. v_trans_x = v_prev_x;
  21596. v_trans_y = v_prev_y;
  21597. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21598. }
  21599. }
  21600. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21601. }
  21602. const contourMovements = [];
  21603. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21604. if ( j === il ) j = 0;
  21605. if ( k === il ) k = 0;
  21606. // (j)---(i)---(k)
  21607. // console.log('i,j,k', i, j , k)
  21608. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21609. }
  21610. const holesMovements = [];
  21611. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21612. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21613. const ahole = holes[ h ];
  21614. oneHoleMovements = [];
  21615. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21616. if ( j === il ) j = 0;
  21617. if ( k === il ) k = 0;
  21618. // (j)---(i)---(k)
  21619. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21620. }
  21621. holesMovements.push( oneHoleMovements );
  21622. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21623. }
  21624. // Loop bevelSegments, 1 for the front, 1 for the back
  21625. for ( let b = 0; b < bevelSegments; b ++ ) {
  21626. //for ( b = bevelSegments; b > 0; b -- ) {
  21627. const t = b / bevelSegments;
  21628. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21629. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21630. // contract shape
  21631. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21632. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21633. v( vert.x, vert.y, - z );
  21634. }
  21635. // expand holes
  21636. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21637. const ahole = holes[ h ];
  21638. oneHoleMovements = holesMovements[ h ];
  21639. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21640. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21641. v( vert.x, vert.y, - z );
  21642. }
  21643. }
  21644. }
  21645. const bs = bevelSize + bevelOffset;
  21646. // Back facing vertices
  21647. for ( let i = 0; i < vlen; i ++ ) {
  21648. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21649. if ( ! extrudeByPath ) {
  21650. v( vert.x, vert.y, 0 );
  21651. } else {
  21652. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21653. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21654. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21655. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21656. v( position2.x, position2.y, position2.z );
  21657. }
  21658. }
  21659. // Add stepped vertices...
  21660. // Including front facing vertices
  21661. for ( let s = 1; s <= steps; s ++ ) {
  21662. for ( let i = 0; i < vlen; i ++ ) {
  21663. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21664. if ( ! extrudeByPath ) {
  21665. v( vert.x, vert.y, depth / steps * s );
  21666. } else {
  21667. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21668. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21669. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21670. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21671. v( position2.x, position2.y, position2.z );
  21672. }
  21673. }
  21674. }
  21675. // Add bevel segments planes
  21676. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21677. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21678. const t = b / bevelSegments;
  21679. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21680. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21681. // contract shape
  21682. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21683. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21684. v( vert.x, vert.y, depth + z );
  21685. }
  21686. // expand holes
  21687. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21688. const ahole = holes[ h ];
  21689. oneHoleMovements = holesMovements[ h ];
  21690. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21691. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21692. if ( ! extrudeByPath ) {
  21693. v( vert.x, vert.y, depth + z );
  21694. } else {
  21695. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21696. }
  21697. }
  21698. }
  21699. }
  21700. /* Faces */
  21701. // Top and bottom faces
  21702. buildLidFaces();
  21703. // Sides faces
  21704. buildSideFaces();
  21705. ///// Internal functions
  21706. function buildLidFaces() {
  21707. const start = verticesArray.length / 3;
  21708. if ( bevelEnabled ) {
  21709. let layer = 0; // steps + 1
  21710. let offset = vlen * layer;
  21711. // Bottom faces
  21712. for ( let i = 0; i < flen; i ++ ) {
  21713. const face = faces[ i ];
  21714. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21715. }
  21716. layer = steps + bevelSegments * 2;
  21717. offset = vlen * layer;
  21718. // Top faces
  21719. for ( let i = 0; i < flen; i ++ ) {
  21720. const face = faces[ i ];
  21721. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21722. }
  21723. } else {
  21724. // Bottom faces
  21725. for ( let i = 0; i < flen; i ++ ) {
  21726. const face = faces[ i ];
  21727. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21728. }
  21729. // Top faces
  21730. for ( let i = 0; i < flen; i ++ ) {
  21731. const face = faces[ i ];
  21732. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21733. }
  21734. }
  21735. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21736. }
  21737. // Create faces for the z-sides of the shape
  21738. function buildSideFaces() {
  21739. const start = verticesArray.length / 3;
  21740. let layeroffset = 0;
  21741. sidewalls( contour, layeroffset );
  21742. layeroffset += contour.length;
  21743. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21744. const ahole = holes[ h ];
  21745. sidewalls( ahole, layeroffset );
  21746. //, true
  21747. layeroffset += ahole.length;
  21748. }
  21749. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21750. }
  21751. function sidewalls( contour, layeroffset ) {
  21752. let i = contour.length;
  21753. while ( -- i >= 0 ) {
  21754. const j = i;
  21755. let k = i - 1;
  21756. if ( k < 0 ) k = contour.length - 1;
  21757. //console.log('b', i,j, i-1, k,vertices.length);
  21758. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21759. const slen1 = vlen * s;
  21760. const slen2 = vlen * ( s + 1 );
  21761. const a = layeroffset + j + slen1,
  21762. b = layeroffset + k + slen1,
  21763. c = layeroffset + k + slen2,
  21764. d = layeroffset + j + slen2;
  21765. f4( a, b, c, d );
  21766. }
  21767. }
  21768. }
  21769. function v( x, y, z ) {
  21770. placeholder.push( x );
  21771. placeholder.push( y );
  21772. placeholder.push( z );
  21773. }
  21774. function f3( a, b, c ) {
  21775. addVertex( a );
  21776. addVertex( b );
  21777. addVertex( c );
  21778. const nextIndex = verticesArray.length / 3;
  21779. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21780. addUV( uvs[ 0 ] );
  21781. addUV( uvs[ 1 ] );
  21782. addUV( uvs[ 2 ] );
  21783. }
  21784. function f4( a, b, c, d ) {
  21785. addVertex( a );
  21786. addVertex( b );
  21787. addVertex( d );
  21788. addVertex( b );
  21789. addVertex( c );
  21790. addVertex( d );
  21791. const nextIndex = verticesArray.length / 3;
  21792. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21793. addUV( uvs[ 0 ] );
  21794. addUV( uvs[ 1 ] );
  21795. addUV( uvs[ 3 ] );
  21796. addUV( uvs[ 1 ] );
  21797. addUV( uvs[ 2 ] );
  21798. addUV( uvs[ 3 ] );
  21799. }
  21800. function addVertex( index ) {
  21801. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21802. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21803. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21804. }
  21805. function addUV( vector2 ) {
  21806. uvArray.push( vector2.x );
  21807. uvArray.push( vector2.y );
  21808. }
  21809. }
  21810. }
  21811. copy( source ) {
  21812. super.copy( source );
  21813. this.parameters = Object.assign( {}, source.parameters );
  21814. return this;
  21815. }
  21816. toJSON() {
  21817. const data = super.toJSON();
  21818. const shapes = this.parameters.shapes;
  21819. const options = this.parameters.options;
  21820. return toJSON$1( shapes, options, data );
  21821. }
  21822. static fromJSON( data, shapes ) {
  21823. const geometryShapes = [];
  21824. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21825. const shape = shapes[ data.shapes[ j ] ];
  21826. geometryShapes.push( shape );
  21827. }
  21828. const extrudePath = data.options.extrudePath;
  21829. if ( extrudePath !== undefined ) {
  21830. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21831. }
  21832. return new ExtrudeGeometry( geometryShapes, data.options );
  21833. }
  21834. }
  21835. const WorldUVGenerator = {
  21836. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21837. const a_x = vertices[ indexA * 3 ];
  21838. const a_y = vertices[ indexA * 3 + 1 ];
  21839. const b_x = vertices[ indexB * 3 ];
  21840. const b_y = vertices[ indexB * 3 + 1 ];
  21841. const c_x = vertices[ indexC * 3 ];
  21842. const c_y = vertices[ indexC * 3 + 1 ];
  21843. return [
  21844. new Vector2( a_x, a_y ),
  21845. new Vector2( b_x, b_y ),
  21846. new Vector2( c_x, c_y )
  21847. ];
  21848. },
  21849. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21850. const a_x = vertices[ indexA * 3 ];
  21851. const a_y = vertices[ indexA * 3 + 1 ];
  21852. const a_z = vertices[ indexA * 3 + 2 ];
  21853. const b_x = vertices[ indexB * 3 ];
  21854. const b_y = vertices[ indexB * 3 + 1 ];
  21855. const b_z = vertices[ indexB * 3 + 2 ];
  21856. const c_x = vertices[ indexC * 3 ];
  21857. const c_y = vertices[ indexC * 3 + 1 ];
  21858. const c_z = vertices[ indexC * 3 + 2 ];
  21859. const d_x = vertices[ indexD * 3 ];
  21860. const d_y = vertices[ indexD * 3 + 1 ];
  21861. const d_z = vertices[ indexD * 3 + 2 ];
  21862. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21863. return [
  21864. new Vector2( a_x, 1 - a_z ),
  21865. new Vector2( b_x, 1 - b_z ),
  21866. new Vector2( c_x, 1 - c_z ),
  21867. new Vector2( d_x, 1 - d_z )
  21868. ];
  21869. } else {
  21870. return [
  21871. new Vector2( a_y, 1 - a_z ),
  21872. new Vector2( b_y, 1 - b_z ),
  21873. new Vector2( c_y, 1 - c_z ),
  21874. new Vector2( d_y, 1 - d_z )
  21875. ];
  21876. }
  21877. }
  21878. };
  21879. function toJSON$1( shapes, options, data ) {
  21880. data.shapes = [];
  21881. if ( Array.isArray( shapes ) ) {
  21882. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21883. const shape = shapes[ i ];
  21884. data.shapes.push( shape.uuid );
  21885. }
  21886. } else {
  21887. data.shapes.push( shapes.uuid );
  21888. }
  21889. data.options = Object.assign( {}, options );
  21890. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21891. return data;
  21892. }
  21893. class IcosahedronGeometry extends PolyhedronGeometry {
  21894. constructor( radius = 1, detail = 0 ) {
  21895. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21896. const vertices = [
  21897. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21898. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21899. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21900. ];
  21901. const indices = [
  21902. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21903. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21904. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21905. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21906. ];
  21907. super( vertices, indices, radius, detail );
  21908. this.type = 'IcosahedronGeometry';
  21909. this.parameters = {
  21910. radius: radius,
  21911. detail: detail
  21912. };
  21913. }
  21914. static fromJSON( data ) {
  21915. return new IcosahedronGeometry( data.radius, data.detail );
  21916. }
  21917. }
  21918. class OctahedronGeometry extends PolyhedronGeometry {
  21919. constructor( radius = 1, detail = 0 ) {
  21920. const vertices = [
  21921. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21922. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21923. ];
  21924. const indices = [
  21925. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21926. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21927. 1, 3, 4, 1, 4, 2
  21928. ];
  21929. super( vertices, indices, radius, detail );
  21930. this.type = 'OctahedronGeometry';
  21931. this.parameters = {
  21932. radius: radius,
  21933. detail: detail
  21934. };
  21935. }
  21936. static fromJSON( data ) {
  21937. return new OctahedronGeometry( data.radius, data.detail );
  21938. }
  21939. }
  21940. class RingGeometry extends BufferGeometry {
  21941. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21942. super();
  21943. this.type = 'RingGeometry';
  21944. this.parameters = {
  21945. innerRadius: innerRadius,
  21946. outerRadius: outerRadius,
  21947. thetaSegments: thetaSegments,
  21948. phiSegments: phiSegments,
  21949. thetaStart: thetaStart,
  21950. thetaLength: thetaLength
  21951. };
  21952. thetaSegments = Math.max( 3, thetaSegments );
  21953. phiSegments = Math.max( 1, phiSegments );
  21954. // buffers
  21955. const indices = [];
  21956. const vertices = [];
  21957. const normals = [];
  21958. const uvs = [];
  21959. // some helper variables
  21960. let radius = innerRadius;
  21961. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21962. const vertex = new Vector3();
  21963. const uv = new Vector2();
  21964. // generate vertices, normals and uvs
  21965. for ( let j = 0; j <= phiSegments; j ++ ) {
  21966. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21967. // values are generate from the inside of the ring to the outside
  21968. const segment = thetaStart + i / thetaSegments * thetaLength;
  21969. // vertex
  21970. vertex.x = radius * Math.cos( segment );
  21971. vertex.y = radius * Math.sin( segment );
  21972. vertices.push( vertex.x, vertex.y, vertex.z );
  21973. // normal
  21974. normals.push( 0, 0, 1 );
  21975. // uv
  21976. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21977. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21978. uvs.push( uv.x, uv.y );
  21979. }
  21980. // increase the radius for next row of vertices
  21981. radius += radiusStep;
  21982. }
  21983. // indices
  21984. for ( let j = 0; j < phiSegments; j ++ ) {
  21985. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21986. for ( let i = 0; i < thetaSegments; i ++ ) {
  21987. const segment = i + thetaSegmentLevel;
  21988. const a = segment;
  21989. const b = segment + thetaSegments + 1;
  21990. const c = segment + thetaSegments + 2;
  21991. const d = segment + 1;
  21992. // faces
  21993. indices.push( a, b, d );
  21994. indices.push( b, c, d );
  21995. }
  21996. }
  21997. // build geometry
  21998. this.setIndex( indices );
  21999. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22000. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22001. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22002. }
  22003. copy( source ) {
  22004. super.copy( source );
  22005. this.parameters = Object.assign( {}, source.parameters );
  22006. return this;
  22007. }
  22008. static fromJSON( data ) {
  22009. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  22010. }
  22011. }
  22012. class ShapeGeometry extends BufferGeometry {
  22013. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  22014. super();
  22015. this.type = 'ShapeGeometry';
  22016. this.parameters = {
  22017. shapes: shapes,
  22018. curveSegments: curveSegments
  22019. };
  22020. // buffers
  22021. const indices = [];
  22022. const vertices = [];
  22023. const normals = [];
  22024. const uvs = [];
  22025. // helper variables
  22026. let groupStart = 0;
  22027. let groupCount = 0;
  22028. // allow single and array values for "shapes" parameter
  22029. if ( Array.isArray( shapes ) === false ) {
  22030. addShape( shapes );
  22031. } else {
  22032. for ( let i = 0; i < shapes.length; i ++ ) {
  22033. addShape( shapes[ i ] );
  22034. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  22035. groupStart += groupCount;
  22036. groupCount = 0;
  22037. }
  22038. }
  22039. // build geometry
  22040. this.setIndex( indices );
  22041. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22042. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22043. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22044. // helper functions
  22045. function addShape( shape ) {
  22046. const indexOffset = vertices.length / 3;
  22047. const points = shape.extractPoints( curveSegments );
  22048. let shapeVertices = points.shape;
  22049. const shapeHoles = points.holes;
  22050. // check direction of vertices
  22051. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  22052. shapeVertices = shapeVertices.reverse();
  22053. }
  22054. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  22055. const shapeHole = shapeHoles[ i ];
  22056. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  22057. shapeHoles[ i ] = shapeHole.reverse();
  22058. }
  22059. }
  22060. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  22061. // join vertices of inner and outer paths to a single array
  22062. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  22063. const shapeHole = shapeHoles[ i ];
  22064. shapeVertices = shapeVertices.concat( shapeHole );
  22065. }
  22066. // vertices, normals, uvs
  22067. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  22068. const vertex = shapeVertices[ i ];
  22069. vertices.push( vertex.x, vertex.y, 0 );
  22070. normals.push( 0, 0, 1 );
  22071. uvs.push( vertex.x, vertex.y ); // world uvs
  22072. }
  22073. // indices
  22074. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  22075. const face = faces[ i ];
  22076. const a = face[ 0 ] + indexOffset;
  22077. const b = face[ 1 ] + indexOffset;
  22078. const c = face[ 2 ] + indexOffset;
  22079. indices.push( a, b, c );
  22080. groupCount += 3;
  22081. }
  22082. }
  22083. }
  22084. copy( source ) {
  22085. super.copy( source );
  22086. this.parameters = Object.assign( {}, source.parameters );
  22087. return this;
  22088. }
  22089. toJSON() {
  22090. const data = super.toJSON();
  22091. const shapes = this.parameters.shapes;
  22092. return toJSON( shapes, data );
  22093. }
  22094. static fromJSON( data, shapes ) {
  22095. const geometryShapes = [];
  22096. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  22097. const shape = shapes[ data.shapes[ j ] ];
  22098. geometryShapes.push( shape );
  22099. }
  22100. return new ShapeGeometry( geometryShapes, data.curveSegments );
  22101. }
  22102. }
  22103. function toJSON( shapes, data ) {
  22104. data.shapes = [];
  22105. if ( Array.isArray( shapes ) ) {
  22106. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22107. const shape = shapes[ i ];
  22108. data.shapes.push( shape.uuid );
  22109. }
  22110. } else {
  22111. data.shapes.push( shapes.uuid );
  22112. }
  22113. return data;
  22114. }
  22115. class SphereGeometry extends BufferGeometry {
  22116. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  22117. super();
  22118. this.type = 'SphereGeometry';
  22119. this.parameters = {
  22120. radius: radius,
  22121. widthSegments: widthSegments,
  22122. heightSegments: heightSegments,
  22123. phiStart: phiStart,
  22124. phiLength: phiLength,
  22125. thetaStart: thetaStart,
  22126. thetaLength: thetaLength
  22127. };
  22128. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  22129. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  22130. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  22131. let index = 0;
  22132. const grid = [];
  22133. const vertex = new Vector3();
  22134. const normal = new Vector3();
  22135. // buffers
  22136. const indices = [];
  22137. const vertices = [];
  22138. const normals = [];
  22139. const uvs = [];
  22140. // generate vertices, normals and uvs
  22141. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  22142. const verticesRow = [];
  22143. const v = iy / heightSegments;
  22144. // special case for the poles
  22145. let uOffset = 0;
  22146. if ( iy === 0 && thetaStart === 0 ) {
  22147. uOffset = 0.5 / widthSegments;
  22148. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  22149. uOffset = - 0.5 / widthSegments;
  22150. }
  22151. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  22152. const u = ix / widthSegments;
  22153. // vertex
  22154. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22155. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22156. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22157. vertices.push( vertex.x, vertex.y, vertex.z );
  22158. // normal
  22159. normal.copy( vertex ).normalize();
  22160. normals.push( normal.x, normal.y, normal.z );
  22161. // uv
  22162. uvs.push( u + uOffset, 1 - v );
  22163. verticesRow.push( index ++ );
  22164. }
  22165. grid.push( verticesRow );
  22166. }
  22167. // indices
  22168. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  22169. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  22170. const a = grid[ iy ][ ix + 1 ];
  22171. const b = grid[ iy ][ ix ];
  22172. const c = grid[ iy + 1 ][ ix ];
  22173. const d = grid[ iy + 1 ][ ix + 1 ];
  22174. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22175. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  22176. }
  22177. }
  22178. // build geometry
  22179. this.setIndex( indices );
  22180. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22181. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22182. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22183. }
  22184. copy( source ) {
  22185. super.copy( source );
  22186. this.parameters = Object.assign( {}, source.parameters );
  22187. return this;
  22188. }
  22189. static fromJSON( data ) {
  22190. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  22191. }
  22192. }
  22193. class TetrahedronGeometry extends PolyhedronGeometry {
  22194. constructor( radius = 1, detail = 0 ) {
  22195. const vertices = [
  22196. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22197. ];
  22198. const indices = [
  22199. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22200. ];
  22201. super( vertices, indices, radius, detail );
  22202. this.type = 'TetrahedronGeometry';
  22203. this.parameters = {
  22204. radius: radius,
  22205. detail: detail
  22206. };
  22207. }
  22208. static fromJSON( data ) {
  22209. return new TetrahedronGeometry( data.radius, data.detail );
  22210. }
  22211. }
  22212. class TorusGeometry extends BufferGeometry {
  22213. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  22214. super();
  22215. this.type = 'TorusGeometry';
  22216. this.parameters = {
  22217. radius: radius,
  22218. tube: tube,
  22219. radialSegments: radialSegments,
  22220. tubularSegments: tubularSegments,
  22221. arc: arc
  22222. };
  22223. radialSegments = Math.floor( radialSegments );
  22224. tubularSegments = Math.floor( tubularSegments );
  22225. // buffers
  22226. const indices = [];
  22227. const vertices = [];
  22228. const normals = [];
  22229. const uvs = [];
  22230. // helper variables
  22231. const center = new Vector3();
  22232. const vertex = new Vector3();
  22233. const normal = new Vector3();
  22234. // generate vertices, normals and uvs
  22235. for ( let j = 0; j <= radialSegments; j ++ ) {
  22236. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22237. const u = i / tubularSegments * arc;
  22238. const v = j / radialSegments * Math.PI * 2;
  22239. // vertex
  22240. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22241. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22242. vertex.z = tube * Math.sin( v );
  22243. vertices.push( vertex.x, vertex.y, vertex.z );
  22244. // normal
  22245. center.x = radius * Math.cos( u );
  22246. center.y = radius * Math.sin( u );
  22247. normal.subVectors( vertex, center ).normalize();
  22248. normals.push( normal.x, normal.y, normal.z );
  22249. // uv
  22250. uvs.push( i / tubularSegments );
  22251. uvs.push( j / radialSegments );
  22252. }
  22253. }
  22254. // generate indices
  22255. for ( let j = 1; j <= radialSegments; j ++ ) {
  22256. for ( let i = 1; i <= tubularSegments; i ++ ) {
  22257. // indices
  22258. const a = ( tubularSegments + 1 ) * j + i - 1;
  22259. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22260. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22261. const d = ( tubularSegments + 1 ) * j + i;
  22262. // faces
  22263. indices.push( a, b, d );
  22264. indices.push( b, c, d );
  22265. }
  22266. }
  22267. // build geometry
  22268. this.setIndex( indices );
  22269. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22270. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22271. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22272. }
  22273. copy( source ) {
  22274. super.copy( source );
  22275. this.parameters = Object.assign( {}, source.parameters );
  22276. return this;
  22277. }
  22278. static fromJSON( data ) {
  22279. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  22280. }
  22281. }
  22282. class TorusKnotGeometry extends BufferGeometry {
  22283. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  22284. super();
  22285. this.type = 'TorusKnotGeometry';
  22286. this.parameters = {
  22287. radius: radius,
  22288. tube: tube,
  22289. tubularSegments: tubularSegments,
  22290. radialSegments: radialSegments,
  22291. p: p,
  22292. q: q
  22293. };
  22294. tubularSegments = Math.floor( tubularSegments );
  22295. radialSegments = Math.floor( radialSegments );
  22296. // buffers
  22297. const indices = [];
  22298. const vertices = [];
  22299. const normals = [];
  22300. const uvs = [];
  22301. // helper variables
  22302. const vertex = new Vector3();
  22303. const normal = new Vector3();
  22304. const P1 = new Vector3();
  22305. const P2 = new Vector3();
  22306. const B = new Vector3();
  22307. const T = new Vector3();
  22308. const N = new Vector3();
  22309. // generate vertices, normals and uvs
  22310. for ( let i = 0; i <= tubularSegments; ++ i ) {
  22311. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  22312. const u = i / tubularSegments * p * Math.PI * 2;
  22313. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22314. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22315. calculatePositionOnCurve( u, p, q, radius, P1 );
  22316. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  22317. // calculate orthonormal basis
  22318. T.subVectors( P2, P1 );
  22319. N.addVectors( P2, P1 );
  22320. B.crossVectors( T, N );
  22321. N.crossVectors( B, T );
  22322. // normalize B, N. T can be ignored, we don't use it
  22323. B.normalize();
  22324. N.normalize();
  22325. for ( let j = 0; j <= radialSegments; ++ j ) {
  22326. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22327. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22328. const v = j / radialSegments * Math.PI * 2;
  22329. const cx = - tube * Math.cos( v );
  22330. const cy = tube * Math.sin( v );
  22331. // now calculate the final vertex position.
  22332. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  22333. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  22334. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  22335. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  22336. vertices.push( vertex.x, vertex.y, vertex.z );
  22337. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22338. normal.subVectors( vertex, P1 ).normalize();
  22339. normals.push( normal.x, normal.y, normal.z );
  22340. // uv
  22341. uvs.push( i / tubularSegments );
  22342. uvs.push( j / radialSegments );
  22343. }
  22344. }
  22345. // generate indices
  22346. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22347. for ( let i = 1; i <= radialSegments; i ++ ) {
  22348. // indices
  22349. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22350. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22351. const c = ( radialSegments + 1 ) * j + i;
  22352. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22353. // faces
  22354. indices.push( a, b, d );
  22355. indices.push( b, c, d );
  22356. }
  22357. }
  22358. // build geometry
  22359. this.setIndex( indices );
  22360. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22361. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22362. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22363. // this function calculates the current position on the torus curve
  22364. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22365. const cu = Math.cos( u );
  22366. const su = Math.sin( u );
  22367. const quOverP = q / p * u;
  22368. const cs = Math.cos( quOverP );
  22369. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22370. position.y = radius * ( 2 + cs ) * su * 0.5;
  22371. position.z = radius * Math.sin( quOverP ) * 0.5;
  22372. }
  22373. }
  22374. copy( source ) {
  22375. super.copy( source );
  22376. this.parameters = Object.assign( {}, source.parameters );
  22377. return this;
  22378. }
  22379. static fromJSON( data ) {
  22380. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  22381. }
  22382. }
  22383. class TubeGeometry extends BufferGeometry {
  22384. 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 ) {
  22385. super();
  22386. this.type = 'TubeGeometry';
  22387. this.parameters = {
  22388. path: path,
  22389. tubularSegments: tubularSegments,
  22390. radius: radius,
  22391. radialSegments: radialSegments,
  22392. closed: closed
  22393. };
  22394. const frames = path.computeFrenetFrames( tubularSegments, closed );
  22395. // expose internals
  22396. this.tangents = frames.tangents;
  22397. this.normals = frames.normals;
  22398. this.binormals = frames.binormals;
  22399. // helper variables
  22400. const vertex = new Vector3();
  22401. const normal = new Vector3();
  22402. const uv = new Vector2();
  22403. let P = new Vector3();
  22404. // buffer
  22405. const vertices = [];
  22406. const normals = [];
  22407. const uvs = [];
  22408. const indices = [];
  22409. // create buffer data
  22410. generateBufferData();
  22411. // build geometry
  22412. this.setIndex( indices );
  22413. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22414. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22415. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22416. // functions
  22417. function generateBufferData() {
  22418. for ( let i = 0; i < tubularSegments; i ++ ) {
  22419. generateSegment( i );
  22420. }
  22421. // if the geometry is not closed, generate the last row of vertices and normals
  22422. // at the regular position on the given path
  22423. //
  22424. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22425. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22426. // uvs are generated in a separate function.
  22427. // this makes it easy compute correct values for closed geometries
  22428. generateUVs();
  22429. // finally create faces
  22430. generateIndices();
  22431. }
  22432. function generateSegment( i ) {
  22433. // we use getPointAt to sample evenly distributed points from the given path
  22434. P = path.getPointAt( i / tubularSegments, P );
  22435. // retrieve corresponding normal and binormal
  22436. const N = frames.normals[ i ];
  22437. const B = frames.binormals[ i ];
  22438. // generate normals and vertices for the current segment
  22439. for ( let j = 0; j <= radialSegments; j ++ ) {
  22440. const v = j / radialSegments * Math.PI * 2;
  22441. const sin = Math.sin( v );
  22442. const cos = - Math.cos( v );
  22443. // normal
  22444. normal.x = ( cos * N.x + sin * B.x );
  22445. normal.y = ( cos * N.y + sin * B.y );
  22446. normal.z = ( cos * N.z + sin * B.z );
  22447. normal.normalize();
  22448. normals.push( normal.x, normal.y, normal.z );
  22449. // vertex
  22450. vertex.x = P.x + radius * normal.x;
  22451. vertex.y = P.y + radius * normal.y;
  22452. vertex.z = P.z + radius * normal.z;
  22453. vertices.push( vertex.x, vertex.y, vertex.z );
  22454. }
  22455. }
  22456. function generateIndices() {
  22457. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22458. for ( let i = 1; i <= radialSegments; i ++ ) {
  22459. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22460. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22461. const c = ( radialSegments + 1 ) * j + i;
  22462. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22463. // faces
  22464. indices.push( a, b, d );
  22465. indices.push( b, c, d );
  22466. }
  22467. }
  22468. }
  22469. function generateUVs() {
  22470. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22471. for ( let j = 0; j <= radialSegments; j ++ ) {
  22472. uv.x = i / tubularSegments;
  22473. uv.y = j / radialSegments;
  22474. uvs.push( uv.x, uv.y );
  22475. }
  22476. }
  22477. }
  22478. }
  22479. copy( source ) {
  22480. super.copy( source );
  22481. this.parameters = Object.assign( {}, source.parameters );
  22482. return this;
  22483. }
  22484. toJSON() {
  22485. const data = super.toJSON();
  22486. data.path = this.parameters.path.toJSON();
  22487. return data;
  22488. }
  22489. static fromJSON( data ) {
  22490. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22491. // User defined curves or instances of CurvePath will not be deserialized.
  22492. return new TubeGeometry(
  22493. new Curves[ data.path.type ]().fromJSON( data.path ),
  22494. data.tubularSegments,
  22495. data.radius,
  22496. data.radialSegments,
  22497. data.closed
  22498. );
  22499. }
  22500. }
  22501. class WireframeGeometry extends BufferGeometry {
  22502. constructor( geometry = null ) {
  22503. super();
  22504. this.type = 'WireframeGeometry';
  22505. this.parameters = {
  22506. geometry: geometry
  22507. };
  22508. if ( geometry !== null ) {
  22509. // buffer
  22510. const vertices = [];
  22511. const edges = new Set();
  22512. // helper variables
  22513. const start = new Vector3();
  22514. const end = new Vector3();
  22515. if ( geometry.index !== null ) {
  22516. // indexed BufferGeometry
  22517. const position = geometry.attributes.position;
  22518. const indices = geometry.index;
  22519. let groups = geometry.groups;
  22520. if ( groups.length === 0 ) {
  22521. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22522. }
  22523. // create a data structure that contains all edges without duplicates
  22524. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22525. const group = groups[ o ];
  22526. const groupStart = group.start;
  22527. const groupCount = group.count;
  22528. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22529. for ( let j = 0; j < 3; j ++ ) {
  22530. const index1 = indices.getX( i + j );
  22531. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22532. start.fromBufferAttribute( position, index1 );
  22533. end.fromBufferAttribute( position, index2 );
  22534. if ( isUniqueEdge( start, end, edges ) === true ) {
  22535. vertices.push( start.x, start.y, start.z );
  22536. vertices.push( end.x, end.y, end.z );
  22537. }
  22538. }
  22539. }
  22540. }
  22541. } else {
  22542. // non-indexed BufferGeometry
  22543. const position = geometry.attributes.position;
  22544. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22545. for ( let j = 0; j < 3; j ++ ) {
  22546. // three edges per triangle, an edge is represented as (index1, index2)
  22547. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22548. const index1 = 3 * i + j;
  22549. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22550. start.fromBufferAttribute( position, index1 );
  22551. end.fromBufferAttribute( position, index2 );
  22552. if ( isUniqueEdge( start, end, edges ) === true ) {
  22553. vertices.push( start.x, start.y, start.z );
  22554. vertices.push( end.x, end.y, end.z );
  22555. }
  22556. }
  22557. }
  22558. }
  22559. // build geometry
  22560. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22561. }
  22562. }
  22563. copy( source ) {
  22564. super.copy( source );
  22565. this.parameters = Object.assign( {}, source.parameters );
  22566. return this;
  22567. }
  22568. }
  22569. function isUniqueEdge( start, end, edges ) {
  22570. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22571. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22572. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22573. return false;
  22574. } else {
  22575. edges.add( hash1 );
  22576. edges.add( hash2 );
  22577. return true;
  22578. }
  22579. }
  22580. var Geometries = /*#__PURE__*/Object.freeze({
  22581. __proto__: null,
  22582. BoxGeometry: BoxGeometry,
  22583. CapsuleGeometry: CapsuleGeometry,
  22584. CircleGeometry: CircleGeometry,
  22585. ConeGeometry: ConeGeometry,
  22586. CylinderGeometry: CylinderGeometry,
  22587. DodecahedronGeometry: DodecahedronGeometry,
  22588. EdgesGeometry: EdgesGeometry,
  22589. ExtrudeGeometry: ExtrudeGeometry,
  22590. IcosahedronGeometry: IcosahedronGeometry,
  22591. LatheGeometry: LatheGeometry,
  22592. OctahedronGeometry: OctahedronGeometry,
  22593. PlaneGeometry: PlaneGeometry,
  22594. PolyhedronGeometry: PolyhedronGeometry,
  22595. RingGeometry: RingGeometry,
  22596. ShapeGeometry: ShapeGeometry,
  22597. SphereGeometry: SphereGeometry,
  22598. TetrahedronGeometry: TetrahedronGeometry,
  22599. TorusGeometry: TorusGeometry,
  22600. TorusKnotGeometry: TorusKnotGeometry,
  22601. TubeGeometry: TubeGeometry,
  22602. WireframeGeometry: WireframeGeometry
  22603. });
  22604. class ShadowMaterial extends Material {
  22605. constructor( parameters ) {
  22606. super();
  22607. this.isShadowMaterial = true;
  22608. this.type = 'ShadowMaterial';
  22609. this.color = new Color( 0x000000 );
  22610. this.transparent = true;
  22611. this.fog = true;
  22612. this.setValues( parameters );
  22613. }
  22614. copy( source ) {
  22615. super.copy( source );
  22616. this.color.copy( source.color );
  22617. this.fog = source.fog;
  22618. return this;
  22619. }
  22620. }
  22621. class RawShaderMaterial extends ShaderMaterial {
  22622. constructor( parameters ) {
  22623. super( parameters );
  22624. this.isRawShaderMaterial = true;
  22625. this.type = 'RawShaderMaterial';
  22626. }
  22627. }
  22628. class MeshStandardMaterial extends Material {
  22629. constructor( parameters ) {
  22630. super();
  22631. this.isMeshStandardMaterial = true;
  22632. this.defines = { 'STANDARD': '' };
  22633. this.type = 'MeshStandardMaterial';
  22634. this.color = new Color( 0xffffff ); // diffuse
  22635. this.roughness = 1.0;
  22636. this.metalness = 0.0;
  22637. this.map = null;
  22638. this.lightMap = null;
  22639. this.lightMapIntensity = 1.0;
  22640. this.aoMap = null;
  22641. this.aoMapIntensity = 1.0;
  22642. this.emissive = new Color( 0x000000 );
  22643. this.emissiveIntensity = 1.0;
  22644. this.emissiveMap = null;
  22645. this.bumpMap = null;
  22646. this.bumpScale = 1;
  22647. this.normalMap = null;
  22648. this.normalMapType = TangentSpaceNormalMap;
  22649. this.normalScale = new Vector2( 1, 1 );
  22650. this.displacementMap = null;
  22651. this.displacementScale = 1;
  22652. this.displacementBias = 0;
  22653. this.roughnessMap = null;
  22654. this.metalnessMap = null;
  22655. this.alphaMap = null;
  22656. this.envMap = null;
  22657. this.envMapIntensity = 1.0;
  22658. this.wireframe = false;
  22659. this.wireframeLinewidth = 1;
  22660. this.wireframeLinecap = 'round';
  22661. this.wireframeLinejoin = 'round';
  22662. this.flatShading = false;
  22663. this.fog = true;
  22664. this.setValues( parameters );
  22665. }
  22666. copy( source ) {
  22667. super.copy( source );
  22668. this.defines = { 'STANDARD': '' };
  22669. this.color.copy( source.color );
  22670. this.roughness = source.roughness;
  22671. this.metalness = source.metalness;
  22672. this.map = source.map;
  22673. this.lightMap = source.lightMap;
  22674. this.lightMapIntensity = source.lightMapIntensity;
  22675. this.aoMap = source.aoMap;
  22676. this.aoMapIntensity = source.aoMapIntensity;
  22677. this.emissive.copy( source.emissive );
  22678. this.emissiveMap = source.emissiveMap;
  22679. this.emissiveIntensity = source.emissiveIntensity;
  22680. this.bumpMap = source.bumpMap;
  22681. this.bumpScale = source.bumpScale;
  22682. this.normalMap = source.normalMap;
  22683. this.normalMapType = source.normalMapType;
  22684. this.normalScale.copy( source.normalScale );
  22685. this.displacementMap = source.displacementMap;
  22686. this.displacementScale = source.displacementScale;
  22687. this.displacementBias = source.displacementBias;
  22688. this.roughnessMap = source.roughnessMap;
  22689. this.metalnessMap = source.metalnessMap;
  22690. this.alphaMap = source.alphaMap;
  22691. this.envMap = source.envMap;
  22692. this.envMapIntensity = source.envMapIntensity;
  22693. this.wireframe = source.wireframe;
  22694. this.wireframeLinewidth = source.wireframeLinewidth;
  22695. this.wireframeLinecap = source.wireframeLinecap;
  22696. this.wireframeLinejoin = source.wireframeLinejoin;
  22697. this.flatShading = source.flatShading;
  22698. this.fog = source.fog;
  22699. return this;
  22700. }
  22701. }
  22702. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22703. constructor( parameters ) {
  22704. super();
  22705. this.isMeshPhysicalMaterial = true;
  22706. this.defines = {
  22707. 'STANDARD': '',
  22708. 'PHYSICAL': ''
  22709. };
  22710. this.type = 'MeshPhysicalMaterial';
  22711. this.clearcoatMap = null;
  22712. this.clearcoatRoughness = 0.0;
  22713. this.clearcoatRoughnessMap = null;
  22714. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22715. this.clearcoatNormalMap = null;
  22716. this.ior = 1.5;
  22717. Object.defineProperty( this, 'reflectivity', {
  22718. get: function () {
  22719. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22720. },
  22721. set: function ( reflectivity ) {
  22722. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22723. }
  22724. } );
  22725. this.iridescenceMap = null;
  22726. this.iridescenceIOR = 1.3;
  22727. this.iridescenceThicknessRange = [ 100, 400 ];
  22728. this.iridescenceThicknessMap = null;
  22729. this.sheenColor = new Color( 0x000000 );
  22730. this.sheenColorMap = null;
  22731. this.sheenRoughness = 1.0;
  22732. this.sheenRoughnessMap = null;
  22733. this.transmissionMap = null;
  22734. this.thickness = 0;
  22735. this.thicknessMap = null;
  22736. this.attenuationDistance = Infinity;
  22737. this.attenuationColor = new Color( 1, 1, 1 );
  22738. this.specularIntensity = 1.0;
  22739. this.specularIntensityMap = null;
  22740. this.specularColor = new Color( 1, 1, 1 );
  22741. this.specularColorMap = null;
  22742. this._sheen = 0.0;
  22743. this._clearcoat = 0;
  22744. this._iridescence = 0;
  22745. this._transmission = 0;
  22746. this.setValues( parameters );
  22747. }
  22748. get sheen() {
  22749. return this._sheen;
  22750. }
  22751. set sheen( value ) {
  22752. if ( this._sheen > 0 !== value > 0 ) {
  22753. this.version ++;
  22754. }
  22755. this._sheen = value;
  22756. }
  22757. get clearcoat() {
  22758. return this._clearcoat;
  22759. }
  22760. set clearcoat( value ) {
  22761. if ( this._clearcoat > 0 !== value > 0 ) {
  22762. this.version ++;
  22763. }
  22764. this._clearcoat = value;
  22765. }
  22766. get iridescence() {
  22767. return this._iridescence;
  22768. }
  22769. set iridescence( value ) {
  22770. if ( this._iridescence > 0 !== value > 0 ) {
  22771. this.version ++;
  22772. }
  22773. this._iridescence = value;
  22774. }
  22775. get transmission() {
  22776. return this._transmission;
  22777. }
  22778. set transmission( value ) {
  22779. if ( this._transmission > 0 !== value > 0 ) {
  22780. this.version ++;
  22781. }
  22782. this._transmission = value;
  22783. }
  22784. copy( source ) {
  22785. super.copy( source );
  22786. this.defines = {
  22787. 'STANDARD': '',
  22788. 'PHYSICAL': ''
  22789. };
  22790. this.clearcoat = source.clearcoat;
  22791. this.clearcoatMap = source.clearcoatMap;
  22792. this.clearcoatRoughness = source.clearcoatRoughness;
  22793. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22794. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22795. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22796. this.ior = source.ior;
  22797. this.iridescence = source.iridescence;
  22798. this.iridescenceMap = source.iridescenceMap;
  22799. this.iridescenceIOR = source.iridescenceIOR;
  22800. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22801. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22802. this.sheen = source.sheen;
  22803. this.sheenColor.copy( source.sheenColor );
  22804. this.sheenColorMap = source.sheenColorMap;
  22805. this.sheenRoughness = source.sheenRoughness;
  22806. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22807. this.transmission = source.transmission;
  22808. this.transmissionMap = source.transmissionMap;
  22809. this.thickness = source.thickness;
  22810. this.thicknessMap = source.thicknessMap;
  22811. this.attenuationDistance = source.attenuationDistance;
  22812. this.attenuationColor.copy( source.attenuationColor );
  22813. this.specularIntensity = source.specularIntensity;
  22814. this.specularIntensityMap = source.specularIntensityMap;
  22815. this.specularColor.copy( source.specularColor );
  22816. this.specularColorMap = source.specularColorMap;
  22817. return this;
  22818. }
  22819. }
  22820. class MeshPhongMaterial extends Material {
  22821. constructor( parameters ) {
  22822. super();
  22823. this.isMeshPhongMaterial = true;
  22824. this.type = 'MeshPhongMaterial';
  22825. this.color = new Color( 0xffffff ); // diffuse
  22826. this.specular = new Color( 0x111111 );
  22827. this.shininess = 30;
  22828. this.map = null;
  22829. this.lightMap = null;
  22830. this.lightMapIntensity = 1.0;
  22831. this.aoMap = null;
  22832. this.aoMapIntensity = 1.0;
  22833. this.emissive = new Color( 0x000000 );
  22834. this.emissiveIntensity = 1.0;
  22835. this.emissiveMap = null;
  22836. this.bumpMap = null;
  22837. this.bumpScale = 1;
  22838. this.normalMap = null;
  22839. this.normalMapType = TangentSpaceNormalMap;
  22840. this.normalScale = new Vector2( 1, 1 );
  22841. this.displacementMap = null;
  22842. this.displacementScale = 1;
  22843. this.displacementBias = 0;
  22844. this.specularMap = null;
  22845. this.alphaMap = null;
  22846. this.envMap = null;
  22847. this.combine = MultiplyOperation;
  22848. this.reflectivity = 1;
  22849. this.refractionRatio = 0.98;
  22850. this.wireframe = false;
  22851. this.wireframeLinewidth = 1;
  22852. this.wireframeLinecap = 'round';
  22853. this.wireframeLinejoin = 'round';
  22854. this.flatShading = false;
  22855. this.fog = true;
  22856. this.setValues( parameters );
  22857. }
  22858. copy( source ) {
  22859. super.copy( source );
  22860. this.color.copy( source.color );
  22861. this.specular.copy( source.specular );
  22862. this.shininess = source.shininess;
  22863. this.map = source.map;
  22864. this.lightMap = source.lightMap;
  22865. this.lightMapIntensity = source.lightMapIntensity;
  22866. this.aoMap = source.aoMap;
  22867. this.aoMapIntensity = source.aoMapIntensity;
  22868. this.emissive.copy( source.emissive );
  22869. this.emissiveMap = source.emissiveMap;
  22870. this.emissiveIntensity = source.emissiveIntensity;
  22871. this.bumpMap = source.bumpMap;
  22872. this.bumpScale = source.bumpScale;
  22873. this.normalMap = source.normalMap;
  22874. this.normalMapType = source.normalMapType;
  22875. this.normalScale.copy( source.normalScale );
  22876. this.displacementMap = source.displacementMap;
  22877. this.displacementScale = source.displacementScale;
  22878. this.displacementBias = source.displacementBias;
  22879. this.specularMap = source.specularMap;
  22880. this.alphaMap = source.alphaMap;
  22881. this.envMap = source.envMap;
  22882. this.combine = source.combine;
  22883. this.reflectivity = source.reflectivity;
  22884. this.refractionRatio = source.refractionRatio;
  22885. this.wireframe = source.wireframe;
  22886. this.wireframeLinewidth = source.wireframeLinewidth;
  22887. this.wireframeLinecap = source.wireframeLinecap;
  22888. this.wireframeLinejoin = source.wireframeLinejoin;
  22889. this.flatShading = source.flatShading;
  22890. this.fog = source.fog;
  22891. return this;
  22892. }
  22893. }
  22894. class MeshToonMaterial extends Material {
  22895. constructor( parameters ) {
  22896. super();
  22897. this.isMeshToonMaterial = true;
  22898. this.defines = { 'TOON': '' };
  22899. this.type = 'MeshToonMaterial';
  22900. this.color = new Color( 0xffffff );
  22901. this.map = null;
  22902. this.gradientMap = null;
  22903. this.lightMap = null;
  22904. this.lightMapIntensity = 1.0;
  22905. this.aoMap = null;
  22906. this.aoMapIntensity = 1.0;
  22907. this.emissive = new Color( 0x000000 );
  22908. this.emissiveIntensity = 1.0;
  22909. this.emissiveMap = null;
  22910. this.bumpMap = null;
  22911. this.bumpScale = 1;
  22912. this.normalMap = null;
  22913. this.normalMapType = TangentSpaceNormalMap;
  22914. this.normalScale = new Vector2( 1, 1 );
  22915. this.displacementMap = null;
  22916. this.displacementScale = 1;
  22917. this.displacementBias = 0;
  22918. this.alphaMap = null;
  22919. this.wireframe = false;
  22920. this.wireframeLinewidth = 1;
  22921. this.wireframeLinecap = 'round';
  22922. this.wireframeLinejoin = 'round';
  22923. this.fog = true;
  22924. this.setValues( parameters );
  22925. }
  22926. copy( source ) {
  22927. super.copy( source );
  22928. this.color.copy( source.color );
  22929. this.map = source.map;
  22930. this.gradientMap = source.gradientMap;
  22931. this.lightMap = source.lightMap;
  22932. this.lightMapIntensity = source.lightMapIntensity;
  22933. this.aoMap = source.aoMap;
  22934. this.aoMapIntensity = source.aoMapIntensity;
  22935. this.emissive.copy( source.emissive );
  22936. this.emissiveMap = source.emissiveMap;
  22937. this.emissiveIntensity = source.emissiveIntensity;
  22938. this.bumpMap = source.bumpMap;
  22939. this.bumpScale = source.bumpScale;
  22940. this.normalMap = source.normalMap;
  22941. this.normalMapType = source.normalMapType;
  22942. this.normalScale.copy( source.normalScale );
  22943. this.displacementMap = source.displacementMap;
  22944. this.displacementScale = source.displacementScale;
  22945. this.displacementBias = source.displacementBias;
  22946. this.alphaMap = source.alphaMap;
  22947. this.wireframe = source.wireframe;
  22948. this.wireframeLinewidth = source.wireframeLinewidth;
  22949. this.wireframeLinecap = source.wireframeLinecap;
  22950. this.wireframeLinejoin = source.wireframeLinejoin;
  22951. this.fog = source.fog;
  22952. return this;
  22953. }
  22954. }
  22955. class MeshNormalMaterial extends Material {
  22956. constructor( parameters ) {
  22957. super();
  22958. this.isMeshNormalMaterial = true;
  22959. this.type = 'MeshNormalMaterial';
  22960. this.bumpMap = null;
  22961. this.bumpScale = 1;
  22962. this.normalMap = null;
  22963. this.normalMapType = TangentSpaceNormalMap;
  22964. this.normalScale = new Vector2( 1, 1 );
  22965. this.displacementMap = null;
  22966. this.displacementScale = 1;
  22967. this.displacementBias = 0;
  22968. this.wireframe = false;
  22969. this.wireframeLinewidth = 1;
  22970. this.flatShading = false;
  22971. this.setValues( parameters );
  22972. }
  22973. copy( source ) {
  22974. super.copy( source );
  22975. this.bumpMap = source.bumpMap;
  22976. this.bumpScale = source.bumpScale;
  22977. this.normalMap = source.normalMap;
  22978. this.normalMapType = source.normalMapType;
  22979. this.normalScale.copy( source.normalScale );
  22980. this.displacementMap = source.displacementMap;
  22981. this.displacementScale = source.displacementScale;
  22982. this.displacementBias = source.displacementBias;
  22983. this.wireframe = source.wireframe;
  22984. this.wireframeLinewidth = source.wireframeLinewidth;
  22985. this.flatShading = source.flatShading;
  22986. return this;
  22987. }
  22988. }
  22989. class MeshLambertMaterial extends Material {
  22990. constructor( parameters ) {
  22991. super();
  22992. this.isMeshLambertMaterial = true;
  22993. this.type = 'MeshLambertMaterial';
  22994. this.color = new Color( 0xffffff ); // diffuse
  22995. this.map = null;
  22996. this.lightMap = null;
  22997. this.lightMapIntensity = 1.0;
  22998. this.aoMap = null;
  22999. this.aoMapIntensity = 1.0;
  23000. this.emissive = new Color( 0x000000 );
  23001. this.emissiveIntensity = 1.0;
  23002. this.emissiveMap = null;
  23003. this.bumpMap = null;
  23004. this.bumpScale = 1;
  23005. this.normalMap = null;
  23006. this.normalMapType = TangentSpaceNormalMap;
  23007. this.normalScale = new Vector2( 1, 1 );
  23008. this.displacementMap = null;
  23009. this.displacementScale = 1;
  23010. this.displacementBias = 0;
  23011. this.specularMap = null;
  23012. this.alphaMap = null;
  23013. this.envMap = null;
  23014. this.combine = MultiplyOperation;
  23015. this.reflectivity = 1;
  23016. this.refractionRatio = 0.98;
  23017. this.wireframe = false;
  23018. this.wireframeLinewidth = 1;
  23019. this.wireframeLinecap = 'round';
  23020. this.wireframeLinejoin = 'round';
  23021. this.flatShading = false;
  23022. this.fog = true;
  23023. this.setValues( parameters );
  23024. }
  23025. copy( source ) {
  23026. super.copy( source );
  23027. this.color.copy( source.color );
  23028. this.map = source.map;
  23029. this.lightMap = source.lightMap;
  23030. this.lightMapIntensity = source.lightMapIntensity;
  23031. this.aoMap = source.aoMap;
  23032. this.aoMapIntensity = source.aoMapIntensity;
  23033. this.emissive.copy( source.emissive );
  23034. this.emissiveMap = source.emissiveMap;
  23035. this.emissiveIntensity = source.emissiveIntensity;
  23036. this.bumpMap = source.bumpMap;
  23037. this.bumpScale = source.bumpScale;
  23038. this.normalMap = source.normalMap;
  23039. this.normalMapType = source.normalMapType;
  23040. this.normalScale.copy( source.normalScale );
  23041. this.displacementMap = source.displacementMap;
  23042. this.displacementScale = source.displacementScale;
  23043. this.displacementBias = source.displacementBias;
  23044. this.specularMap = source.specularMap;
  23045. this.alphaMap = source.alphaMap;
  23046. this.envMap = source.envMap;
  23047. this.combine = source.combine;
  23048. this.reflectivity = source.reflectivity;
  23049. this.refractionRatio = source.refractionRatio;
  23050. this.wireframe = source.wireframe;
  23051. this.wireframeLinewidth = source.wireframeLinewidth;
  23052. this.wireframeLinecap = source.wireframeLinecap;
  23053. this.wireframeLinejoin = source.wireframeLinejoin;
  23054. this.flatShading = source.flatShading;
  23055. this.fog = source.fog;
  23056. return this;
  23057. }
  23058. }
  23059. class MeshMatcapMaterial extends Material {
  23060. constructor( parameters ) {
  23061. super();
  23062. this.isMeshMatcapMaterial = true;
  23063. this.defines = { 'MATCAP': '' };
  23064. this.type = 'MeshMatcapMaterial';
  23065. this.color = new Color( 0xffffff ); // diffuse
  23066. this.matcap = null;
  23067. this.map = null;
  23068. this.bumpMap = null;
  23069. this.bumpScale = 1;
  23070. this.normalMap = null;
  23071. this.normalMapType = TangentSpaceNormalMap;
  23072. this.normalScale = new Vector2( 1, 1 );
  23073. this.displacementMap = null;
  23074. this.displacementScale = 1;
  23075. this.displacementBias = 0;
  23076. this.alphaMap = null;
  23077. this.flatShading = false;
  23078. this.fog = true;
  23079. this.setValues( parameters );
  23080. }
  23081. copy( source ) {
  23082. super.copy( source );
  23083. this.defines = { 'MATCAP': '' };
  23084. this.color.copy( source.color );
  23085. this.matcap = source.matcap;
  23086. this.map = source.map;
  23087. this.bumpMap = source.bumpMap;
  23088. this.bumpScale = source.bumpScale;
  23089. this.normalMap = source.normalMap;
  23090. this.normalMapType = source.normalMapType;
  23091. this.normalScale.copy( source.normalScale );
  23092. this.displacementMap = source.displacementMap;
  23093. this.displacementScale = source.displacementScale;
  23094. this.displacementBias = source.displacementBias;
  23095. this.alphaMap = source.alphaMap;
  23096. this.flatShading = source.flatShading;
  23097. this.fog = source.fog;
  23098. return this;
  23099. }
  23100. }
  23101. class LineDashedMaterial extends LineBasicMaterial {
  23102. constructor( parameters ) {
  23103. super();
  23104. this.isLineDashedMaterial = true;
  23105. this.type = 'LineDashedMaterial';
  23106. this.scale = 1;
  23107. this.dashSize = 3;
  23108. this.gapSize = 1;
  23109. this.setValues( parameters );
  23110. }
  23111. copy( source ) {
  23112. super.copy( source );
  23113. this.scale = source.scale;
  23114. this.dashSize = source.dashSize;
  23115. this.gapSize = source.gapSize;
  23116. return this;
  23117. }
  23118. }
  23119. // same as Array.prototype.slice, but also works on typed arrays
  23120. function arraySlice( array, from, to ) {
  23121. if ( isTypedArray( array ) ) {
  23122. // in ios9 array.subarray(from, undefined) will return empty array
  23123. // but array.subarray(from) or array.subarray(from, len) is correct
  23124. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  23125. }
  23126. return array.slice( from, to );
  23127. }
  23128. // converts an array to a specific type
  23129. function convertArray( array, type, forceClone ) {
  23130. if ( ! array || // let 'undefined' and 'null' pass
  23131. ! forceClone && array.constructor === type ) return array;
  23132. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  23133. return new type( array ); // create typed array
  23134. }
  23135. return Array.prototype.slice.call( array ); // create Array
  23136. }
  23137. function isTypedArray( object ) {
  23138. return ArrayBuffer.isView( object ) &&
  23139. ! ( object instanceof DataView );
  23140. }
  23141. // returns an array by which times and values can be sorted
  23142. function getKeyframeOrder( times ) {
  23143. function compareTime( i, j ) {
  23144. return times[ i ] - times[ j ];
  23145. }
  23146. const n = times.length;
  23147. const result = new Array( n );
  23148. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  23149. result.sort( compareTime );
  23150. return result;
  23151. }
  23152. // uses the array previously returned by 'getKeyframeOrder' to sort data
  23153. function sortedArray( values, stride, order ) {
  23154. const nValues = values.length;
  23155. const result = new values.constructor( nValues );
  23156. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  23157. const srcOffset = order[ i ] * stride;
  23158. for ( let j = 0; j !== stride; ++ j ) {
  23159. result[ dstOffset ++ ] = values[ srcOffset + j ];
  23160. }
  23161. }
  23162. return result;
  23163. }
  23164. // function for parsing AOS keyframe formats
  23165. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  23166. let i = 1, key = jsonKeys[ 0 ];
  23167. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  23168. key = jsonKeys[ i ++ ];
  23169. }
  23170. if ( key === undefined ) return; // no data
  23171. let value = key[ valuePropertyName ];
  23172. if ( value === undefined ) return; // no data
  23173. if ( Array.isArray( value ) ) {
  23174. do {
  23175. value = key[ valuePropertyName ];
  23176. if ( value !== undefined ) {
  23177. times.push( key.time );
  23178. values.push.apply( values, value ); // push all elements
  23179. }
  23180. key = jsonKeys[ i ++ ];
  23181. } while ( key !== undefined );
  23182. } else if ( value.toArray !== undefined ) {
  23183. // ...assume THREE.Math-ish
  23184. do {
  23185. value = key[ valuePropertyName ];
  23186. if ( value !== undefined ) {
  23187. times.push( key.time );
  23188. value.toArray( values, values.length );
  23189. }
  23190. key = jsonKeys[ i ++ ];
  23191. } while ( key !== undefined );
  23192. } else {
  23193. // otherwise push as-is
  23194. do {
  23195. value = key[ valuePropertyName ];
  23196. if ( value !== undefined ) {
  23197. times.push( key.time );
  23198. values.push( value );
  23199. }
  23200. key = jsonKeys[ i ++ ];
  23201. } while ( key !== undefined );
  23202. }
  23203. }
  23204. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  23205. const clip = sourceClip.clone();
  23206. clip.name = name;
  23207. const tracks = [];
  23208. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23209. const track = clip.tracks[ i ];
  23210. const valueSize = track.getValueSize();
  23211. const times = [];
  23212. const values = [];
  23213. for ( let j = 0; j < track.times.length; ++ j ) {
  23214. const frame = track.times[ j ] * fps;
  23215. if ( frame < startFrame || frame >= endFrame ) continue;
  23216. times.push( track.times[ j ] );
  23217. for ( let k = 0; k < valueSize; ++ k ) {
  23218. values.push( track.values[ j * valueSize + k ] );
  23219. }
  23220. }
  23221. if ( times.length === 0 ) continue;
  23222. track.times = convertArray( times, track.times.constructor );
  23223. track.values = convertArray( values, track.values.constructor );
  23224. tracks.push( track );
  23225. }
  23226. clip.tracks = tracks;
  23227. // find minimum .times value across all tracks in the trimmed clip
  23228. let minStartTime = Infinity;
  23229. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23230. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  23231. minStartTime = clip.tracks[ i ].times[ 0 ];
  23232. }
  23233. }
  23234. // shift all tracks such that clip begins at t=0
  23235. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23236. clip.tracks[ i ].shift( - 1 * minStartTime );
  23237. }
  23238. clip.resetDuration();
  23239. return clip;
  23240. }
  23241. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  23242. if ( fps <= 0 ) fps = 30;
  23243. const numTracks = referenceClip.tracks.length;
  23244. const referenceTime = referenceFrame / fps;
  23245. // Make each track's values relative to the values at the reference frame
  23246. for ( let i = 0; i < numTracks; ++ i ) {
  23247. const referenceTrack = referenceClip.tracks[ i ];
  23248. const referenceTrackType = referenceTrack.ValueTypeName;
  23249. // Skip this track if it's non-numeric
  23250. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  23251. // Find the track in the target clip whose name and type matches the reference track
  23252. const targetTrack = targetClip.tracks.find( function ( track ) {
  23253. return track.name === referenceTrack.name
  23254. && track.ValueTypeName === referenceTrackType;
  23255. } );
  23256. if ( targetTrack === undefined ) continue;
  23257. let referenceOffset = 0;
  23258. const referenceValueSize = referenceTrack.getValueSize();
  23259. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23260. referenceOffset = referenceValueSize / 3;
  23261. }
  23262. let targetOffset = 0;
  23263. const targetValueSize = targetTrack.getValueSize();
  23264. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23265. targetOffset = targetValueSize / 3;
  23266. }
  23267. const lastIndex = referenceTrack.times.length - 1;
  23268. let referenceValue;
  23269. // Find the value to subtract out of the track
  23270. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  23271. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23272. const startIndex = referenceOffset;
  23273. const endIndex = referenceValueSize - referenceOffset;
  23274. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23275. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  23276. // Reference frame is after the last keyframe, so just use the last keyframe
  23277. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23278. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23279. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23280. } else {
  23281. // Interpolate to the reference value
  23282. const interpolant = referenceTrack.createInterpolant();
  23283. const startIndex = referenceOffset;
  23284. const endIndex = referenceValueSize - referenceOffset;
  23285. interpolant.evaluate( referenceTime );
  23286. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  23287. }
  23288. // Conjugate the quaternion
  23289. if ( referenceTrackType === 'quaternion' ) {
  23290. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  23291. referenceQuat.toArray( referenceValue );
  23292. }
  23293. // Subtract the reference value from all of the track values
  23294. const numTimes = targetTrack.times.length;
  23295. for ( let j = 0; j < numTimes; ++ j ) {
  23296. const valueStart = j * targetValueSize + targetOffset;
  23297. if ( referenceTrackType === 'quaternion' ) {
  23298. // Multiply the conjugate for quaternion track types
  23299. Quaternion.multiplyQuaternionsFlat(
  23300. targetTrack.values,
  23301. valueStart,
  23302. referenceValue,
  23303. 0,
  23304. targetTrack.values,
  23305. valueStart
  23306. );
  23307. } else {
  23308. const valueEnd = targetValueSize - targetOffset * 2;
  23309. // Subtract each value for all other numeric track types
  23310. for ( let k = 0; k < valueEnd; ++ k ) {
  23311. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  23312. }
  23313. }
  23314. }
  23315. }
  23316. targetClip.blendMode = AdditiveAnimationBlendMode;
  23317. return targetClip;
  23318. }
  23319. const AnimationUtils = {
  23320. arraySlice: arraySlice,
  23321. convertArray: convertArray,
  23322. isTypedArray: isTypedArray,
  23323. getKeyframeOrder: getKeyframeOrder,
  23324. sortedArray: sortedArray,
  23325. flattenJSON: flattenJSON,
  23326. subclip: subclip,
  23327. makeClipAdditive: makeClipAdditive
  23328. };
  23329. /**
  23330. * Abstract base class of interpolants over parametric samples.
  23331. *
  23332. * The parameter domain is one dimensional, typically the time or a path
  23333. * along a curve defined by the data.
  23334. *
  23335. * The sample values can have any dimensionality and derived classes may
  23336. * apply special interpretations to the data.
  23337. *
  23338. * This class provides the interval seek in a Template Method, deferring
  23339. * the actual interpolation to derived classes.
  23340. *
  23341. * Time complexity is O(1) for linear access crossing at most two points
  23342. * and O(log N) for random access, where N is the number of positions.
  23343. *
  23344. * References:
  23345. *
  23346. * http://www.oodesign.com/template-method-pattern.html
  23347. *
  23348. */
  23349. class Interpolant {
  23350. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23351. this.parameterPositions = parameterPositions;
  23352. this._cachedIndex = 0;
  23353. this.resultBuffer = resultBuffer !== undefined ?
  23354. resultBuffer : new sampleValues.constructor( sampleSize );
  23355. this.sampleValues = sampleValues;
  23356. this.valueSize = sampleSize;
  23357. this.settings = null;
  23358. this.DefaultSettings_ = {};
  23359. }
  23360. evaluate( t ) {
  23361. const pp = this.parameterPositions;
  23362. let i1 = this._cachedIndex,
  23363. t1 = pp[ i1 ],
  23364. t0 = pp[ i1 - 1 ];
  23365. validate_interval: {
  23366. seek: {
  23367. let right;
  23368. linear_scan: {
  23369. //- See http://jsperf.com/comparison-to-undefined/3
  23370. //- slower code:
  23371. //-
  23372. //- if ( t >= t1 || t1 === undefined ) {
  23373. forward_scan: if ( ! ( t < t1 ) ) {
  23374. for ( let giveUpAt = i1 + 2; ; ) {
  23375. if ( t1 === undefined ) {
  23376. if ( t < t0 ) break forward_scan;
  23377. // after end
  23378. i1 = pp.length;
  23379. this._cachedIndex = i1;
  23380. return this.copySampleValue_( i1 - 1 );
  23381. }
  23382. if ( i1 === giveUpAt ) break; // this loop
  23383. t0 = t1;
  23384. t1 = pp[ ++ i1 ];
  23385. if ( t < t1 ) {
  23386. // we have arrived at the sought interval
  23387. break seek;
  23388. }
  23389. }
  23390. // prepare binary search on the right side of the index
  23391. right = pp.length;
  23392. break linear_scan;
  23393. }
  23394. //- slower code:
  23395. //- if ( t < t0 || t0 === undefined ) {
  23396. if ( ! ( t >= t0 ) ) {
  23397. // looping?
  23398. const t1global = pp[ 1 ];
  23399. if ( t < t1global ) {
  23400. i1 = 2; // + 1, using the scan for the details
  23401. t0 = t1global;
  23402. }
  23403. // linear reverse scan
  23404. for ( let giveUpAt = i1 - 2; ; ) {
  23405. if ( t0 === undefined ) {
  23406. // before start
  23407. this._cachedIndex = 0;
  23408. return this.copySampleValue_( 0 );
  23409. }
  23410. if ( i1 === giveUpAt ) break; // this loop
  23411. t1 = t0;
  23412. t0 = pp[ -- i1 - 1 ];
  23413. if ( t >= t0 ) {
  23414. // we have arrived at the sought interval
  23415. break seek;
  23416. }
  23417. }
  23418. // prepare binary search on the left side of the index
  23419. right = i1;
  23420. i1 = 0;
  23421. break linear_scan;
  23422. }
  23423. // the interval is valid
  23424. break validate_interval;
  23425. } // linear scan
  23426. // binary search
  23427. while ( i1 < right ) {
  23428. const mid = ( i1 + right ) >>> 1;
  23429. if ( t < pp[ mid ] ) {
  23430. right = mid;
  23431. } else {
  23432. i1 = mid + 1;
  23433. }
  23434. }
  23435. t1 = pp[ i1 ];
  23436. t0 = pp[ i1 - 1 ];
  23437. // check boundary cases, again
  23438. if ( t0 === undefined ) {
  23439. this._cachedIndex = 0;
  23440. return this.copySampleValue_( 0 );
  23441. }
  23442. if ( t1 === undefined ) {
  23443. i1 = pp.length;
  23444. this._cachedIndex = i1;
  23445. return this.copySampleValue_( i1 - 1 );
  23446. }
  23447. } // seek
  23448. this._cachedIndex = i1;
  23449. this.intervalChanged_( i1, t0, t1 );
  23450. } // validate_interval
  23451. return this.interpolate_( i1, t0, t, t1 );
  23452. }
  23453. getSettings_() {
  23454. return this.settings || this.DefaultSettings_;
  23455. }
  23456. copySampleValue_( index ) {
  23457. // copies a sample value to the result buffer
  23458. const result = this.resultBuffer,
  23459. values = this.sampleValues,
  23460. stride = this.valueSize,
  23461. offset = index * stride;
  23462. for ( let i = 0; i !== stride; ++ i ) {
  23463. result[ i ] = values[ offset + i ];
  23464. }
  23465. return result;
  23466. }
  23467. // Template methods for derived classes:
  23468. interpolate_( /* i1, t0, t, t1 */ ) {
  23469. throw new Error( 'call to abstract method' );
  23470. // implementations shall return this.resultBuffer
  23471. }
  23472. intervalChanged_( /* i1, t0, t1 */ ) {
  23473. // empty
  23474. }
  23475. }
  23476. /**
  23477. * Fast and simple cubic spline interpolant.
  23478. *
  23479. * It was derived from a Hermitian construction setting the first derivative
  23480. * at each sample position to the linear slope between neighboring positions
  23481. * over their parameter interval.
  23482. */
  23483. class CubicInterpolant extends Interpolant {
  23484. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23485. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23486. this._weightPrev = - 0;
  23487. this._offsetPrev = - 0;
  23488. this._weightNext = - 0;
  23489. this._offsetNext = - 0;
  23490. this.DefaultSettings_ = {
  23491. endingStart: ZeroCurvatureEnding,
  23492. endingEnd: ZeroCurvatureEnding
  23493. };
  23494. }
  23495. intervalChanged_( i1, t0, t1 ) {
  23496. const pp = this.parameterPositions;
  23497. let iPrev = i1 - 2,
  23498. iNext = i1 + 1,
  23499. tPrev = pp[ iPrev ],
  23500. tNext = pp[ iNext ];
  23501. if ( tPrev === undefined ) {
  23502. switch ( this.getSettings_().endingStart ) {
  23503. case ZeroSlopeEnding:
  23504. // f'(t0) = 0
  23505. iPrev = i1;
  23506. tPrev = 2 * t0 - t1;
  23507. break;
  23508. case WrapAroundEnding:
  23509. // use the other end of the curve
  23510. iPrev = pp.length - 2;
  23511. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23512. break;
  23513. default: // ZeroCurvatureEnding
  23514. // f''(t0) = 0 a.k.a. Natural Spline
  23515. iPrev = i1;
  23516. tPrev = t1;
  23517. }
  23518. }
  23519. if ( tNext === undefined ) {
  23520. switch ( this.getSettings_().endingEnd ) {
  23521. case ZeroSlopeEnding:
  23522. // f'(tN) = 0
  23523. iNext = i1;
  23524. tNext = 2 * t1 - t0;
  23525. break;
  23526. case WrapAroundEnding:
  23527. // use the other end of the curve
  23528. iNext = 1;
  23529. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23530. break;
  23531. default: // ZeroCurvatureEnding
  23532. // f''(tN) = 0, a.k.a. Natural Spline
  23533. iNext = i1 - 1;
  23534. tNext = t0;
  23535. }
  23536. }
  23537. const halfDt = ( t1 - t0 ) * 0.5,
  23538. stride = this.valueSize;
  23539. this._weightPrev = halfDt / ( t0 - tPrev );
  23540. this._weightNext = halfDt / ( tNext - t1 );
  23541. this._offsetPrev = iPrev * stride;
  23542. this._offsetNext = iNext * stride;
  23543. }
  23544. interpolate_( i1, t0, t, t1 ) {
  23545. const result = this.resultBuffer,
  23546. values = this.sampleValues,
  23547. stride = this.valueSize,
  23548. o1 = i1 * stride, o0 = o1 - stride,
  23549. oP = this._offsetPrev, oN = this._offsetNext,
  23550. wP = this._weightPrev, wN = this._weightNext,
  23551. p = ( t - t0 ) / ( t1 - t0 ),
  23552. pp = p * p,
  23553. ppp = pp * p;
  23554. // evaluate polynomials
  23555. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23556. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23557. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23558. const sN = wN * ppp - wN * pp;
  23559. // combine data linearly
  23560. for ( let i = 0; i !== stride; ++ i ) {
  23561. result[ i ] =
  23562. sP * values[ oP + i ] +
  23563. s0 * values[ o0 + i ] +
  23564. s1 * values[ o1 + i ] +
  23565. sN * values[ oN + i ];
  23566. }
  23567. return result;
  23568. }
  23569. }
  23570. class LinearInterpolant extends Interpolant {
  23571. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23572. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23573. }
  23574. interpolate_( i1, t0, t, t1 ) {
  23575. const result = this.resultBuffer,
  23576. values = this.sampleValues,
  23577. stride = this.valueSize,
  23578. offset1 = i1 * stride,
  23579. offset0 = offset1 - stride,
  23580. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23581. weight0 = 1 - weight1;
  23582. for ( let i = 0; i !== stride; ++ i ) {
  23583. result[ i ] =
  23584. values[ offset0 + i ] * weight0 +
  23585. values[ offset1 + i ] * weight1;
  23586. }
  23587. return result;
  23588. }
  23589. }
  23590. /**
  23591. *
  23592. * Interpolant that evaluates to the sample value at the position preceding
  23593. * the parameter.
  23594. */
  23595. class DiscreteInterpolant extends Interpolant {
  23596. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23597. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23598. }
  23599. interpolate_( i1 /*, t0, t, t1 */ ) {
  23600. return this.copySampleValue_( i1 - 1 );
  23601. }
  23602. }
  23603. class KeyframeTrack {
  23604. constructor( name, times, values, interpolation ) {
  23605. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23606. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23607. this.name = name;
  23608. this.times = convertArray( times, this.TimeBufferType );
  23609. this.values = convertArray( values, this.ValueBufferType );
  23610. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23611. }
  23612. // Serialization (in static context, because of constructor invocation
  23613. // and automatic invocation of .toJSON):
  23614. static toJSON( track ) {
  23615. const trackType = track.constructor;
  23616. let json;
  23617. // derived classes can define a static toJSON method
  23618. if ( trackType.toJSON !== this.toJSON ) {
  23619. json = trackType.toJSON( track );
  23620. } else {
  23621. // by default, we assume the data can be serialized as-is
  23622. json = {
  23623. 'name': track.name,
  23624. 'times': convertArray( track.times, Array ),
  23625. 'values': convertArray( track.values, Array )
  23626. };
  23627. const interpolation = track.getInterpolation();
  23628. if ( interpolation !== track.DefaultInterpolation ) {
  23629. json.interpolation = interpolation;
  23630. }
  23631. }
  23632. json.type = track.ValueTypeName; // mandatory
  23633. return json;
  23634. }
  23635. InterpolantFactoryMethodDiscrete( result ) {
  23636. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23637. }
  23638. InterpolantFactoryMethodLinear( result ) {
  23639. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23640. }
  23641. InterpolantFactoryMethodSmooth( result ) {
  23642. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23643. }
  23644. setInterpolation( interpolation ) {
  23645. let factoryMethod;
  23646. switch ( interpolation ) {
  23647. case InterpolateDiscrete:
  23648. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23649. break;
  23650. case InterpolateLinear:
  23651. factoryMethod = this.InterpolantFactoryMethodLinear;
  23652. break;
  23653. case InterpolateSmooth:
  23654. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23655. break;
  23656. }
  23657. if ( factoryMethod === undefined ) {
  23658. const message = 'unsupported interpolation for ' +
  23659. this.ValueTypeName + ' keyframe track named ' + this.name;
  23660. if ( this.createInterpolant === undefined ) {
  23661. // fall back to default, unless the default itself is messed up
  23662. if ( interpolation !== this.DefaultInterpolation ) {
  23663. this.setInterpolation( this.DefaultInterpolation );
  23664. } else {
  23665. throw new Error( message ); // fatal, in this case
  23666. }
  23667. }
  23668. console.warn( 'THREE.KeyframeTrack:', message );
  23669. return this;
  23670. }
  23671. this.createInterpolant = factoryMethod;
  23672. return this;
  23673. }
  23674. getInterpolation() {
  23675. switch ( this.createInterpolant ) {
  23676. case this.InterpolantFactoryMethodDiscrete:
  23677. return InterpolateDiscrete;
  23678. case this.InterpolantFactoryMethodLinear:
  23679. return InterpolateLinear;
  23680. case this.InterpolantFactoryMethodSmooth:
  23681. return InterpolateSmooth;
  23682. }
  23683. }
  23684. getValueSize() {
  23685. return this.values.length / this.times.length;
  23686. }
  23687. // move all keyframes either forwards or backwards in time
  23688. shift( timeOffset ) {
  23689. if ( timeOffset !== 0.0 ) {
  23690. const times = this.times;
  23691. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23692. times[ i ] += timeOffset;
  23693. }
  23694. }
  23695. return this;
  23696. }
  23697. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23698. scale( timeScale ) {
  23699. if ( timeScale !== 1.0 ) {
  23700. const times = this.times;
  23701. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23702. times[ i ] *= timeScale;
  23703. }
  23704. }
  23705. return this;
  23706. }
  23707. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23708. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23709. trim( startTime, endTime ) {
  23710. const times = this.times,
  23711. nKeys = times.length;
  23712. let from = 0,
  23713. to = nKeys - 1;
  23714. while ( from !== nKeys && times[ from ] < startTime ) {
  23715. ++ from;
  23716. }
  23717. while ( to !== - 1 && times[ to ] > endTime ) {
  23718. -- to;
  23719. }
  23720. ++ to; // inclusive -> exclusive bound
  23721. if ( from !== 0 || to !== nKeys ) {
  23722. // empty tracks are forbidden, so keep at least one keyframe
  23723. if ( from >= to ) {
  23724. to = Math.max( to, 1 );
  23725. from = to - 1;
  23726. }
  23727. const stride = this.getValueSize();
  23728. this.times = arraySlice( times, from, to );
  23729. this.values = arraySlice( this.values, from * stride, to * stride );
  23730. }
  23731. return this;
  23732. }
  23733. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23734. validate() {
  23735. let valid = true;
  23736. const valueSize = this.getValueSize();
  23737. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23738. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23739. valid = false;
  23740. }
  23741. const times = this.times,
  23742. values = this.values,
  23743. nKeys = times.length;
  23744. if ( nKeys === 0 ) {
  23745. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23746. valid = false;
  23747. }
  23748. let prevTime = null;
  23749. for ( let i = 0; i !== nKeys; i ++ ) {
  23750. const currTime = times[ i ];
  23751. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23752. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23753. valid = false;
  23754. break;
  23755. }
  23756. if ( prevTime !== null && prevTime > currTime ) {
  23757. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23758. valid = false;
  23759. break;
  23760. }
  23761. prevTime = currTime;
  23762. }
  23763. if ( values !== undefined ) {
  23764. if ( isTypedArray( values ) ) {
  23765. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23766. const value = values[ i ];
  23767. if ( isNaN( value ) ) {
  23768. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23769. valid = false;
  23770. break;
  23771. }
  23772. }
  23773. }
  23774. }
  23775. return valid;
  23776. }
  23777. // removes equivalent sequential keys as common in morph target sequences
  23778. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23779. optimize() {
  23780. // times or values may be shared with other tracks, so overwriting is unsafe
  23781. const times = arraySlice( this.times ),
  23782. values = arraySlice( this.values ),
  23783. stride = this.getValueSize(),
  23784. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23785. lastIndex = times.length - 1;
  23786. let writeIndex = 1;
  23787. for ( let i = 1; i < lastIndex; ++ i ) {
  23788. let keep = false;
  23789. const time = times[ i ];
  23790. const timeNext = times[ i + 1 ];
  23791. // remove adjacent keyframes scheduled at the same time
  23792. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23793. if ( ! smoothInterpolation ) {
  23794. // remove unnecessary keyframes same as their neighbors
  23795. const offset = i * stride,
  23796. offsetP = offset - stride,
  23797. offsetN = offset + stride;
  23798. for ( let j = 0; j !== stride; ++ j ) {
  23799. const value = values[ offset + j ];
  23800. if ( value !== values[ offsetP + j ] ||
  23801. value !== values[ offsetN + j ] ) {
  23802. keep = true;
  23803. break;
  23804. }
  23805. }
  23806. } else {
  23807. keep = true;
  23808. }
  23809. }
  23810. // in-place compaction
  23811. if ( keep ) {
  23812. if ( i !== writeIndex ) {
  23813. times[ writeIndex ] = times[ i ];
  23814. const readOffset = i * stride,
  23815. writeOffset = writeIndex * stride;
  23816. for ( let j = 0; j !== stride; ++ j ) {
  23817. values[ writeOffset + j ] = values[ readOffset + j ];
  23818. }
  23819. }
  23820. ++ writeIndex;
  23821. }
  23822. }
  23823. // flush last keyframe (compaction looks ahead)
  23824. if ( lastIndex > 0 ) {
  23825. times[ writeIndex ] = times[ lastIndex ];
  23826. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23827. values[ writeOffset + j ] = values[ readOffset + j ];
  23828. }
  23829. ++ writeIndex;
  23830. }
  23831. if ( writeIndex !== times.length ) {
  23832. this.times = arraySlice( times, 0, writeIndex );
  23833. this.values = arraySlice( values, 0, writeIndex * stride );
  23834. } else {
  23835. this.times = times;
  23836. this.values = values;
  23837. }
  23838. return this;
  23839. }
  23840. clone() {
  23841. const times = arraySlice( this.times, 0 );
  23842. const values = arraySlice( this.values, 0 );
  23843. const TypedKeyframeTrack = this.constructor;
  23844. const track = new TypedKeyframeTrack( this.name, times, values );
  23845. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23846. track.createInterpolant = this.createInterpolant;
  23847. return track;
  23848. }
  23849. }
  23850. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23851. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23852. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23853. /**
  23854. * A Track of Boolean keyframe values.
  23855. */
  23856. class BooleanKeyframeTrack extends KeyframeTrack {}
  23857. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23858. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23859. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23860. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23861. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23862. /**
  23863. * A Track of keyframe values that represent color.
  23864. */
  23865. class ColorKeyframeTrack extends KeyframeTrack {}
  23866. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23867. /**
  23868. * A Track of numeric keyframe values.
  23869. */
  23870. class NumberKeyframeTrack extends KeyframeTrack {}
  23871. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23872. /**
  23873. * Spherical linear unit quaternion interpolant.
  23874. */
  23875. class QuaternionLinearInterpolant extends Interpolant {
  23876. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23877. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23878. }
  23879. interpolate_( i1, t0, t, t1 ) {
  23880. const result = this.resultBuffer,
  23881. values = this.sampleValues,
  23882. stride = this.valueSize,
  23883. alpha = ( t - t0 ) / ( t1 - t0 );
  23884. let offset = i1 * stride;
  23885. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23886. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23887. }
  23888. return result;
  23889. }
  23890. }
  23891. /**
  23892. * A Track of quaternion keyframe values.
  23893. */
  23894. class QuaternionKeyframeTrack extends KeyframeTrack {
  23895. InterpolantFactoryMethodLinear( result ) {
  23896. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23897. }
  23898. }
  23899. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23900. // ValueBufferType is inherited
  23901. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23902. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23903. /**
  23904. * A Track that interpolates Strings
  23905. */
  23906. class StringKeyframeTrack extends KeyframeTrack {}
  23907. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23908. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23909. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23910. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23911. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23912. /**
  23913. * A Track of vectored keyframe values.
  23914. */
  23915. class VectorKeyframeTrack extends KeyframeTrack {}
  23916. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23917. class AnimationClip {
  23918. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23919. this.name = name;
  23920. this.tracks = tracks;
  23921. this.duration = duration;
  23922. this.blendMode = blendMode;
  23923. this.uuid = generateUUID();
  23924. // this means it should figure out its duration by scanning the tracks
  23925. if ( this.duration < 0 ) {
  23926. this.resetDuration();
  23927. }
  23928. }
  23929. static parse( json ) {
  23930. const tracks = [],
  23931. jsonTracks = json.tracks,
  23932. frameTime = 1.0 / ( json.fps || 1.0 );
  23933. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23934. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23935. }
  23936. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23937. clip.uuid = json.uuid;
  23938. return clip;
  23939. }
  23940. static toJSON( clip ) {
  23941. const tracks = [],
  23942. clipTracks = clip.tracks;
  23943. const json = {
  23944. 'name': clip.name,
  23945. 'duration': clip.duration,
  23946. 'tracks': tracks,
  23947. 'uuid': clip.uuid,
  23948. 'blendMode': clip.blendMode
  23949. };
  23950. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23951. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23952. }
  23953. return json;
  23954. }
  23955. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23956. const numMorphTargets = morphTargetSequence.length;
  23957. const tracks = [];
  23958. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23959. let times = [];
  23960. let values = [];
  23961. times.push(
  23962. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23963. i,
  23964. ( i + 1 ) % numMorphTargets );
  23965. values.push( 0, 1, 0 );
  23966. const order = getKeyframeOrder( times );
  23967. times = sortedArray( times, 1, order );
  23968. values = sortedArray( values, 1, order );
  23969. // if there is a key at the first frame, duplicate it as the
  23970. // last frame as well for perfect loop.
  23971. if ( ! noLoop && times[ 0 ] === 0 ) {
  23972. times.push( numMorphTargets );
  23973. values.push( values[ 0 ] );
  23974. }
  23975. tracks.push(
  23976. new NumberKeyframeTrack(
  23977. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23978. times, values
  23979. ).scale( 1.0 / fps ) );
  23980. }
  23981. return new this( name, - 1, tracks );
  23982. }
  23983. static findByName( objectOrClipArray, name ) {
  23984. let clipArray = objectOrClipArray;
  23985. if ( ! Array.isArray( objectOrClipArray ) ) {
  23986. const o = objectOrClipArray;
  23987. clipArray = o.geometry && o.geometry.animations || o.animations;
  23988. }
  23989. for ( let i = 0; i < clipArray.length; i ++ ) {
  23990. if ( clipArray[ i ].name === name ) {
  23991. return clipArray[ i ];
  23992. }
  23993. }
  23994. return null;
  23995. }
  23996. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23997. const animationToMorphTargets = {};
  23998. // tested with https://regex101.com/ on trick sequences
  23999. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  24000. const pattern = /^([\w-]*?)([\d]+)$/;
  24001. // sort morph target names into animation groups based
  24002. // patterns like Walk_001, Walk_002, Run_001, Run_002
  24003. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  24004. const morphTarget = morphTargets[ i ];
  24005. const parts = morphTarget.name.match( pattern );
  24006. if ( parts && parts.length > 1 ) {
  24007. const name = parts[ 1 ];
  24008. let animationMorphTargets = animationToMorphTargets[ name ];
  24009. if ( ! animationMorphTargets ) {
  24010. animationToMorphTargets[ name ] = animationMorphTargets = [];
  24011. }
  24012. animationMorphTargets.push( morphTarget );
  24013. }
  24014. }
  24015. const clips = [];
  24016. for ( const name in animationToMorphTargets ) {
  24017. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  24018. }
  24019. return clips;
  24020. }
  24021. // parse the animation.hierarchy format
  24022. static parseAnimation( animation, bones ) {
  24023. if ( ! animation ) {
  24024. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  24025. return null;
  24026. }
  24027. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  24028. // only return track if there are actually keys.
  24029. if ( animationKeys.length !== 0 ) {
  24030. const times = [];
  24031. const values = [];
  24032. flattenJSON( animationKeys, times, values, propertyName );
  24033. // empty keys are filtered out, so check again
  24034. if ( times.length !== 0 ) {
  24035. destTracks.push( new trackType( trackName, times, values ) );
  24036. }
  24037. }
  24038. };
  24039. const tracks = [];
  24040. const clipName = animation.name || 'default';
  24041. const fps = animation.fps || 30;
  24042. const blendMode = animation.blendMode;
  24043. // automatic length determination in AnimationClip.
  24044. let duration = animation.length || - 1;
  24045. const hierarchyTracks = animation.hierarchy || [];
  24046. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  24047. const animationKeys = hierarchyTracks[ h ].keys;
  24048. // skip empty tracks
  24049. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  24050. // process morph targets
  24051. if ( animationKeys[ 0 ].morphTargets ) {
  24052. // figure out all morph targets used in this track
  24053. const morphTargetNames = {};
  24054. let k;
  24055. for ( k = 0; k < animationKeys.length; k ++ ) {
  24056. if ( animationKeys[ k ].morphTargets ) {
  24057. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  24058. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  24059. }
  24060. }
  24061. }
  24062. // create a track for each morph target with all zero
  24063. // morphTargetInfluences except for the keys in which
  24064. // the morphTarget is named.
  24065. for ( const morphTargetName in morphTargetNames ) {
  24066. const times = [];
  24067. const values = [];
  24068. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  24069. const animationKey = animationKeys[ k ];
  24070. times.push( animationKey.time );
  24071. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  24072. }
  24073. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  24074. }
  24075. duration = morphTargetNames.length * fps;
  24076. } else {
  24077. // ...assume skeletal animation
  24078. const boneName = '.bones[' + bones[ h ].name + ']';
  24079. addNonemptyTrack(
  24080. VectorKeyframeTrack, boneName + '.position',
  24081. animationKeys, 'pos', tracks );
  24082. addNonemptyTrack(
  24083. QuaternionKeyframeTrack, boneName + '.quaternion',
  24084. animationKeys, 'rot', tracks );
  24085. addNonemptyTrack(
  24086. VectorKeyframeTrack, boneName + '.scale',
  24087. animationKeys, 'scl', tracks );
  24088. }
  24089. }
  24090. if ( tracks.length === 0 ) {
  24091. return null;
  24092. }
  24093. const clip = new this( clipName, duration, tracks, blendMode );
  24094. return clip;
  24095. }
  24096. resetDuration() {
  24097. const tracks = this.tracks;
  24098. let duration = 0;
  24099. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  24100. const track = this.tracks[ i ];
  24101. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  24102. }
  24103. this.duration = duration;
  24104. return this;
  24105. }
  24106. trim() {
  24107. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24108. this.tracks[ i ].trim( 0, this.duration );
  24109. }
  24110. return this;
  24111. }
  24112. validate() {
  24113. let valid = true;
  24114. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24115. valid = valid && this.tracks[ i ].validate();
  24116. }
  24117. return valid;
  24118. }
  24119. optimize() {
  24120. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24121. this.tracks[ i ].optimize();
  24122. }
  24123. return this;
  24124. }
  24125. clone() {
  24126. const tracks = [];
  24127. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24128. tracks.push( this.tracks[ i ].clone() );
  24129. }
  24130. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  24131. }
  24132. toJSON() {
  24133. return this.constructor.toJSON( this );
  24134. }
  24135. }
  24136. function getTrackTypeForValueTypeName( typeName ) {
  24137. switch ( typeName.toLowerCase() ) {
  24138. case 'scalar':
  24139. case 'double':
  24140. case 'float':
  24141. case 'number':
  24142. case 'integer':
  24143. return NumberKeyframeTrack;
  24144. case 'vector':
  24145. case 'vector2':
  24146. case 'vector3':
  24147. case 'vector4':
  24148. return VectorKeyframeTrack;
  24149. case 'color':
  24150. return ColorKeyframeTrack;
  24151. case 'quaternion':
  24152. return QuaternionKeyframeTrack;
  24153. case 'bool':
  24154. case 'boolean':
  24155. return BooleanKeyframeTrack;
  24156. case 'string':
  24157. return StringKeyframeTrack;
  24158. }
  24159. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  24160. }
  24161. function parseKeyframeTrack( json ) {
  24162. if ( json.type === undefined ) {
  24163. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  24164. }
  24165. const trackType = getTrackTypeForValueTypeName( json.type );
  24166. if ( json.times === undefined ) {
  24167. const times = [], values = [];
  24168. flattenJSON( json.keys, times, values, 'value' );
  24169. json.times = times;
  24170. json.values = values;
  24171. }
  24172. // derived classes can define a static parse method
  24173. if ( trackType.parse !== undefined ) {
  24174. return trackType.parse( json );
  24175. } else {
  24176. // by default, we assume a constructor compatible with the base
  24177. return new trackType( json.name, json.times, json.values, json.interpolation );
  24178. }
  24179. }
  24180. const Cache = {
  24181. enabled: false,
  24182. files: {},
  24183. add: function ( key, file ) {
  24184. if ( this.enabled === false ) return;
  24185. // console.log( 'THREE.Cache', 'Adding key:', key );
  24186. this.files[ key ] = file;
  24187. },
  24188. get: function ( key ) {
  24189. if ( this.enabled === false ) return;
  24190. // console.log( 'THREE.Cache', 'Checking key:', key );
  24191. return this.files[ key ];
  24192. },
  24193. remove: function ( key ) {
  24194. delete this.files[ key ];
  24195. },
  24196. clear: function () {
  24197. this.files = {};
  24198. }
  24199. };
  24200. class LoadingManager {
  24201. constructor( onLoad, onProgress, onError ) {
  24202. const scope = this;
  24203. let isLoading = false;
  24204. let itemsLoaded = 0;
  24205. let itemsTotal = 0;
  24206. let urlModifier = undefined;
  24207. const handlers = [];
  24208. // Refer to #5689 for the reason why we don't set .onStart
  24209. // in the constructor
  24210. this.onStart = undefined;
  24211. this.onLoad = onLoad;
  24212. this.onProgress = onProgress;
  24213. this.onError = onError;
  24214. this.itemStart = function ( url ) {
  24215. itemsTotal ++;
  24216. if ( isLoading === false ) {
  24217. if ( scope.onStart !== undefined ) {
  24218. scope.onStart( url, itemsLoaded, itemsTotal );
  24219. }
  24220. }
  24221. isLoading = true;
  24222. };
  24223. this.itemEnd = function ( url ) {
  24224. itemsLoaded ++;
  24225. if ( scope.onProgress !== undefined ) {
  24226. scope.onProgress( url, itemsLoaded, itemsTotal );
  24227. }
  24228. if ( itemsLoaded === itemsTotal ) {
  24229. isLoading = false;
  24230. if ( scope.onLoad !== undefined ) {
  24231. scope.onLoad();
  24232. }
  24233. }
  24234. };
  24235. this.itemError = function ( url ) {
  24236. if ( scope.onError !== undefined ) {
  24237. scope.onError( url );
  24238. }
  24239. };
  24240. this.resolveURL = function ( url ) {
  24241. if ( urlModifier ) {
  24242. return urlModifier( url );
  24243. }
  24244. return url;
  24245. };
  24246. this.setURLModifier = function ( transform ) {
  24247. urlModifier = transform;
  24248. return this;
  24249. };
  24250. this.addHandler = function ( regex, loader ) {
  24251. handlers.push( regex, loader );
  24252. return this;
  24253. };
  24254. this.removeHandler = function ( regex ) {
  24255. const index = handlers.indexOf( regex );
  24256. if ( index !== - 1 ) {
  24257. handlers.splice( index, 2 );
  24258. }
  24259. return this;
  24260. };
  24261. this.getHandler = function ( file ) {
  24262. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  24263. const regex = handlers[ i ];
  24264. const loader = handlers[ i + 1 ];
  24265. if ( regex.global ) regex.lastIndex = 0; // see #17920
  24266. if ( regex.test( file ) ) {
  24267. return loader;
  24268. }
  24269. }
  24270. return null;
  24271. };
  24272. }
  24273. }
  24274. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  24275. class Loader {
  24276. constructor( manager ) {
  24277. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24278. this.crossOrigin = 'anonymous';
  24279. this.withCredentials = false;
  24280. this.path = '';
  24281. this.resourcePath = '';
  24282. this.requestHeader = {};
  24283. }
  24284. load( /* url, onLoad, onProgress, onError */ ) {}
  24285. loadAsync( url, onProgress ) {
  24286. const scope = this;
  24287. return new Promise( function ( resolve, reject ) {
  24288. scope.load( url, resolve, onProgress, reject );
  24289. } );
  24290. }
  24291. parse( /* data */ ) {}
  24292. setCrossOrigin( crossOrigin ) {
  24293. this.crossOrigin = crossOrigin;
  24294. return this;
  24295. }
  24296. setWithCredentials( value ) {
  24297. this.withCredentials = value;
  24298. return this;
  24299. }
  24300. setPath( path ) {
  24301. this.path = path;
  24302. return this;
  24303. }
  24304. setResourcePath( resourcePath ) {
  24305. this.resourcePath = resourcePath;
  24306. return this;
  24307. }
  24308. setRequestHeader( requestHeader ) {
  24309. this.requestHeader = requestHeader;
  24310. return this;
  24311. }
  24312. }
  24313. const loading = {};
  24314. class HttpError extends Error {
  24315. constructor( message, response ) {
  24316. super( message );
  24317. this.response = response;
  24318. }
  24319. }
  24320. class FileLoader extends Loader {
  24321. constructor( manager ) {
  24322. super( manager );
  24323. }
  24324. load( url, onLoad, onProgress, onError ) {
  24325. if ( url === undefined ) url = '';
  24326. if ( this.path !== undefined ) url = this.path + url;
  24327. url = this.manager.resolveURL( url );
  24328. const cached = Cache.get( url );
  24329. if ( cached !== undefined ) {
  24330. this.manager.itemStart( url );
  24331. setTimeout( () => {
  24332. if ( onLoad ) onLoad( cached );
  24333. this.manager.itemEnd( url );
  24334. }, 0 );
  24335. return cached;
  24336. }
  24337. // Check if request is duplicate
  24338. if ( loading[ url ] !== undefined ) {
  24339. loading[ url ].push( {
  24340. onLoad: onLoad,
  24341. onProgress: onProgress,
  24342. onError: onError
  24343. } );
  24344. return;
  24345. }
  24346. // Initialise array for duplicate requests
  24347. loading[ url ] = [];
  24348. loading[ url ].push( {
  24349. onLoad: onLoad,
  24350. onProgress: onProgress,
  24351. onError: onError,
  24352. } );
  24353. // create request
  24354. const req = new Request( url, {
  24355. headers: new Headers( this.requestHeader ),
  24356. credentials: this.withCredentials ? 'include' : 'same-origin',
  24357. // An abort controller could be added within a future PR
  24358. } );
  24359. // record states ( avoid data race )
  24360. const mimeType = this.mimeType;
  24361. const responseType = this.responseType;
  24362. // start the fetch
  24363. fetch( req )
  24364. .then( response => {
  24365. if ( response.status === 200 || response.status === 0 ) {
  24366. // Some browsers return HTTP Status 0 when using non-http protocol
  24367. // e.g. 'file://' or 'data://'. Handle as success.
  24368. if ( response.status === 0 ) {
  24369. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24370. }
  24371. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24372. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  24373. return response;
  24374. }
  24375. const callbacks = loading[ url ];
  24376. const reader = response.body.getReader();
  24377. // Nginx needs X-File-Size check
  24378. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24379. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  24380. const total = contentLength ? parseInt( contentLength ) : 0;
  24381. const lengthComputable = total !== 0;
  24382. let loaded = 0;
  24383. // periodically read data into the new stream tracking while download progress
  24384. const stream = new ReadableStream( {
  24385. start( controller ) {
  24386. readData();
  24387. function readData() {
  24388. reader.read().then( ( { done, value } ) => {
  24389. if ( done ) {
  24390. controller.close();
  24391. } else {
  24392. loaded += value.byteLength;
  24393. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  24394. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24395. const callback = callbacks[ i ];
  24396. if ( callback.onProgress ) callback.onProgress( event );
  24397. }
  24398. controller.enqueue( value );
  24399. readData();
  24400. }
  24401. } );
  24402. }
  24403. }
  24404. } );
  24405. return new Response( stream );
  24406. } else {
  24407. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  24408. }
  24409. } )
  24410. .then( response => {
  24411. switch ( responseType ) {
  24412. case 'arraybuffer':
  24413. return response.arrayBuffer();
  24414. case 'blob':
  24415. return response.blob();
  24416. case 'document':
  24417. return response.text()
  24418. .then( text => {
  24419. const parser = new DOMParser();
  24420. return parser.parseFromString( text, mimeType );
  24421. } );
  24422. case 'json':
  24423. return response.json();
  24424. default:
  24425. if ( mimeType === undefined ) {
  24426. return response.text();
  24427. } else {
  24428. // sniff encoding
  24429. const re = /charset="?([^;"\s]*)"?/i;
  24430. const exec = re.exec( mimeType );
  24431. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  24432. const decoder = new TextDecoder( label );
  24433. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  24434. }
  24435. }
  24436. } )
  24437. .then( data => {
  24438. // Add to cache only on HTTP success, so that we do not cache
  24439. // error response bodies as proper responses to requests.
  24440. Cache.add( url, data );
  24441. const callbacks = loading[ url ];
  24442. delete loading[ url ];
  24443. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24444. const callback = callbacks[ i ];
  24445. if ( callback.onLoad ) callback.onLoad( data );
  24446. }
  24447. } )
  24448. .catch( err => {
  24449. // Abort errors and other errors are handled the same
  24450. const callbacks = loading[ url ];
  24451. if ( callbacks === undefined ) {
  24452. // When onLoad was called and url was deleted in `loading`
  24453. this.manager.itemError( url );
  24454. throw err;
  24455. }
  24456. delete loading[ url ];
  24457. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24458. const callback = callbacks[ i ];
  24459. if ( callback.onError ) callback.onError( err );
  24460. }
  24461. this.manager.itemError( url );
  24462. } )
  24463. .finally( () => {
  24464. this.manager.itemEnd( url );
  24465. } );
  24466. this.manager.itemStart( url );
  24467. }
  24468. setResponseType( value ) {
  24469. this.responseType = value;
  24470. return this;
  24471. }
  24472. setMimeType( value ) {
  24473. this.mimeType = value;
  24474. return this;
  24475. }
  24476. }
  24477. class AnimationLoader extends Loader {
  24478. constructor( manager ) {
  24479. super( manager );
  24480. }
  24481. load( url, onLoad, onProgress, onError ) {
  24482. const scope = this;
  24483. const loader = new FileLoader( this.manager );
  24484. loader.setPath( this.path );
  24485. loader.setRequestHeader( this.requestHeader );
  24486. loader.setWithCredentials( this.withCredentials );
  24487. loader.load( url, function ( text ) {
  24488. try {
  24489. onLoad( scope.parse( JSON.parse( text ) ) );
  24490. } catch ( e ) {
  24491. if ( onError ) {
  24492. onError( e );
  24493. } else {
  24494. console.error( e );
  24495. }
  24496. scope.manager.itemError( url );
  24497. }
  24498. }, onProgress, onError );
  24499. }
  24500. parse( json ) {
  24501. const animations = [];
  24502. for ( let i = 0; i < json.length; i ++ ) {
  24503. const clip = AnimationClip.parse( json[ i ] );
  24504. animations.push( clip );
  24505. }
  24506. return animations;
  24507. }
  24508. }
  24509. /**
  24510. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24511. *
  24512. * Sub classes have to implement the parse() method which will be used in load().
  24513. */
  24514. class CompressedTextureLoader extends Loader {
  24515. constructor( manager ) {
  24516. super( manager );
  24517. }
  24518. load( url, onLoad, onProgress, onError ) {
  24519. const scope = this;
  24520. const images = [];
  24521. const texture = new CompressedTexture();
  24522. const loader = new FileLoader( this.manager );
  24523. loader.setPath( this.path );
  24524. loader.setResponseType( 'arraybuffer' );
  24525. loader.setRequestHeader( this.requestHeader );
  24526. loader.setWithCredentials( scope.withCredentials );
  24527. let loaded = 0;
  24528. function loadTexture( i ) {
  24529. loader.load( url[ i ], function ( buffer ) {
  24530. const texDatas = scope.parse( buffer, true );
  24531. images[ i ] = {
  24532. width: texDatas.width,
  24533. height: texDatas.height,
  24534. format: texDatas.format,
  24535. mipmaps: texDatas.mipmaps
  24536. };
  24537. loaded += 1;
  24538. if ( loaded === 6 ) {
  24539. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24540. texture.image = images;
  24541. texture.format = texDatas.format;
  24542. texture.needsUpdate = true;
  24543. if ( onLoad ) onLoad( texture );
  24544. }
  24545. }, onProgress, onError );
  24546. }
  24547. if ( Array.isArray( url ) ) {
  24548. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24549. loadTexture( i );
  24550. }
  24551. } else {
  24552. // compressed cubemap texture stored in a single DDS file
  24553. loader.load( url, function ( buffer ) {
  24554. const texDatas = scope.parse( buffer, true );
  24555. if ( texDatas.isCubemap ) {
  24556. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24557. for ( let f = 0; f < faces; f ++ ) {
  24558. images[ f ] = { mipmaps: [] };
  24559. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24560. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24561. images[ f ].format = texDatas.format;
  24562. images[ f ].width = texDatas.width;
  24563. images[ f ].height = texDatas.height;
  24564. }
  24565. }
  24566. texture.image = images;
  24567. } else {
  24568. texture.image.width = texDatas.width;
  24569. texture.image.height = texDatas.height;
  24570. texture.mipmaps = texDatas.mipmaps;
  24571. }
  24572. if ( texDatas.mipmapCount === 1 ) {
  24573. texture.minFilter = LinearFilter;
  24574. }
  24575. texture.format = texDatas.format;
  24576. texture.needsUpdate = true;
  24577. if ( onLoad ) onLoad( texture );
  24578. }, onProgress, onError );
  24579. }
  24580. return texture;
  24581. }
  24582. }
  24583. class ImageLoader extends Loader {
  24584. constructor( manager ) {
  24585. super( manager );
  24586. }
  24587. load( url, onLoad, onProgress, onError ) {
  24588. if ( this.path !== undefined ) url = this.path + url;
  24589. url = this.manager.resolveURL( url );
  24590. const scope = this;
  24591. const cached = Cache.get( url );
  24592. if ( cached !== undefined ) {
  24593. scope.manager.itemStart( url );
  24594. setTimeout( function () {
  24595. if ( onLoad ) onLoad( cached );
  24596. scope.manager.itemEnd( url );
  24597. }, 0 );
  24598. return cached;
  24599. }
  24600. const image = createElementNS( 'img' );
  24601. function onImageLoad() {
  24602. removeEventListeners();
  24603. Cache.add( url, this );
  24604. if ( onLoad ) onLoad( this );
  24605. scope.manager.itemEnd( url );
  24606. }
  24607. function onImageError( event ) {
  24608. removeEventListeners();
  24609. if ( onError ) onError( event );
  24610. scope.manager.itemError( url );
  24611. scope.manager.itemEnd( url );
  24612. }
  24613. function removeEventListeners() {
  24614. image.removeEventListener( 'load', onImageLoad, false );
  24615. image.removeEventListener( 'error', onImageError, false );
  24616. }
  24617. image.addEventListener( 'load', onImageLoad, false );
  24618. image.addEventListener( 'error', onImageError, false );
  24619. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24620. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24621. }
  24622. scope.manager.itemStart( url );
  24623. image.src = url;
  24624. return image;
  24625. }
  24626. }
  24627. class CubeTextureLoader extends Loader {
  24628. constructor( manager ) {
  24629. super( manager );
  24630. }
  24631. load( urls, onLoad, onProgress, onError ) {
  24632. const texture = new CubeTexture();
  24633. const loader = new ImageLoader( this.manager );
  24634. loader.setCrossOrigin( this.crossOrigin );
  24635. loader.setPath( this.path );
  24636. let loaded = 0;
  24637. function loadTexture( i ) {
  24638. loader.load( urls[ i ], function ( image ) {
  24639. texture.images[ i ] = image;
  24640. loaded ++;
  24641. if ( loaded === 6 ) {
  24642. texture.needsUpdate = true;
  24643. if ( onLoad ) onLoad( texture );
  24644. }
  24645. }, undefined, onError );
  24646. }
  24647. for ( let i = 0; i < urls.length; ++ i ) {
  24648. loadTexture( i );
  24649. }
  24650. return texture;
  24651. }
  24652. }
  24653. /**
  24654. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24655. *
  24656. * Sub classes have to implement the parse() method which will be used in load().
  24657. */
  24658. class DataTextureLoader extends Loader {
  24659. constructor( manager ) {
  24660. super( manager );
  24661. }
  24662. load( url, onLoad, onProgress, onError ) {
  24663. const scope = this;
  24664. const texture = new DataTexture();
  24665. const loader = new FileLoader( this.manager );
  24666. loader.setResponseType( 'arraybuffer' );
  24667. loader.setRequestHeader( this.requestHeader );
  24668. loader.setPath( this.path );
  24669. loader.setWithCredentials( scope.withCredentials );
  24670. loader.load( url, function ( buffer ) {
  24671. const texData = scope.parse( buffer );
  24672. if ( ! texData ) return;
  24673. if ( texData.image !== undefined ) {
  24674. texture.image = texData.image;
  24675. } else if ( texData.data !== undefined ) {
  24676. texture.image.width = texData.width;
  24677. texture.image.height = texData.height;
  24678. texture.image.data = texData.data;
  24679. }
  24680. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24681. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24682. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24683. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24684. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24685. if ( texData.encoding !== undefined ) {
  24686. texture.encoding = texData.encoding;
  24687. }
  24688. if ( texData.flipY !== undefined ) {
  24689. texture.flipY = texData.flipY;
  24690. }
  24691. if ( texData.format !== undefined ) {
  24692. texture.format = texData.format;
  24693. }
  24694. if ( texData.type !== undefined ) {
  24695. texture.type = texData.type;
  24696. }
  24697. if ( texData.mipmaps !== undefined ) {
  24698. texture.mipmaps = texData.mipmaps;
  24699. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24700. }
  24701. if ( texData.mipmapCount === 1 ) {
  24702. texture.minFilter = LinearFilter;
  24703. }
  24704. if ( texData.generateMipmaps !== undefined ) {
  24705. texture.generateMipmaps = texData.generateMipmaps;
  24706. }
  24707. texture.needsUpdate = true;
  24708. if ( onLoad ) onLoad( texture, texData );
  24709. }, onProgress, onError );
  24710. return texture;
  24711. }
  24712. }
  24713. class TextureLoader extends Loader {
  24714. constructor( manager ) {
  24715. super( manager );
  24716. }
  24717. load( url, onLoad, onProgress, onError ) {
  24718. const texture = new Texture();
  24719. const loader = new ImageLoader( this.manager );
  24720. loader.setCrossOrigin( this.crossOrigin );
  24721. loader.setPath( this.path );
  24722. loader.load( url, function ( image ) {
  24723. texture.image = image;
  24724. texture.needsUpdate = true;
  24725. if ( onLoad !== undefined ) {
  24726. onLoad( texture );
  24727. }
  24728. }, onProgress, onError );
  24729. return texture;
  24730. }
  24731. }
  24732. class Light extends Object3D {
  24733. constructor( color, intensity = 1 ) {
  24734. super();
  24735. this.isLight = true;
  24736. this.type = 'Light';
  24737. this.color = new Color( color );
  24738. this.intensity = intensity;
  24739. }
  24740. dispose() {
  24741. // Empty here in base class; some subclasses override.
  24742. }
  24743. copy( source, recursive ) {
  24744. super.copy( source, recursive );
  24745. this.color.copy( source.color );
  24746. this.intensity = source.intensity;
  24747. return this;
  24748. }
  24749. toJSON( meta ) {
  24750. const data = super.toJSON( meta );
  24751. data.object.color = this.color.getHex();
  24752. data.object.intensity = this.intensity;
  24753. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24754. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24755. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24756. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24757. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24758. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24759. return data;
  24760. }
  24761. }
  24762. class HemisphereLight extends Light {
  24763. constructor( skyColor, groundColor, intensity ) {
  24764. super( skyColor, intensity );
  24765. this.isHemisphereLight = true;
  24766. this.type = 'HemisphereLight';
  24767. this.position.copy( Object3D.DEFAULT_UP );
  24768. this.updateMatrix();
  24769. this.groundColor = new Color( groundColor );
  24770. }
  24771. copy( source, recursive ) {
  24772. super.copy( source, recursive );
  24773. this.groundColor.copy( source.groundColor );
  24774. return this;
  24775. }
  24776. }
  24777. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24778. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24779. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24780. class LightShadow {
  24781. constructor( camera ) {
  24782. this.camera = camera;
  24783. this.bias = 0;
  24784. this.normalBias = 0;
  24785. this.radius = 1;
  24786. this.blurSamples = 8;
  24787. this.mapSize = new Vector2( 512, 512 );
  24788. this.map = null;
  24789. this.mapPass = null;
  24790. this.matrix = new Matrix4();
  24791. this.autoUpdate = true;
  24792. this.needsUpdate = false;
  24793. this._frustum = new Frustum();
  24794. this._frameExtents = new Vector2( 1, 1 );
  24795. this._viewportCount = 1;
  24796. this._viewports = [
  24797. new Vector4( 0, 0, 1, 1 )
  24798. ];
  24799. }
  24800. getViewportCount() {
  24801. return this._viewportCount;
  24802. }
  24803. getFrustum() {
  24804. return this._frustum;
  24805. }
  24806. updateMatrices( light ) {
  24807. const shadowCamera = this.camera;
  24808. const shadowMatrix = this.matrix;
  24809. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24810. shadowCamera.position.copy( _lightPositionWorld$1 );
  24811. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24812. shadowCamera.lookAt( _lookTarget$1 );
  24813. shadowCamera.updateMatrixWorld();
  24814. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24815. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24816. shadowMatrix.set(
  24817. 0.5, 0.0, 0.0, 0.5,
  24818. 0.0, 0.5, 0.0, 0.5,
  24819. 0.0, 0.0, 0.5, 0.5,
  24820. 0.0, 0.0, 0.0, 1.0
  24821. );
  24822. shadowMatrix.multiply( _projScreenMatrix$1 );
  24823. }
  24824. getViewport( viewportIndex ) {
  24825. return this._viewports[ viewportIndex ];
  24826. }
  24827. getFrameExtents() {
  24828. return this._frameExtents;
  24829. }
  24830. dispose() {
  24831. if ( this.map ) {
  24832. this.map.dispose();
  24833. }
  24834. if ( this.mapPass ) {
  24835. this.mapPass.dispose();
  24836. }
  24837. }
  24838. copy( source ) {
  24839. this.camera = source.camera.clone();
  24840. this.bias = source.bias;
  24841. this.radius = source.radius;
  24842. this.mapSize.copy( source.mapSize );
  24843. return this;
  24844. }
  24845. clone() {
  24846. return new this.constructor().copy( this );
  24847. }
  24848. toJSON() {
  24849. const object = {};
  24850. if ( this.bias !== 0 ) object.bias = this.bias;
  24851. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24852. if ( this.radius !== 1 ) object.radius = this.radius;
  24853. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24854. object.camera = this.camera.toJSON( false ).object;
  24855. delete object.camera.matrix;
  24856. return object;
  24857. }
  24858. }
  24859. class SpotLightShadow extends LightShadow {
  24860. constructor() {
  24861. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24862. this.isSpotLightShadow = true;
  24863. this.focus = 1;
  24864. }
  24865. updateMatrices( light ) {
  24866. const camera = this.camera;
  24867. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24868. const aspect = this.mapSize.width / this.mapSize.height;
  24869. const far = light.distance || camera.far;
  24870. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24871. camera.fov = fov;
  24872. camera.aspect = aspect;
  24873. camera.far = far;
  24874. camera.updateProjectionMatrix();
  24875. }
  24876. super.updateMatrices( light );
  24877. }
  24878. copy( source ) {
  24879. super.copy( source );
  24880. this.focus = source.focus;
  24881. return this;
  24882. }
  24883. }
  24884. class SpotLight extends Light {
  24885. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  24886. super( color, intensity );
  24887. this.isSpotLight = true;
  24888. this.type = 'SpotLight';
  24889. this.position.copy( Object3D.DEFAULT_UP );
  24890. this.updateMatrix();
  24891. this.target = new Object3D();
  24892. this.distance = distance;
  24893. this.angle = angle;
  24894. this.penumbra = penumbra;
  24895. this.decay = decay;
  24896. this.map = null;
  24897. this.shadow = new SpotLightShadow();
  24898. }
  24899. get power() {
  24900. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24901. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24902. return this.intensity * Math.PI;
  24903. }
  24904. set power( power ) {
  24905. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24906. this.intensity = power / Math.PI;
  24907. }
  24908. dispose() {
  24909. this.shadow.dispose();
  24910. }
  24911. copy( source, recursive ) {
  24912. super.copy( source, recursive );
  24913. this.distance = source.distance;
  24914. this.angle = source.angle;
  24915. this.penumbra = source.penumbra;
  24916. this.decay = source.decay;
  24917. this.target = source.target.clone();
  24918. this.shadow = source.shadow.clone();
  24919. return this;
  24920. }
  24921. }
  24922. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24923. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24924. const _lookTarget = /*@__PURE__*/ new Vector3();
  24925. class PointLightShadow extends LightShadow {
  24926. constructor() {
  24927. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24928. this.isPointLightShadow = true;
  24929. this._frameExtents = new Vector2( 4, 2 );
  24930. this._viewportCount = 6;
  24931. this._viewports = [
  24932. // These viewports map a cube-map onto a 2D texture with the
  24933. // following orientation:
  24934. //
  24935. // xzXZ
  24936. // y Y
  24937. //
  24938. // X - Positive x direction
  24939. // x - Negative x direction
  24940. // Y - Positive y direction
  24941. // y - Negative y direction
  24942. // Z - Positive z direction
  24943. // z - Negative z direction
  24944. // positive X
  24945. new Vector4( 2, 1, 1, 1 ),
  24946. // negative X
  24947. new Vector4( 0, 1, 1, 1 ),
  24948. // positive Z
  24949. new Vector4( 3, 1, 1, 1 ),
  24950. // negative Z
  24951. new Vector4( 1, 1, 1, 1 ),
  24952. // positive Y
  24953. new Vector4( 3, 0, 1, 1 ),
  24954. // negative Y
  24955. new Vector4( 1, 0, 1, 1 )
  24956. ];
  24957. this._cubeDirections = [
  24958. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24959. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24960. ];
  24961. this._cubeUps = [
  24962. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24963. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24964. ];
  24965. }
  24966. updateMatrices( light, viewportIndex = 0 ) {
  24967. const camera = this.camera;
  24968. const shadowMatrix = this.matrix;
  24969. const far = light.distance || camera.far;
  24970. if ( far !== camera.far ) {
  24971. camera.far = far;
  24972. camera.updateProjectionMatrix();
  24973. }
  24974. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24975. camera.position.copy( _lightPositionWorld );
  24976. _lookTarget.copy( camera.position );
  24977. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24978. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24979. camera.lookAt( _lookTarget );
  24980. camera.updateMatrixWorld();
  24981. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24982. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24983. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24984. }
  24985. }
  24986. class PointLight extends Light {
  24987. constructor( color, intensity, distance = 0, decay = 2 ) {
  24988. super( color, intensity );
  24989. this.isPointLight = true;
  24990. this.type = 'PointLight';
  24991. this.distance = distance;
  24992. this.decay = decay;
  24993. this.shadow = new PointLightShadow();
  24994. }
  24995. get power() {
  24996. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24997. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24998. return this.intensity * 4 * Math.PI;
  24999. }
  25000. set power( power ) {
  25001. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25002. this.intensity = power / ( 4 * Math.PI );
  25003. }
  25004. dispose() {
  25005. this.shadow.dispose();
  25006. }
  25007. copy( source, recursive ) {
  25008. super.copy( source, recursive );
  25009. this.distance = source.distance;
  25010. this.decay = source.decay;
  25011. this.shadow = source.shadow.clone();
  25012. return this;
  25013. }
  25014. }
  25015. class DirectionalLightShadow extends LightShadow {
  25016. constructor() {
  25017. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  25018. this.isDirectionalLightShadow = true;
  25019. }
  25020. }
  25021. class DirectionalLight extends Light {
  25022. constructor( color, intensity ) {
  25023. super( color, intensity );
  25024. this.isDirectionalLight = true;
  25025. this.type = 'DirectionalLight';
  25026. this.position.copy( Object3D.DEFAULT_UP );
  25027. this.updateMatrix();
  25028. this.target = new Object3D();
  25029. this.shadow = new DirectionalLightShadow();
  25030. }
  25031. dispose() {
  25032. this.shadow.dispose();
  25033. }
  25034. copy( source ) {
  25035. super.copy( source );
  25036. this.target = source.target.clone();
  25037. this.shadow = source.shadow.clone();
  25038. return this;
  25039. }
  25040. }
  25041. class AmbientLight extends Light {
  25042. constructor( color, intensity ) {
  25043. super( color, intensity );
  25044. this.isAmbientLight = true;
  25045. this.type = 'AmbientLight';
  25046. }
  25047. }
  25048. class RectAreaLight extends Light {
  25049. constructor( color, intensity, width = 10, height = 10 ) {
  25050. super( color, intensity );
  25051. this.isRectAreaLight = true;
  25052. this.type = 'RectAreaLight';
  25053. this.width = width;
  25054. this.height = height;
  25055. }
  25056. get power() {
  25057. // compute the light's luminous power (in lumens) from its intensity (in nits)
  25058. return this.intensity * this.width * this.height * Math.PI;
  25059. }
  25060. set power( power ) {
  25061. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  25062. this.intensity = power / ( this.width * this.height * Math.PI );
  25063. }
  25064. copy( source ) {
  25065. super.copy( source );
  25066. this.width = source.width;
  25067. this.height = source.height;
  25068. return this;
  25069. }
  25070. toJSON( meta ) {
  25071. const data = super.toJSON( meta );
  25072. data.object.width = this.width;
  25073. data.object.height = this.height;
  25074. return data;
  25075. }
  25076. }
  25077. /**
  25078. * Primary reference:
  25079. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25080. *
  25081. * Secondary reference:
  25082. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25083. */
  25084. // 3-band SH defined by 9 coefficients
  25085. class SphericalHarmonics3 {
  25086. constructor() {
  25087. this.isSphericalHarmonics3 = true;
  25088. this.coefficients = [];
  25089. for ( let i = 0; i < 9; i ++ ) {
  25090. this.coefficients.push( new Vector3() );
  25091. }
  25092. }
  25093. set( coefficients ) {
  25094. for ( let i = 0; i < 9; i ++ ) {
  25095. this.coefficients[ i ].copy( coefficients[ i ] );
  25096. }
  25097. return this;
  25098. }
  25099. zero() {
  25100. for ( let i = 0; i < 9; i ++ ) {
  25101. this.coefficients[ i ].set( 0, 0, 0 );
  25102. }
  25103. return this;
  25104. }
  25105. // get the radiance in the direction of the normal
  25106. // target is a Vector3
  25107. getAt( normal, target ) {
  25108. // normal is assumed to be unit length
  25109. const x = normal.x, y = normal.y, z = normal.z;
  25110. const coeff = this.coefficients;
  25111. // band 0
  25112. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  25113. // band 1
  25114. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  25115. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  25116. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  25117. // band 2
  25118. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  25119. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  25120. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  25121. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  25122. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  25123. return target;
  25124. }
  25125. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25126. // target is a Vector3
  25127. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25128. getIrradianceAt( normal, target ) {
  25129. // normal is assumed to be unit length
  25130. const x = normal.x, y = normal.y, z = normal.z;
  25131. const coeff = this.coefficients;
  25132. // band 0
  25133. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  25134. // band 1
  25135. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  25136. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  25137. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  25138. // band 2
  25139. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  25140. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  25141. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  25142. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  25143. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  25144. return target;
  25145. }
  25146. add( sh ) {
  25147. for ( let i = 0; i < 9; i ++ ) {
  25148. this.coefficients[ i ].add( sh.coefficients[ i ] );
  25149. }
  25150. return this;
  25151. }
  25152. addScaledSH( sh, s ) {
  25153. for ( let i = 0; i < 9; i ++ ) {
  25154. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  25155. }
  25156. return this;
  25157. }
  25158. scale( s ) {
  25159. for ( let i = 0; i < 9; i ++ ) {
  25160. this.coefficients[ i ].multiplyScalar( s );
  25161. }
  25162. return this;
  25163. }
  25164. lerp( sh, alpha ) {
  25165. for ( let i = 0; i < 9; i ++ ) {
  25166. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  25167. }
  25168. return this;
  25169. }
  25170. equals( sh ) {
  25171. for ( let i = 0; i < 9; i ++ ) {
  25172. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  25173. return false;
  25174. }
  25175. }
  25176. return true;
  25177. }
  25178. copy( sh ) {
  25179. return this.set( sh.coefficients );
  25180. }
  25181. clone() {
  25182. return new this.constructor().copy( this );
  25183. }
  25184. fromArray( array, offset = 0 ) {
  25185. const coefficients = this.coefficients;
  25186. for ( let i = 0; i < 9; i ++ ) {
  25187. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  25188. }
  25189. return this;
  25190. }
  25191. toArray( array = [], offset = 0 ) {
  25192. const coefficients = this.coefficients;
  25193. for ( let i = 0; i < 9; i ++ ) {
  25194. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  25195. }
  25196. return array;
  25197. }
  25198. // evaluate the basis functions
  25199. // shBasis is an Array[ 9 ]
  25200. static getBasisAt( normal, shBasis ) {
  25201. // normal is assumed to be unit length
  25202. const x = normal.x, y = normal.y, z = normal.z;
  25203. // band 0
  25204. shBasis[ 0 ] = 0.282095;
  25205. // band 1
  25206. shBasis[ 1 ] = 0.488603 * y;
  25207. shBasis[ 2 ] = 0.488603 * z;
  25208. shBasis[ 3 ] = 0.488603 * x;
  25209. // band 2
  25210. shBasis[ 4 ] = 1.092548 * x * y;
  25211. shBasis[ 5 ] = 1.092548 * y * z;
  25212. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  25213. shBasis[ 7 ] = 1.092548 * x * z;
  25214. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  25215. }
  25216. }
  25217. class LightProbe extends Light {
  25218. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  25219. super( undefined, intensity );
  25220. this.isLightProbe = true;
  25221. this.sh = sh;
  25222. }
  25223. copy( source ) {
  25224. super.copy( source );
  25225. this.sh.copy( source.sh );
  25226. return this;
  25227. }
  25228. fromJSON( json ) {
  25229. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  25230. this.sh.fromArray( json.sh );
  25231. return this;
  25232. }
  25233. toJSON( meta ) {
  25234. const data = super.toJSON( meta );
  25235. data.object.sh = this.sh.toArray();
  25236. return data;
  25237. }
  25238. }
  25239. class MaterialLoader extends Loader {
  25240. constructor( manager ) {
  25241. super( manager );
  25242. this.textures = {};
  25243. }
  25244. load( url, onLoad, onProgress, onError ) {
  25245. const scope = this;
  25246. const loader = new FileLoader( scope.manager );
  25247. loader.setPath( scope.path );
  25248. loader.setRequestHeader( scope.requestHeader );
  25249. loader.setWithCredentials( scope.withCredentials );
  25250. loader.load( url, function ( text ) {
  25251. try {
  25252. onLoad( scope.parse( JSON.parse( text ) ) );
  25253. } catch ( e ) {
  25254. if ( onError ) {
  25255. onError( e );
  25256. } else {
  25257. console.error( e );
  25258. }
  25259. scope.manager.itemError( url );
  25260. }
  25261. }, onProgress, onError );
  25262. }
  25263. parse( json ) {
  25264. const textures = this.textures;
  25265. function getTexture( name ) {
  25266. if ( textures[ name ] === undefined ) {
  25267. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25268. }
  25269. return textures[ name ];
  25270. }
  25271. const material = MaterialLoader.createMaterialFromType( json.type );
  25272. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25273. if ( json.name !== undefined ) material.name = json.name;
  25274. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  25275. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25276. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25277. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  25278. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  25279. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  25280. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25281. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  25282. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  25283. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  25284. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25285. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  25286. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  25287. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  25288. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  25289. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  25290. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  25291. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  25292. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  25293. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  25294. if ( json.fog !== undefined ) material.fog = json.fog;
  25295. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25296. if ( json.blending !== undefined ) material.blending = json.blending;
  25297. if ( json.combine !== undefined ) material.combine = json.combine;
  25298. if ( json.side !== undefined ) material.side = json.side;
  25299. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  25300. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25301. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25302. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25303. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25304. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25305. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25306. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  25307. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  25308. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  25309. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  25310. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  25311. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  25312. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  25313. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  25314. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25315. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25316. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25317. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25318. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25319. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25320. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25321. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25322. if ( json.scale !== undefined ) material.scale = json.scale;
  25323. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25324. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25325. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25326. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25327. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  25328. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  25329. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  25330. if ( json.visible !== undefined ) material.visible = json.visible;
  25331. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  25332. if ( json.userData !== undefined ) material.userData = json.userData;
  25333. if ( json.vertexColors !== undefined ) {
  25334. if ( typeof json.vertexColors === 'number' ) {
  25335. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  25336. } else {
  25337. material.vertexColors = json.vertexColors;
  25338. }
  25339. }
  25340. // Shader Material
  25341. if ( json.uniforms !== undefined ) {
  25342. for ( const name in json.uniforms ) {
  25343. const uniform = json.uniforms[ name ];
  25344. material.uniforms[ name ] = {};
  25345. switch ( uniform.type ) {
  25346. case 't':
  25347. material.uniforms[ name ].value = getTexture( uniform.value );
  25348. break;
  25349. case 'c':
  25350. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  25351. break;
  25352. case 'v2':
  25353. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  25354. break;
  25355. case 'v3':
  25356. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  25357. break;
  25358. case 'v4':
  25359. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  25360. break;
  25361. case 'm3':
  25362. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  25363. break;
  25364. case 'm4':
  25365. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  25366. break;
  25367. default:
  25368. material.uniforms[ name ].value = uniform.value;
  25369. }
  25370. }
  25371. }
  25372. if ( json.defines !== undefined ) material.defines = json.defines;
  25373. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25374. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25375. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  25376. if ( json.extensions !== undefined ) {
  25377. for ( const key in json.extensions ) {
  25378. material.extensions[ key ] = json.extensions[ key ];
  25379. }
  25380. }
  25381. // for PointsMaterial
  25382. if ( json.size !== undefined ) material.size = json.size;
  25383. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25384. // maps
  25385. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25386. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  25387. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  25388. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25389. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25390. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25391. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25392. if ( json.normalScale !== undefined ) {
  25393. let normalScale = json.normalScale;
  25394. if ( Array.isArray( normalScale ) === false ) {
  25395. // Blender exporter used to export a scalar. See #7459
  25396. normalScale = [ normalScale, normalScale ];
  25397. }
  25398. material.normalScale = new Vector2().fromArray( normalScale );
  25399. }
  25400. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25401. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25402. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25403. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25404. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25405. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25406. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25407. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25408. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  25409. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  25410. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25411. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  25412. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25413. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  25414. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25415. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25416. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25417. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25418. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25419. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  25420. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  25421. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  25422. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  25423. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  25424. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  25425. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  25426. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  25427. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  25428. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  25429. return material;
  25430. }
  25431. setTextures( value ) {
  25432. this.textures = value;
  25433. return this;
  25434. }
  25435. static createMaterialFromType( type ) {
  25436. const materialLib = {
  25437. ShadowMaterial,
  25438. SpriteMaterial,
  25439. RawShaderMaterial,
  25440. ShaderMaterial,
  25441. PointsMaterial,
  25442. MeshPhysicalMaterial,
  25443. MeshStandardMaterial,
  25444. MeshPhongMaterial,
  25445. MeshToonMaterial,
  25446. MeshNormalMaterial,
  25447. MeshLambertMaterial,
  25448. MeshDepthMaterial,
  25449. MeshDistanceMaterial,
  25450. MeshBasicMaterial,
  25451. MeshMatcapMaterial,
  25452. LineDashedMaterial,
  25453. LineBasicMaterial,
  25454. Material
  25455. };
  25456. return new materialLib[ type ]();
  25457. }
  25458. }
  25459. class LoaderUtils {
  25460. static decodeText( array ) {
  25461. if ( typeof TextDecoder !== 'undefined' ) {
  25462. return new TextDecoder().decode( array );
  25463. }
  25464. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25465. // throws a "maximum call stack size exceeded" error for large arrays.
  25466. let s = '';
  25467. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25468. // Implicitly assumes little-endian.
  25469. s += String.fromCharCode( array[ i ] );
  25470. }
  25471. try {
  25472. // merges multi-byte utf-8 characters.
  25473. return decodeURIComponent( escape( s ) );
  25474. } catch ( e ) { // see #16358
  25475. return s;
  25476. }
  25477. }
  25478. static extractUrlBase( url ) {
  25479. const index = url.lastIndexOf( '/' );
  25480. if ( index === - 1 ) return './';
  25481. return url.slice( 0, index + 1 );
  25482. }
  25483. static resolveURL( url, path ) {
  25484. // Invalid URL
  25485. if ( typeof url !== 'string' || url === '' ) return '';
  25486. // Host Relative URL
  25487. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25488. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25489. }
  25490. // Absolute URL http://,https://,//
  25491. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25492. // Data URI
  25493. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25494. // Blob URL
  25495. if ( /^blob:.*$/i.test( url ) ) return url;
  25496. // Relative URL
  25497. return path + url;
  25498. }
  25499. }
  25500. class InstancedBufferGeometry extends BufferGeometry {
  25501. constructor() {
  25502. super();
  25503. this.isInstancedBufferGeometry = true;
  25504. this.type = 'InstancedBufferGeometry';
  25505. this.instanceCount = Infinity;
  25506. }
  25507. copy( source ) {
  25508. super.copy( source );
  25509. this.instanceCount = source.instanceCount;
  25510. return this;
  25511. }
  25512. toJSON() {
  25513. const data = super.toJSON();
  25514. data.instanceCount = this.instanceCount;
  25515. data.isInstancedBufferGeometry = true;
  25516. return data;
  25517. }
  25518. }
  25519. class BufferGeometryLoader extends Loader {
  25520. constructor( manager ) {
  25521. super( manager );
  25522. }
  25523. load( url, onLoad, onProgress, onError ) {
  25524. const scope = this;
  25525. const loader = new FileLoader( scope.manager );
  25526. loader.setPath( scope.path );
  25527. loader.setRequestHeader( scope.requestHeader );
  25528. loader.setWithCredentials( scope.withCredentials );
  25529. loader.load( url, function ( text ) {
  25530. try {
  25531. onLoad( scope.parse( JSON.parse( text ) ) );
  25532. } catch ( e ) {
  25533. if ( onError ) {
  25534. onError( e );
  25535. } else {
  25536. console.error( e );
  25537. }
  25538. scope.manager.itemError( url );
  25539. }
  25540. }, onProgress, onError );
  25541. }
  25542. parse( json ) {
  25543. const interleavedBufferMap = {};
  25544. const arrayBufferMap = {};
  25545. function getInterleavedBuffer( json, uuid ) {
  25546. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25547. const interleavedBuffers = json.interleavedBuffers;
  25548. const interleavedBuffer = interleavedBuffers[ uuid ];
  25549. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25550. const array = getTypedArray( interleavedBuffer.type, buffer );
  25551. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25552. ib.uuid = interleavedBuffer.uuid;
  25553. interleavedBufferMap[ uuid ] = ib;
  25554. return ib;
  25555. }
  25556. function getArrayBuffer( json, uuid ) {
  25557. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25558. const arrayBuffers = json.arrayBuffers;
  25559. const arrayBuffer = arrayBuffers[ uuid ];
  25560. const ab = new Uint32Array( arrayBuffer ).buffer;
  25561. arrayBufferMap[ uuid ] = ab;
  25562. return ab;
  25563. }
  25564. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25565. const index = json.data.index;
  25566. if ( index !== undefined ) {
  25567. const typedArray = getTypedArray( index.type, index.array );
  25568. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25569. }
  25570. const attributes = json.data.attributes;
  25571. for ( const key in attributes ) {
  25572. const attribute = attributes[ key ];
  25573. let bufferAttribute;
  25574. if ( attribute.isInterleavedBufferAttribute ) {
  25575. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25576. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25577. } else {
  25578. const typedArray = getTypedArray( attribute.type, attribute.array );
  25579. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25580. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25581. }
  25582. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25583. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25584. if ( attribute.updateRange !== undefined ) {
  25585. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25586. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25587. }
  25588. geometry.setAttribute( key, bufferAttribute );
  25589. }
  25590. const morphAttributes = json.data.morphAttributes;
  25591. if ( morphAttributes ) {
  25592. for ( const key in morphAttributes ) {
  25593. const attributeArray = morphAttributes[ key ];
  25594. const array = [];
  25595. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25596. const attribute = attributeArray[ i ];
  25597. let bufferAttribute;
  25598. if ( attribute.isInterleavedBufferAttribute ) {
  25599. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25600. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25601. } else {
  25602. const typedArray = getTypedArray( attribute.type, attribute.array );
  25603. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25604. }
  25605. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25606. array.push( bufferAttribute );
  25607. }
  25608. geometry.morphAttributes[ key ] = array;
  25609. }
  25610. }
  25611. const morphTargetsRelative = json.data.morphTargetsRelative;
  25612. if ( morphTargetsRelative ) {
  25613. geometry.morphTargetsRelative = true;
  25614. }
  25615. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25616. if ( groups !== undefined ) {
  25617. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25618. const group = groups[ i ];
  25619. geometry.addGroup( group.start, group.count, group.materialIndex );
  25620. }
  25621. }
  25622. const boundingSphere = json.data.boundingSphere;
  25623. if ( boundingSphere !== undefined ) {
  25624. const center = new Vector3();
  25625. if ( boundingSphere.center !== undefined ) {
  25626. center.fromArray( boundingSphere.center );
  25627. }
  25628. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25629. }
  25630. if ( json.name ) geometry.name = json.name;
  25631. if ( json.userData ) geometry.userData = json.userData;
  25632. return geometry;
  25633. }
  25634. }
  25635. class ObjectLoader extends Loader {
  25636. constructor( manager ) {
  25637. super( manager );
  25638. }
  25639. load( url, onLoad, onProgress, onError ) {
  25640. const scope = this;
  25641. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25642. this.resourcePath = this.resourcePath || path;
  25643. const loader = new FileLoader( this.manager );
  25644. loader.setPath( this.path );
  25645. loader.setRequestHeader( this.requestHeader );
  25646. loader.setWithCredentials( this.withCredentials );
  25647. loader.load( url, function ( text ) {
  25648. let json = null;
  25649. try {
  25650. json = JSON.parse( text );
  25651. } catch ( error ) {
  25652. if ( onError !== undefined ) onError( error );
  25653. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25654. return;
  25655. }
  25656. const metadata = json.metadata;
  25657. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25658. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  25659. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25660. return;
  25661. }
  25662. scope.parse( json, onLoad );
  25663. }, onProgress, onError );
  25664. }
  25665. async loadAsync( url, onProgress ) {
  25666. const scope = this;
  25667. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25668. this.resourcePath = this.resourcePath || path;
  25669. const loader = new FileLoader( this.manager );
  25670. loader.setPath( this.path );
  25671. loader.setRequestHeader( this.requestHeader );
  25672. loader.setWithCredentials( this.withCredentials );
  25673. const text = await loader.loadAsync( url, onProgress );
  25674. const json = JSON.parse( text );
  25675. const metadata = json.metadata;
  25676. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25677. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25678. }
  25679. return await scope.parseAsync( json );
  25680. }
  25681. parse( json, onLoad ) {
  25682. const animations = this.parseAnimations( json.animations );
  25683. const shapes = this.parseShapes( json.shapes );
  25684. const geometries = this.parseGeometries( json.geometries, shapes );
  25685. const images = this.parseImages( json.images, function () {
  25686. if ( onLoad !== undefined ) onLoad( object );
  25687. } );
  25688. const textures = this.parseTextures( json.textures, images );
  25689. const materials = this.parseMaterials( json.materials, textures );
  25690. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25691. const skeletons = this.parseSkeletons( json.skeletons, object );
  25692. this.bindSkeletons( object, skeletons );
  25693. //
  25694. if ( onLoad !== undefined ) {
  25695. let hasImages = false;
  25696. for ( const uuid in images ) {
  25697. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  25698. hasImages = true;
  25699. break;
  25700. }
  25701. }
  25702. if ( hasImages === false ) onLoad( object );
  25703. }
  25704. return object;
  25705. }
  25706. async parseAsync( json ) {
  25707. const animations = this.parseAnimations( json.animations );
  25708. const shapes = this.parseShapes( json.shapes );
  25709. const geometries = this.parseGeometries( json.geometries, shapes );
  25710. const images = await this.parseImagesAsync( json.images );
  25711. const textures = this.parseTextures( json.textures, images );
  25712. const materials = this.parseMaterials( json.materials, textures );
  25713. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25714. const skeletons = this.parseSkeletons( json.skeletons, object );
  25715. this.bindSkeletons( object, skeletons );
  25716. return object;
  25717. }
  25718. parseShapes( json ) {
  25719. const shapes = {};
  25720. if ( json !== undefined ) {
  25721. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25722. const shape = new Shape().fromJSON( json[ i ] );
  25723. shapes[ shape.uuid ] = shape;
  25724. }
  25725. }
  25726. return shapes;
  25727. }
  25728. parseSkeletons( json, object ) {
  25729. const skeletons = {};
  25730. const bones = {};
  25731. // generate bone lookup table
  25732. object.traverse( function ( child ) {
  25733. if ( child.isBone ) bones[ child.uuid ] = child;
  25734. } );
  25735. // create skeletons
  25736. if ( json !== undefined ) {
  25737. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25738. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25739. skeletons[ skeleton.uuid ] = skeleton;
  25740. }
  25741. }
  25742. return skeletons;
  25743. }
  25744. parseGeometries( json, shapes ) {
  25745. const geometries = {};
  25746. if ( json !== undefined ) {
  25747. const bufferGeometryLoader = new BufferGeometryLoader();
  25748. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25749. let geometry;
  25750. const data = json[ i ];
  25751. switch ( data.type ) {
  25752. case 'BufferGeometry':
  25753. case 'InstancedBufferGeometry':
  25754. geometry = bufferGeometryLoader.parse( data );
  25755. break;
  25756. default:
  25757. if ( data.type in Geometries ) {
  25758. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25759. } else {
  25760. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25761. }
  25762. }
  25763. geometry.uuid = data.uuid;
  25764. if ( data.name !== undefined ) geometry.name = data.name;
  25765. if ( data.userData !== undefined ) geometry.userData = data.userData;
  25766. geometries[ data.uuid ] = geometry;
  25767. }
  25768. }
  25769. return geometries;
  25770. }
  25771. parseMaterials( json, textures ) {
  25772. const cache = {}; // MultiMaterial
  25773. const materials = {};
  25774. if ( json !== undefined ) {
  25775. const loader = new MaterialLoader();
  25776. loader.setTextures( textures );
  25777. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25778. const data = json[ i ];
  25779. if ( cache[ data.uuid ] === undefined ) {
  25780. cache[ data.uuid ] = loader.parse( data );
  25781. }
  25782. materials[ data.uuid ] = cache[ data.uuid ];
  25783. }
  25784. }
  25785. return materials;
  25786. }
  25787. parseAnimations( json ) {
  25788. const animations = {};
  25789. if ( json !== undefined ) {
  25790. for ( let i = 0; i < json.length; i ++ ) {
  25791. const data = json[ i ];
  25792. const clip = AnimationClip.parse( data );
  25793. animations[ clip.uuid ] = clip;
  25794. }
  25795. }
  25796. return animations;
  25797. }
  25798. parseImages( json, onLoad ) {
  25799. const scope = this;
  25800. const images = {};
  25801. let loader;
  25802. function loadImage( url ) {
  25803. scope.manager.itemStart( url );
  25804. return loader.load( url, function () {
  25805. scope.manager.itemEnd( url );
  25806. }, undefined, function () {
  25807. scope.manager.itemError( url );
  25808. scope.manager.itemEnd( url );
  25809. } );
  25810. }
  25811. function deserializeImage( image ) {
  25812. if ( typeof image === 'string' ) {
  25813. const url = image;
  25814. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25815. return loadImage( path );
  25816. } else {
  25817. if ( image.data ) {
  25818. return {
  25819. data: getTypedArray( image.type, image.data ),
  25820. width: image.width,
  25821. height: image.height
  25822. };
  25823. } else {
  25824. return null;
  25825. }
  25826. }
  25827. }
  25828. if ( json !== undefined && json.length > 0 ) {
  25829. const manager = new LoadingManager( onLoad );
  25830. loader = new ImageLoader( manager );
  25831. loader.setCrossOrigin( this.crossOrigin );
  25832. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25833. const image = json[ i ];
  25834. const url = image.url;
  25835. if ( Array.isArray( url ) ) {
  25836. // load array of images e.g CubeTexture
  25837. const imageArray = [];
  25838. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25839. const currentUrl = url[ j ];
  25840. const deserializedImage = deserializeImage( currentUrl );
  25841. if ( deserializedImage !== null ) {
  25842. if ( deserializedImage instanceof HTMLImageElement ) {
  25843. imageArray.push( deserializedImage );
  25844. } else {
  25845. // special case: handle array of data textures for cube textures
  25846. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25847. }
  25848. }
  25849. }
  25850. images[ image.uuid ] = new Source( imageArray );
  25851. } else {
  25852. // load single image
  25853. const deserializedImage = deserializeImage( image.url );
  25854. images[ image.uuid ] = new Source( deserializedImage );
  25855. }
  25856. }
  25857. }
  25858. return images;
  25859. }
  25860. async parseImagesAsync( json ) {
  25861. const scope = this;
  25862. const images = {};
  25863. let loader;
  25864. async function deserializeImage( image ) {
  25865. if ( typeof image === 'string' ) {
  25866. const url = image;
  25867. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25868. return await loader.loadAsync( path );
  25869. } else {
  25870. if ( image.data ) {
  25871. return {
  25872. data: getTypedArray( image.type, image.data ),
  25873. width: image.width,
  25874. height: image.height
  25875. };
  25876. } else {
  25877. return null;
  25878. }
  25879. }
  25880. }
  25881. if ( json !== undefined && json.length > 0 ) {
  25882. loader = new ImageLoader( this.manager );
  25883. loader.setCrossOrigin( this.crossOrigin );
  25884. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25885. const image = json[ i ];
  25886. const url = image.url;
  25887. if ( Array.isArray( url ) ) {
  25888. // load array of images e.g CubeTexture
  25889. const imageArray = [];
  25890. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25891. const currentUrl = url[ j ];
  25892. const deserializedImage = await deserializeImage( currentUrl );
  25893. if ( deserializedImage !== null ) {
  25894. if ( deserializedImage instanceof HTMLImageElement ) {
  25895. imageArray.push( deserializedImage );
  25896. } else {
  25897. // special case: handle array of data textures for cube textures
  25898. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25899. }
  25900. }
  25901. }
  25902. images[ image.uuid ] = new Source( imageArray );
  25903. } else {
  25904. // load single image
  25905. const deserializedImage = await deserializeImage( image.url );
  25906. images[ image.uuid ] = new Source( deserializedImage );
  25907. }
  25908. }
  25909. }
  25910. return images;
  25911. }
  25912. parseTextures( json, images ) {
  25913. function parseConstant( value, type ) {
  25914. if ( typeof value === 'number' ) return value;
  25915. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25916. return type[ value ];
  25917. }
  25918. const textures = {};
  25919. if ( json !== undefined ) {
  25920. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25921. const data = json[ i ];
  25922. if ( data.image === undefined ) {
  25923. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25924. }
  25925. if ( images[ data.image ] === undefined ) {
  25926. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25927. }
  25928. const source = images[ data.image ];
  25929. const image = source.data;
  25930. let texture;
  25931. if ( Array.isArray( image ) ) {
  25932. texture = new CubeTexture();
  25933. if ( image.length === 6 ) texture.needsUpdate = true;
  25934. } else {
  25935. if ( image && image.data ) {
  25936. texture = new DataTexture();
  25937. } else {
  25938. texture = new Texture();
  25939. }
  25940. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25941. }
  25942. texture.source = source;
  25943. texture.uuid = data.uuid;
  25944. if ( data.name !== undefined ) texture.name = data.name;
  25945. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25946. if ( data.channel !== undefined ) texture.channel = data.channel;
  25947. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25948. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25949. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25950. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25951. if ( data.wrap !== undefined ) {
  25952. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25953. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25954. }
  25955. if ( data.format !== undefined ) texture.format = data.format;
  25956. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  25957. if ( data.type !== undefined ) texture.type = data.type;
  25958. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25959. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25960. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25961. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25962. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25963. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  25964. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25965. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25966. if ( data.userData !== undefined ) texture.userData = data.userData;
  25967. textures[ data.uuid ] = texture;
  25968. }
  25969. }
  25970. return textures;
  25971. }
  25972. parseObject( data, geometries, materials, textures, animations ) {
  25973. let object;
  25974. function getGeometry( name ) {
  25975. if ( geometries[ name ] === undefined ) {
  25976. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25977. }
  25978. return geometries[ name ];
  25979. }
  25980. function getMaterial( name ) {
  25981. if ( name === undefined ) return undefined;
  25982. if ( Array.isArray( name ) ) {
  25983. const array = [];
  25984. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25985. const uuid = name[ i ];
  25986. if ( materials[ uuid ] === undefined ) {
  25987. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25988. }
  25989. array.push( materials[ uuid ] );
  25990. }
  25991. return array;
  25992. }
  25993. if ( materials[ name ] === undefined ) {
  25994. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25995. }
  25996. return materials[ name ];
  25997. }
  25998. function getTexture( uuid ) {
  25999. if ( textures[ uuid ] === undefined ) {
  26000. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  26001. }
  26002. return textures[ uuid ];
  26003. }
  26004. let geometry, material;
  26005. switch ( data.type ) {
  26006. case 'Scene':
  26007. object = new Scene();
  26008. if ( data.background !== undefined ) {
  26009. if ( Number.isInteger( data.background ) ) {
  26010. object.background = new Color( data.background );
  26011. } else {
  26012. object.background = getTexture( data.background );
  26013. }
  26014. }
  26015. if ( data.environment !== undefined ) {
  26016. object.environment = getTexture( data.environment );
  26017. }
  26018. if ( data.fog !== undefined ) {
  26019. if ( data.fog.type === 'Fog' ) {
  26020. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  26021. } else if ( data.fog.type === 'FogExp2' ) {
  26022. object.fog = new FogExp2( data.fog.color, data.fog.density );
  26023. }
  26024. }
  26025. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  26026. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  26027. break;
  26028. case 'PerspectiveCamera':
  26029. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  26030. if ( data.focus !== undefined ) object.focus = data.focus;
  26031. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26032. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  26033. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  26034. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26035. break;
  26036. case 'OrthographicCamera':
  26037. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  26038. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26039. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26040. break;
  26041. case 'AmbientLight':
  26042. object = new AmbientLight( data.color, data.intensity );
  26043. break;
  26044. case 'DirectionalLight':
  26045. object = new DirectionalLight( data.color, data.intensity );
  26046. break;
  26047. case 'PointLight':
  26048. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  26049. break;
  26050. case 'RectAreaLight':
  26051. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  26052. break;
  26053. case 'SpotLight':
  26054. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  26055. break;
  26056. case 'HemisphereLight':
  26057. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  26058. break;
  26059. case 'LightProbe':
  26060. object = new LightProbe().fromJSON( data );
  26061. break;
  26062. case 'SkinnedMesh':
  26063. geometry = getGeometry( data.geometry );
  26064. material = getMaterial( data.material );
  26065. object = new SkinnedMesh( geometry, material );
  26066. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  26067. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  26068. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  26069. break;
  26070. case 'Mesh':
  26071. geometry = getGeometry( data.geometry );
  26072. material = getMaterial( data.material );
  26073. object = new Mesh( geometry, material );
  26074. break;
  26075. case 'InstancedMesh':
  26076. geometry = getGeometry( data.geometry );
  26077. material = getMaterial( data.material );
  26078. const count = data.count;
  26079. const instanceMatrix = data.instanceMatrix;
  26080. const instanceColor = data.instanceColor;
  26081. object = new InstancedMesh( geometry, material, count );
  26082. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  26083. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  26084. break;
  26085. case 'LOD':
  26086. object = new LOD();
  26087. break;
  26088. case 'Line':
  26089. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  26090. break;
  26091. case 'LineLoop':
  26092. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  26093. break;
  26094. case 'LineSegments':
  26095. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  26096. break;
  26097. case 'PointCloud':
  26098. case 'Points':
  26099. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  26100. break;
  26101. case 'Sprite':
  26102. object = new Sprite( getMaterial( data.material ) );
  26103. break;
  26104. case 'Group':
  26105. object = new Group();
  26106. break;
  26107. case 'Bone':
  26108. object = new Bone();
  26109. break;
  26110. default:
  26111. object = new Object3D();
  26112. }
  26113. object.uuid = data.uuid;
  26114. if ( data.name !== undefined ) object.name = data.name;
  26115. if ( data.matrix !== undefined ) {
  26116. object.matrix.fromArray( data.matrix );
  26117. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  26118. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  26119. } else {
  26120. if ( data.position !== undefined ) object.position.fromArray( data.position );
  26121. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  26122. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  26123. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  26124. }
  26125. if ( data.up !== undefined ) object.up.fromArray( data.up );
  26126. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  26127. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  26128. if ( data.shadow ) {
  26129. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  26130. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  26131. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  26132. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  26133. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  26134. }
  26135. if ( data.visible !== undefined ) object.visible = data.visible;
  26136. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  26137. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  26138. if ( data.userData !== undefined ) object.userData = data.userData;
  26139. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  26140. if ( data.children !== undefined ) {
  26141. const children = data.children;
  26142. for ( let i = 0; i < children.length; i ++ ) {
  26143. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  26144. }
  26145. }
  26146. if ( data.animations !== undefined ) {
  26147. const objectAnimations = data.animations;
  26148. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  26149. const uuid = objectAnimations[ i ];
  26150. object.animations.push( animations[ uuid ] );
  26151. }
  26152. }
  26153. if ( data.type === 'LOD' ) {
  26154. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  26155. const levels = data.levels;
  26156. for ( let l = 0; l < levels.length; l ++ ) {
  26157. const level = levels[ l ];
  26158. const child = object.getObjectByProperty( 'uuid', level.object );
  26159. if ( child !== undefined ) {
  26160. object.addLevel( child, level.distance, level.hysteresis );
  26161. }
  26162. }
  26163. }
  26164. return object;
  26165. }
  26166. bindSkeletons( object, skeletons ) {
  26167. if ( Object.keys( skeletons ).length === 0 ) return;
  26168. object.traverse( function ( child ) {
  26169. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  26170. const skeleton = skeletons[ child.skeleton ];
  26171. if ( skeleton === undefined ) {
  26172. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  26173. } else {
  26174. child.bind( skeleton, child.bindMatrix );
  26175. }
  26176. }
  26177. } );
  26178. }
  26179. }
  26180. const TEXTURE_MAPPING = {
  26181. UVMapping: UVMapping,
  26182. CubeReflectionMapping: CubeReflectionMapping,
  26183. CubeRefractionMapping: CubeRefractionMapping,
  26184. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  26185. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  26186. CubeUVReflectionMapping: CubeUVReflectionMapping
  26187. };
  26188. const TEXTURE_WRAPPING = {
  26189. RepeatWrapping: RepeatWrapping,
  26190. ClampToEdgeWrapping: ClampToEdgeWrapping,
  26191. MirroredRepeatWrapping: MirroredRepeatWrapping
  26192. };
  26193. const TEXTURE_FILTER = {
  26194. NearestFilter: NearestFilter,
  26195. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  26196. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  26197. LinearFilter: LinearFilter,
  26198. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  26199. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  26200. };
  26201. class ImageBitmapLoader extends Loader {
  26202. constructor( manager ) {
  26203. super( manager );
  26204. this.isImageBitmapLoader = true;
  26205. if ( typeof createImageBitmap === 'undefined' ) {
  26206. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26207. }
  26208. if ( typeof fetch === 'undefined' ) {
  26209. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26210. }
  26211. this.options = { premultiplyAlpha: 'none' };
  26212. }
  26213. setOptions( options ) {
  26214. this.options = options;
  26215. return this;
  26216. }
  26217. load( url, onLoad, onProgress, onError ) {
  26218. if ( url === undefined ) url = '';
  26219. if ( this.path !== undefined ) url = this.path + url;
  26220. url = this.manager.resolveURL( url );
  26221. const scope = this;
  26222. const cached = Cache.get( url );
  26223. if ( cached !== undefined ) {
  26224. scope.manager.itemStart( url );
  26225. setTimeout( function () {
  26226. if ( onLoad ) onLoad( cached );
  26227. scope.manager.itemEnd( url );
  26228. }, 0 );
  26229. return cached;
  26230. }
  26231. const fetchOptions = {};
  26232. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  26233. fetchOptions.headers = this.requestHeader;
  26234. fetch( url, fetchOptions ).then( function ( res ) {
  26235. return res.blob();
  26236. } ).then( function ( blob ) {
  26237. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  26238. } ).then( function ( imageBitmap ) {
  26239. Cache.add( url, imageBitmap );
  26240. if ( onLoad ) onLoad( imageBitmap );
  26241. scope.manager.itemEnd( url );
  26242. } ).catch( function ( e ) {
  26243. if ( onError ) onError( e );
  26244. scope.manager.itemError( url );
  26245. scope.manager.itemEnd( url );
  26246. } );
  26247. scope.manager.itemStart( url );
  26248. }
  26249. }
  26250. let _context;
  26251. class AudioContext {
  26252. static getContext() {
  26253. if ( _context === undefined ) {
  26254. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26255. }
  26256. return _context;
  26257. }
  26258. static setContext( value ) {
  26259. _context = value;
  26260. }
  26261. }
  26262. class AudioLoader extends Loader {
  26263. constructor( manager ) {
  26264. super( manager );
  26265. }
  26266. load( url, onLoad, onProgress, onError ) {
  26267. const scope = this;
  26268. const loader = new FileLoader( this.manager );
  26269. loader.setResponseType( 'arraybuffer' );
  26270. loader.setPath( this.path );
  26271. loader.setRequestHeader( this.requestHeader );
  26272. loader.setWithCredentials( this.withCredentials );
  26273. loader.load( url, function ( buffer ) {
  26274. try {
  26275. // Create a copy of the buffer. The `decodeAudioData` method
  26276. // detaches the buffer when complete, preventing reuse.
  26277. const bufferCopy = buffer.slice( 0 );
  26278. const context = AudioContext.getContext();
  26279. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26280. onLoad( audioBuffer );
  26281. } );
  26282. } catch ( e ) {
  26283. if ( onError ) {
  26284. onError( e );
  26285. } else {
  26286. console.error( e );
  26287. }
  26288. scope.manager.itemError( url );
  26289. }
  26290. }, onProgress, onError );
  26291. }
  26292. }
  26293. class HemisphereLightProbe extends LightProbe {
  26294. constructor( skyColor, groundColor, intensity = 1 ) {
  26295. super( undefined, intensity );
  26296. this.isHemisphereLightProbe = true;
  26297. const color1 = new Color().set( skyColor );
  26298. const color2 = new Color().set( groundColor );
  26299. const sky = new Vector3( color1.r, color1.g, color1.b );
  26300. const ground = new Vector3( color2.r, color2.g, color2.b );
  26301. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26302. const c0 = Math.sqrt( Math.PI );
  26303. const c1 = c0 * Math.sqrt( 0.75 );
  26304. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26305. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26306. }
  26307. }
  26308. class AmbientLightProbe extends LightProbe {
  26309. constructor( color, intensity = 1 ) {
  26310. super( undefined, intensity );
  26311. this.isAmbientLightProbe = true;
  26312. const color1 = new Color().set( color );
  26313. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26314. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26315. }
  26316. }
  26317. const _eyeRight = /*@__PURE__*/ new Matrix4();
  26318. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  26319. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  26320. class StereoCamera {
  26321. constructor() {
  26322. this.type = 'StereoCamera';
  26323. this.aspect = 1;
  26324. this.eyeSep = 0.064;
  26325. this.cameraL = new PerspectiveCamera();
  26326. this.cameraL.layers.enable( 1 );
  26327. this.cameraL.matrixAutoUpdate = false;
  26328. this.cameraR = new PerspectiveCamera();
  26329. this.cameraR.layers.enable( 2 );
  26330. this.cameraR.matrixAutoUpdate = false;
  26331. this._cache = {
  26332. focus: null,
  26333. fov: null,
  26334. aspect: null,
  26335. near: null,
  26336. far: null,
  26337. zoom: null,
  26338. eyeSep: null
  26339. };
  26340. }
  26341. update( camera ) {
  26342. const cache = this._cache;
  26343. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26344. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26345. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26346. if ( needsUpdate ) {
  26347. cache.focus = camera.focus;
  26348. cache.fov = camera.fov;
  26349. cache.aspect = camera.aspect * this.aspect;
  26350. cache.near = camera.near;
  26351. cache.far = camera.far;
  26352. cache.zoom = camera.zoom;
  26353. cache.eyeSep = this.eyeSep;
  26354. // Off-axis stereoscopic effect based on
  26355. // http://paulbourke.net/stereographics/stereorender/
  26356. _projectionMatrix.copy( camera.projectionMatrix );
  26357. const eyeSepHalf = cache.eyeSep / 2;
  26358. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26359. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26360. let xmin, xmax;
  26361. // translate xOffset
  26362. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26363. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26364. // for left eye
  26365. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26366. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26367. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26368. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26369. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  26370. // for right eye
  26371. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26372. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26373. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26374. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26375. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  26376. }
  26377. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26378. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26379. }
  26380. }
  26381. class Clock {
  26382. constructor( autoStart = true ) {
  26383. this.autoStart = autoStart;
  26384. this.startTime = 0;
  26385. this.oldTime = 0;
  26386. this.elapsedTime = 0;
  26387. this.running = false;
  26388. }
  26389. start() {
  26390. this.startTime = now();
  26391. this.oldTime = this.startTime;
  26392. this.elapsedTime = 0;
  26393. this.running = true;
  26394. }
  26395. stop() {
  26396. this.getElapsedTime();
  26397. this.running = false;
  26398. this.autoStart = false;
  26399. }
  26400. getElapsedTime() {
  26401. this.getDelta();
  26402. return this.elapsedTime;
  26403. }
  26404. getDelta() {
  26405. let diff = 0;
  26406. if ( this.autoStart && ! this.running ) {
  26407. this.start();
  26408. return 0;
  26409. }
  26410. if ( this.running ) {
  26411. const newTime = now();
  26412. diff = ( newTime - this.oldTime ) / 1000;
  26413. this.oldTime = newTime;
  26414. this.elapsedTime += diff;
  26415. }
  26416. return diff;
  26417. }
  26418. }
  26419. function now() {
  26420. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26421. }
  26422. const _position$1 = /*@__PURE__*/ new Vector3();
  26423. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  26424. const _scale$1 = /*@__PURE__*/ new Vector3();
  26425. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26426. class AudioListener extends Object3D {
  26427. constructor() {
  26428. super();
  26429. this.type = 'AudioListener';
  26430. this.context = AudioContext.getContext();
  26431. this.gain = this.context.createGain();
  26432. this.gain.connect( this.context.destination );
  26433. this.filter = null;
  26434. this.timeDelta = 0;
  26435. // private
  26436. this._clock = new Clock();
  26437. }
  26438. getInput() {
  26439. return this.gain;
  26440. }
  26441. removeFilter() {
  26442. if ( this.filter !== null ) {
  26443. this.gain.disconnect( this.filter );
  26444. this.filter.disconnect( this.context.destination );
  26445. this.gain.connect( this.context.destination );
  26446. this.filter = null;
  26447. }
  26448. return this;
  26449. }
  26450. getFilter() {
  26451. return this.filter;
  26452. }
  26453. setFilter( value ) {
  26454. if ( this.filter !== null ) {
  26455. this.gain.disconnect( this.filter );
  26456. this.filter.disconnect( this.context.destination );
  26457. } else {
  26458. this.gain.disconnect( this.context.destination );
  26459. }
  26460. this.filter = value;
  26461. this.gain.connect( this.filter );
  26462. this.filter.connect( this.context.destination );
  26463. return this;
  26464. }
  26465. getMasterVolume() {
  26466. return this.gain.gain.value;
  26467. }
  26468. setMasterVolume( value ) {
  26469. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26470. return this;
  26471. }
  26472. updateMatrixWorld( force ) {
  26473. super.updateMatrixWorld( force );
  26474. const listener = this.context.listener;
  26475. const up = this.up;
  26476. this.timeDelta = this._clock.getDelta();
  26477. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26478. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26479. if ( listener.positionX ) {
  26480. // code path for Chrome (see #14393)
  26481. const endTime = this.context.currentTime + this.timeDelta;
  26482. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26483. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26484. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26485. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26486. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26487. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26488. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26489. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26490. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26491. } else {
  26492. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26493. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26494. }
  26495. }
  26496. }
  26497. class Audio extends Object3D {
  26498. constructor( listener ) {
  26499. super();
  26500. this.type = 'Audio';
  26501. this.listener = listener;
  26502. this.context = listener.context;
  26503. this.gain = this.context.createGain();
  26504. this.gain.connect( listener.getInput() );
  26505. this.autoplay = false;
  26506. this.buffer = null;
  26507. this.detune = 0;
  26508. this.loop = false;
  26509. this.loopStart = 0;
  26510. this.loopEnd = 0;
  26511. this.offset = 0;
  26512. this.duration = undefined;
  26513. this.playbackRate = 1;
  26514. this.isPlaying = false;
  26515. this.hasPlaybackControl = true;
  26516. this.source = null;
  26517. this.sourceType = 'empty';
  26518. this._startedAt = 0;
  26519. this._progress = 0;
  26520. this._connected = false;
  26521. this.filters = [];
  26522. }
  26523. getOutput() {
  26524. return this.gain;
  26525. }
  26526. setNodeSource( audioNode ) {
  26527. this.hasPlaybackControl = false;
  26528. this.sourceType = 'audioNode';
  26529. this.source = audioNode;
  26530. this.connect();
  26531. return this;
  26532. }
  26533. setMediaElementSource( mediaElement ) {
  26534. this.hasPlaybackControl = false;
  26535. this.sourceType = 'mediaNode';
  26536. this.source = this.context.createMediaElementSource( mediaElement );
  26537. this.connect();
  26538. return this;
  26539. }
  26540. setMediaStreamSource( mediaStream ) {
  26541. this.hasPlaybackControl = false;
  26542. this.sourceType = 'mediaStreamNode';
  26543. this.source = this.context.createMediaStreamSource( mediaStream );
  26544. this.connect();
  26545. return this;
  26546. }
  26547. setBuffer( audioBuffer ) {
  26548. this.buffer = audioBuffer;
  26549. this.sourceType = 'buffer';
  26550. if ( this.autoplay ) this.play();
  26551. return this;
  26552. }
  26553. play( delay = 0 ) {
  26554. if ( this.isPlaying === true ) {
  26555. console.warn( 'THREE.Audio: Audio is already playing.' );
  26556. return;
  26557. }
  26558. if ( this.hasPlaybackControl === false ) {
  26559. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26560. return;
  26561. }
  26562. this._startedAt = this.context.currentTime + delay;
  26563. const source = this.context.createBufferSource();
  26564. source.buffer = this.buffer;
  26565. source.loop = this.loop;
  26566. source.loopStart = this.loopStart;
  26567. source.loopEnd = this.loopEnd;
  26568. source.onended = this.onEnded.bind( this );
  26569. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26570. this.isPlaying = true;
  26571. this.source = source;
  26572. this.setDetune( this.detune );
  26573. this.setPlaybackRate( this.playbackRate );
  26574. return this.connect();
  26575. }
  26576. pause() {
  26577. if ( this.hasPlaybackControl === false ) {
  26578. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26579. return;
  26580. }
  26581. if ( this.isPlaying === true ) {
  26582. // update current progress
  26583. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26584. if ( this.loop === true ) {
  26585. // ensure _progress does not exceed duration with looped audios
  26586. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26587. }
  26588. this.source.stop();
  26589. this.source.onended = null;
  26590. this.isPlaying = false;
  26591. }
  26592. return this;
  26593. }
  26594. stop() {
  26595. if ( this.hasPlaybackControl === false ) {
  26596. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26597. return;
  26598. }
  26599. this._progress = 0;
  26600. if ( this.source !== null ) {
  26601. this.source.stop();
  26602. this.source.onended = null;
  26603. }
  26604. this.isPlaying = false;
  26605. return this;
  26606. }
  26607. connect() {
  26608. if ( this.filters.length > 0 ) {
  26609. this.source.connect( this.filters[ 0 ] );
  26610. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26611. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26612. }
  26613. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26614. } else {
  26615. this.source.connect( this.getOutput() );
  26616. }
  26617. this._connected = true;
  26618. return this;
  26619. }
  26620. disconnect() {
  26621. if ( this.filters.length > 0 ) {
  26622. this.source.disconnect( this.filters[ 0 ] );
  26623. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26624. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26625. }
  26626. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26627. } else {
  26628. this.source.disconnect( this.getOutput() );
  26629. }
  26630. this._connected = false;
  26631. return this;
  26632. }
  26633. getFilters() {
  26634. return this.filters;
  26635. }
  26636. setFilters( value ) {
  26637. if ( ! value ) value = [];
  26638. if ( this._connected === true ) {
  26639. this.disconnect();
  26640. this.filters = value.slice();
  26641. this.connect();
  26642. } else {
  26643. this.filters = value.slice();
  26644. }
  26645. return this;
  26646. }
  26647. setDetune( value ) {
  26648. this.detune = value;
  26649. if ( this.source.detune === undefined ) return; // only set detune when available
  26650. if ( this.isPlaying === true ) {
  26651. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26652. }
  26653. return this;
  26654. }
  26655. getDetune() {
  26656. return this.detune;
  26657. }
  26658. getFilter() {
  26659. return this.getFilters()[ 0 ];
  26660. }
  26661. setFilter( filter ) {
  26662. return this.setFilters( filter ? [ filter ] : [] );
  26663. }
  26664. setPlaybackRate( value ) {
  26665. if ( this.hasPlaybackControl === false ) {
  26666. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26667. return;
  26668. }
  26669. this.playbackRate = value;
  26670. if ( this.isPlaying === true ) {
  26671. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26672. }
  26673. return this;
  26674. }
  26675. getPlaybackRate() {
  26676. return this.playbackRate;
  26677. }
  26678. onEnded() {
  26679. this.isPlaying = false;
  26680. }
  26681. getLoop() {
  26682. if ( this.hasPlaybackControl === false ) {
  26683. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26684. return false;
  26685. }
  26686. return this.loop;
  26687. }
  26688. setLoop( value ) {
  26689. if ( this.hasPlaybackControl === false ) {
  26690. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26691. return;
  26692. }
  26693. this.loop = value;
  26694. if ( this.isPlaying === true ) {
  26695. this.source.loop = this.loop;
  26696. }
  26697. return this;
  26698. }
  26699. setLoopStart( value ) {
  26700. this.loopStart = value;
  26701. return this;
  26702. }
  26703. setLoopEnd( value ) {
  26704. this.loopEnd = value;
  26705. return this;
  26706. }
  26707. getVolume() {
  26708. return this.gain.gain.value;
  26709. }
  26710. setVolume( value ) {
  26711. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26712. return this;
  26713. }
  26714. }
  26715. const _position = /*@__PURE__*/ new Vector3();
  26716. const _quaternion = /*@__PURE__*/ new Quaternion();
  26717. const _scale = /*@__PURE__*/ new Vector3();
  26718. const _orientation = /*@__PURE__*/ new Vector3();
  26719. class PositionalAudio extends Audio {
  26720. constructor( listener ) {
  26721. super( listener );
  26722. this.panner = this.context.createPanner();
  26723. this.panner.panningModel = 'HRTF';
  26724. this.panner.connect( this.gain );
  26725. }
  26726. disconnect() {
  26727. super.disconnect();
  26728. this.panner.disconnect( this.gain );
  26729. }
  26730. getOutput() {
  26731. return this.panner;
  26732. }
  26733. getRefDistance() {
  26734. return this.panner.refDistance;
  26735. }
  26736. setRefDistance( value ) {
  26737. this.panner.refDistance = value;
  26738. return this;
  26739. }
  26740. getRolloffFactor() {
  26741. return this.panner.rolloffFactor;
  26742. }
  26743. setRolloffFactor( value ) {
  26744. this.panner.rolloffFactor = value;
  26745. return this;
  26746. }
  26747. getDistanceModel() {
  26748. return this.panner.distanceModel;
  26749. }
  26750. setDistanceModel( value ) {
  26751. this.panner.distanceModel = value;
  26752. return this;
  26753. }
  26754. getMaxDistance() {
  26755. return this.panner.maxDistance;
  26756. }
  26757. setMaxDistance( value ) {
  26758. this.panner.maxDistance = value;
  26759. return this;
  26760. }
  26761. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26762. this.panner.coneInnerAngle = coneInnerAngle;
  26763. this.panner.coneOuterAngle = coneOuterAngle;
  26764. this.panner.coneOuterGain = coneOuterGain;
  26765. return this;
  26766. }
  26767. updateMatrixWorld( force ) {
  26768. super.updateMatrixWorld( force );
  26769. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26770. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26771. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26772. const panner = this.panner;
  26773. if ( panner.positionX ) {
  26774. // code path for Chrome and Firefox (see #14393)
  26775. const endTime = this.context.currentTime + this.listener.timeDelta;
  26776. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26777. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26778. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26779. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26780. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26781. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26782. } else {
  26783. panner.setPosition( _position.x, _position.y, _position.z );
  26784. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26785. }
  26786. }
  26787. }
  26788. class AudioAnalyser {
  26789. constructor( audio, fftSize = 2048 ) {
  26790. this.analyser = audio.context.createAnalyser();
  26791. this.analyser.fftSize = fftSize;
  26792. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26793. audio.getOutput().connect( this.analyser );
  26794. }
  26795. getFrequencyData() {
  26796. this.analyser.getByteFrequencyData( this.data );
  26797. return this.data;
  26798. }
  26799. getAverageFrequency() {
  26800. let value = 0;
  26801. const data = this.getFrequencyData();
  26802. for ( let i = 0; i < data.length; i ++ ) {
  26803. value += data[ i ];
  26804. }
  26805. return value / data.length;
  26806. }
  26807. }
  26808. class PropertyMixer {
  26809. constructor( binding, typeName, valueSize ) {
  26810. this.binding = binding;
  26811. this.valueSize = valueSize;
  26812. let mixFunction,
  26813. mixFunctionAdditive,
  26814. setIdentity;
  26815. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26816. //
  26817. // interpolators can use .buffer as their .result
  26818. // the data then goes to 'incoming'
  26819. //
  26820. // 'accu0' and 'accu1' are used frame-interleaved for
  26821. // the cumulative result and are compared to detect
  26822. // changes
  26823. //
  26824. // 'orig' stores the original state of the property
  26825. //
  26826. // 'add' is used for additive cumulative results
  26827. //
  26828. // 'work' is optional and is only present for quaternion types. It is used
  26829. // to store intermediate quaternion multiplication results
  26830. switch ( typeName ) {
  26831. case 'quaternion':
  26832. mixFunction = this._slerp;
  26833. mixFunctionAdditive = this._slerpAdditive;
  26834. setIdentity = this._setAdditiveIdentityQuaternion;
  26835. this.buffer = new Float64Array( valueSize * 6 );
  26836. this._workIndex = 5;
  26837. break;
  26838. case 'string':
  26839. case 'bool':
  26840. mixFunction = this._select;
  26841. // Use the regular mix function and for additive on these types,
  26842. // additive is not relevant for non-numeric types
  26843. mixFunctionAdditive = this._select;
  26844. setIdentity = this._setAdditiveIdentityOther;
  26845. this.buffer = new Array( valueSize * 5 );
  26846. break;
  26847. default:
  26848. mixFunction = this._lerp;
  26849. mixFunctionAdditive = this._lerpAdditive;
  26850. setIdentity = this._setAdditiveIdentityNumeric;
  26851. this.buffer = new Float64Array( valueSize * 5 );
  26852. }
  26853. this._mixBufferRegion = mixFunction;
  26854. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26855. this._setIdentity = setIdentity;
  26856. this._origIndex = 3;
  26857. this._addIndex = 4;
  26858. this.cumulativeWeight = 0;
  26859. this.cumulativeWeightAdditive = 0;
  26860. this.useCount = 0;
  26861. this.referenceCount = 0;
  26862. }
  26863. // accumulate data in the 'incoming' region into 'accu<i>'
  26864. accumulate( accuIndex, weight ) {
  26865. // note: happily accumulating nothing when weight = 0, the caller knows
  26866. // the weight and shouldn't have made the call in the first place
  26867. const buffer = this.buffer,
  26868. stride = this.valueSize,
  26869. offset = accuIndex * stride + stride;
  26870. let currentWeight = this.cumulativeWeight;
  26871. if ( currentWeight === 0 ) {
  26872. // accuN := incoming * weight
  26873. for ( let i = 0; i !== stride; ++ i ) {
  26874. buffer[ offset + i ] = buffer[ i ];
  26875. }
  26876. currentWeight = weight;
  26877. } else {
  26878. // accuN := accuN + incoming * weight
  26879. currentWeight += weight;
  26880. const mix = weight / currentWeight;
  26881. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26882. }
  26883. this.cumulativeWeight = currentWeight;
  26884. }
  26885. // accumulate data in the 'incoming' region into 'add'
  26886. accumulateAdditive( weight ) {
  26887. const buffer = this.buffer,
  26888. stride = this.valueSize,
  26889. offset = stride * this._addIndex;
  26890. if ( this.cumulativeWeightAdditive === 0 ) {
  26891. // add = identity
  26892. this._setIdentity();
  26893. }
  26894. // add := add + incoming * weight
  26895. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26896. this.cumulativeWeightAdditive += weight;
  26897. }
  26898. // apply the state of 'accu<i>' to the binding when accus differ
  26899. apply( accuIndex ) {
  26900. const stride = this.valueSize,
  26901. buffer = this.buffer,
  26902. offset = accuIndex * stride + stride,
  26903. weight = this.cumulativeWeight,
  26904. weightAdditive = this.cumulativeWeightAdditive,
  26905. binding = this.binding;
  26906. this.cumulativeWeight = 0;
  26907. this.cumulativeWeightAdditive = 0;
  26908. if ( weight < 1 ) {
  26909. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26910. const originalValueOffset = stride * this._origIndex;
  26911. this._mixBufferRegion(
  26912. buffer, offset, originalValueOffset, 1 - weight, stride );
  26913. }
  26914. if ( weightAdditive > 0 ) {
  26915. // accuN := accuN + additive accuN
  26916. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26917. }
  26918. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26919. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26920. // value has changed -> update scene graph
  26921. binding.setValue( buffer, offset );
  26922. break;
  26923. }
  26924. }
  26925. }
  26926. // remember the state of the bound property and copy it to both accus
  26927. saveOriginalState() {
  26928. const binding = this.binding;
  26929. const buffer = this.buffer,
  26930. stride = this.valueSize,
  26931. originalValueOffset = stride * this._origIndex;
  26932. binding.getValue( buffer, originalValueOffset );
  26933. // accu[0..1] := orig -- initially detect changes against the original
  26934. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26935. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26936. }
  26937. // Add to identity for additive
  26938. this._setIdentity();
  26939. this.cumulativeWeight = 0;
  26940. this.cumulativeWeightAdditive = 0;
  26941. }
  26942. // apply the state previously taken via 'saveOriginalState' to the binding
  26943. restoreOriginalState() {
  26944. const originalValueOffset = this.valueSize * 3;
  26945. this.binding.setValue( this.buffer, originalValueOffset );
  26946. }
  26947. _setAdditiveIdentityNumeric() {
  26948. const startIndex = this._addIndex * this.valueSize;
  26949. const endIndex = startIndex + this.valueSize;
  26950. for ( let i = startIndex; i < endIndex; i ++ ) {
  26951. this.buffer[ i ] = 0;
  26952. }
  26953. }
  26954. _setAdditiveIdentityQuaternion() {
  26955. this._setAdditiveIdentityNumeric();
  26956. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26957. }
  26958. _setAdditiveIdentityOther() {
  26959. const startIndex = this._origIndex * this.valueSize;
  26960. const targetIndex = this._addIndex * this.valueSize;
  26961. for ( let i = 0; i < this.valueSize; i ++ ) {
  26962. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26963. }
  26964. }
  26965. // mix functions
  26966. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26967. if ( t >= 0.5 ) {
  26968. for ( let i = 0; i !== stride; ++ i ) {
  26969. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26970. }
  26971. }
  26972. }
  26973. _slerp( buffer, dstOffset, srcOffset, t ) {
  26974. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26975. }
  26976. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26977. const workOffset = this._workIndex * stride;
  26978. // Store result in intermediate buffer offset
  26979. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26980. // Slerp to the intermediate result
  26981. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26982. }
  26983. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26984. const s = 1 - t;
  26985. for ( let i = 0; i !== stride; ++ i ) {
  26986. const j = dstOffset + i;
  26987. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26988. }
  26989. }
  26990. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26991. for ( let i = 0; i !== stride; ++ i ) {
  26992. const j = dstOffset + i;
  26993. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26994. }
  26995. }
  26996. }
  26997. // Characters [].:/ are reserved for track binding syntax.
  26998. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26999. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  27000. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  27001. // only latin characters, and the unicode \p{L} is not yet supported. So
  27002. // instead, we exclude reserved characters and match everything else.
  27003. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  27004. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  27005. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  27006. // be matched to parse the rest of the track name.
  27007. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  27008. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  27009. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  27010. // Object on target node, and accessor. May not contain reserved
  27011. // characters. Accessor may contain any character except closing bracket.
  27012. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  27013. // Property and accessor. May not contain reserved characters. Accessor may
  27014. // contain any non-bracket characters.
  27015. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  27016. const _trackRe = new RegExp( ''
  27017. + '^'
  27018. + _directoryRe
  27019. + _nodeRe
  27020. + _objectRe
  27021. + _propertyRe
  27022. + '$'
  27023. );
  27024. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  27025. class Composite {
  27026. constructor( targetGroup, path, optionalParsedPath ) {
  27027. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  27028. this._targetGroup = targetGroup;
  27029. this._bindings = targetGroup.subscribe_( path, parsedPath );
  27030. }
  27031. getValue( array, offset ) {
  27032. this.bind(); // bind all binding
  27033. const firstValidIndex = this._targetGroup.nCachedObjects_,
  27034. binding = this._bindings[ firstValidIndex ];
  27035. // and only call .getValue on the first
  27036. if ( binding !== undefined ) binding.getValue( array, offset );
  27037. }
  27038. setValue( array, offset ) {
  27039. const bindings = this._bindings;
  27040. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27041. bindings[ i ].setValue( array, offset );
  27042. }
  27043. }
  27044. bind() {
  27045. const bindings = this._bindings;
  27046. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27047. bindings[ i ].bind();
  27048. }
  27049. }
  27050. unbind() {
  27051. const bindings = this._bindings;
  27052. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27053. bindings[ i ].unbind();
  27054. }
  27055. }
  27056. }
  27057. // Note: This class uses a State pattern on a per-method basis:
  27058. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  27059. // prototype version of these methods with one that represents
  27060. // the bound state. When the property is not found, the methods
  27061. // become no-ops.
  27062. class PropertyBinding {
  27063. constructor( rootNode, path, parsedPath ) {
  27064. this.path = path;
  27065. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  27066. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  27067. this.rootNode = rootNode;
  27068. // initial state of these methods that calls 'bind'
  27069. this.getValue = this._getValue_unbound;
  27070. this.setValue = this._setValue_unbound;
  27071. }
  27072. static create( root, path, parsedPath ) {
  27073. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  27074. return new PropertyBinding( root, path, parsedPath );
  27075. } else {
  27076. return new PropertyBinding.Composite( root, path, parsedPath );
  27077. }
  27078. }
  27079. /**
  27080. * Replaces spaces with underscores and removes unsupported characters from
  27081. * node names, to ensure compatibility with parseTrackName().
  27082. *
  27083. * @param {string} name Node name to be sanitized.
  27084. * @return {string}
  27085. */
  27086. static sanitizeNodeName( name ) {
  27087. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  27088. }
  27089. static parseTrackName( trackName ) {
  27090. const matches = _trackRe.exec( trackName );
  27091. if ( matches === null ) {
  27092. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  27093. }
  27094. const results = {
  27095. // directoryName: matches[ 1 ], // (tschw) currently unused
  27096. nodeName: matches[ 2 ],
  27097. objectName: matches[ 3 ],
  27098. objectIndex: matches[ 4 ],
  27099. propertyName: matches[ 5 ], // required
  27100. propertyIndex: matches[ 6 ]
  27101. };
  27102. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  27103. if ( lastDot !== undefined && lastDot !== - 1 ) {
  27104. const objectName = results.nodeName.substring( lastDot + 1 );
  27105. // Object names must be checked against an allowlist. Otherwise, there
  27106. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  27107. // 'bar' could be the objectName, or part of a nodeName (which can
  27108. // include '.' characters).
  27109. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  27110. results.nodeName = results.nodeName.substring( 0, lastDot );
  27111. results.objectName = objectName;
  27112. }
  27113. }
  27114. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  27115. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  27116. }
  27117. return results;
  27118. }
  27119. static findNode( root, nodeName ) {
  27120. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  27121. return root;
  27122. }
  27123. // search into skeleton bones.
  27124. if ( root.skeleton ) {
  27125. const bone = root.skeleton.getBoneByName( nodeName );
  27126. if ( bone !== undefined ) {
  27127. return bone;
  27128. }
  27129. }
  27130. // search into node subtree.
  27131. if ( root.children ) {
  27132. const searchNodeSubtree = function ( children ) {
  27133. for ( let i = 0; i < children.length; i ++ ) {
  27134. const childNode = children[ i ];
  27135. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  27136. return childNode;
  27137. }
  27138. const result = searchNodeSubtree( childNode.children );
  27139. if ( result ) return result;
  27140. }
  27141. return null;
  27142. };
  27143. const subTreeNode = searchNodeSubtree( root.children );
  27144. if ( subTreeNode ) {
  27145. return subTreeNode;
  27146. }
  27147. }
  27148. return null;
  27149. }
  27150. // these are used to "bind" a nonexistent property
  27151. _getValue_unavailable() {}
  27152. _setValue_unavailable() {}
  27153. // Getters
  27154. _getValue_direct( buffer, offset ) {
  27155. buffer[ offset ] = this.targetObject[ this.propertyName ];
  27156. }
  27157. _getValue_array( buffer, offset ) {
  27158. const source = this.resolvedProperty;
  27159. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  27160. buffer[ offset ++ ] = source[ i ];
  27161. }
  27162. }
  27163. _getValue_arrayElement( buffer, offset ) {
  27164. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  27165. }
  27166. _getValue_toArray( buffer, offset ) {
  27167. this.resolvedProperty.toArray( buffer, offset );
  27168. }
  27169. // Direct
  27170. _setValue_direct( buffer, offset ) {
  27171. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27172. }
  27173. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  27174. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27175. this.targetObject.needsUpdate = true;
  27176. }
  27177. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27178. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27179. this.targetObject.matrixWorldNeedsUpdate = true;
  27180. }
  27181. // EntireArray
  27182. _setValue_array( buffer, offset ) {
  27183. const dest = this.resolvedProperty;
  27184. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27185. dest[ i ] = buffer[ offset ++ ];
  27186. }
  27187. }
  27188. _setValue_array_setNeedsUpdate( buffer, offset ) {
  27189. const dest = this.resolvedProperty;
  27190. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27191. dest[ i ] = buffer[ offset ++ ];
  27192. }
  27193. this.targetObject.needsUpdate = true;
  27194. }
  27195. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27196. const dest = this.resolvedProperty;
  27197. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27198. dest[ i ] = buffer[ offset ++ ];
  27199. }
  27200. this.targetObject.matrixWorldNeedsUpdate = true;
  27201. }
  27202. // ArrayElement
  27203. _setValue_arrayElement( buffer, offset ) {
  27204. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27205. }
  27206. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27207. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27208. this.targetObject.needsUpdate = true;
  27209. }
  27210. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27211. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27212. this.targetObject.matrixWorldNeedsUpdate = true;
  27213. }
  27214. // HasToFromArray
  27215. _setValue_fromArray( buffer, offset ) {
  27216. this.resolvedProperty.fromArray( buffer, offset );
  27217. }
  27218. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27219. this.resolvedProperty.fromArray( buffer, offset );
  27220. this.targetObject.needsUpdate = true;
  27221. }
  27222. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27223. this.resolvedProperty.fromArray( buffer, offset );
  27224. this.targetObject.matrixWorldNeedsUpdate = true;
  27225. }
  27226. _getValue_unbound( targetArray, offset ) {
  27227. this.bind();
  27228. this.getValue( targetArray, offset );
  27229. }
  27230. _setValue_unbound( sourceArray, offset ) {
  27231. this.bind();
  27232. this.setValue( sourceArray, offset );
  27233. }
  27234. // create getter / setter pair for a property in the scene graph
  27235. bind() {
  27236. let targetObject = this.node;
  27237. const parsedPath = this.parsedPath;
  27238. const objectName = parsedPath.objectName;
  27239. const propertyName = parsedPath.propertyName;
  27240. let propertyIndex = parsedPath.propertyIndex;
  27241. if ( ! targetObject ) {
  27242. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  27243. this.node = targetObject;
  27244. }
  27245. // set fail state so we can just 'return' on error
  27246. this.getValue = this._getValue_unavailable;
  27247. this.setValue = this._setValue_unavailable;
  27248. // ensure there is a value node
  27249. if ( ! targetObject ) {
  27250. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27251. return;
  27252. }
  27253. if ( objectName ) {
  27254. let objectIndex = parsedPath.objectIndex;
  27255. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27256. switch ( objectName ) {
  27257. case 'materials':
  27258. if ( ! targetObject.material ) {
  27259. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27260. return;
  27261. }
  27262. if ( ! targetObject.material.materials ) {
  27263. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27264. return;
  27265. }
  27266. targetObject = targetObject.material.materials;
  27267. break;
  27268. case 'bones':
  27269. if ( ! targetObject.skeleton ) {
  27270. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27271. return;
  27272. }
  27273. // potential future optimization: skip this if propertyIndex is already an integer
  27274. // and convert the integer string to a true integer.
  27275. targetObject = targetObject.skeleton.bones;
  27276. // support resolving morphTarget names into indices.
  27277. for ( let i = 0; i < targetObject.length; i ++ ) {
  27278. if ( targetObject[ i ].name === objectIndex ) {
  27279. objectIndex = i;
  27280. break;
  27281. }
  27282. }
  27283. break;
  27284. case 'map':
  27285. if ( 'map' in targetObject ) {
  27286. targetObject = targetObject.map;
  27287. break;
  27288. }
  27289. if ( ! targetObject.material ) {
  27290. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27291. return;
  27292. }
  27293. if ( ! targetObject.material.map ) {
  27294. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  27295. return;
  27296. }
  27297. targetObject = targetObject.material.map;
  27298. break;
  27299. default:
  27300. if ( targetObject[ objectName ] === undefined ) {
  27301. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27302. return;
  27303. }
  27304. targetObject = targetObject[ objectName ];
  27305. }
  27306. if ( objectIndex !== undefined ) {
  27307. if ( targetObject[ objectIndex ] === undefined ) {
  27308. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27309. return;
  27310. }
  27311. targetObject = targetObject[ objectIndex ];
  27312. }
  27313. }
  27314. // resolve property
  27315. const nodeProperty = targetObject[ propertyName ];
  27316. if ( nodeProperty === undefined ) {
  27317. const nodeName = parsedPath.nodeName;
  27318. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27319. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27320. return;
  27321. }
  27322. // determine versioning scheme
  27323. let versioning = this.Versioning.None;
  27324. this.targetObject = targetObject;
  27325. if ( targetObject.needsUpdate !== undefined ) { // material
  27326. versioning = this.Versioning.NeedsUpdate;
  27327. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27328. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27329. }
  27330. // determine how the property gets bound
  27331. let bindingType = this.BindingType.Direct;
  27332. if ( propertyIndex !== undefined ) {
  27333. // access a sub element of the property array (only primitives are supported right now)
  27334. if ( propertyName === 'morphTargetInfluences' ) {
  27335. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27336. // support resolving morphTarget names into indices.
  27337. if ( ! targetObject.geometry ) {
  27338. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27339. return;
  27340. }
  27341. if ( ! targetObject.geometry.morphAttributes ) {
  27342. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27343. return;
  27344. }
  27345. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27346. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27347. }
  27348. }
  27349. bindingType = this.BindingType.ArrayElement;
  27350. this.resolvedProperty = nodeProperty;
  27351. this.propertyIndex = propertyIndex;
  27352. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27353. // must use copy for Object3D.Euler/Quaternion
  27354. bindingType = this.BindingType.HasFromToArray;
  27355. this.resolvedProperty = nodeProperty;
  27356. } else if ( Array.isArray( nodeProperty ) ) {
  27357. bindingType = this.BindingType.EntireArray;
  27358. this.resolvedProperty = nodeProperty;
  27359. } else {
  27360. this.propertyName = propertyName;
  27361. }
  27362. // select getter / setter
  27363. this.getValue = this.GetterByBindingType[ bindingType ];
  27364. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27365. }
  27366. unbind() {
  27367. this.node = null;
  27368. // back to the prototype version of getValue / setValue
  27369. // note: avoiding to mutate the shape of 'this' via 'delete'
  27370. this.getValue = this._getValue_unbound;
  27371. this.setValue = this._setValue_unbound;
  27372. }
  27373. }
  27374. PropertyBinding.Composite = Composite;
  27375. PropertyBinding.prototype.BindingType = {
  27376. Direct: 0,
  27377. EntireArray: 1,
  27378. ArrayElement: 2,
  27379. HasFromToArray: 3
  27380. };
  27381. PropertyBinding.prototype.Versioning = {
  27382. None: 0,
  27383. NeedsUpdate: 1,
  27384. MatrixWorldNeedsUpdate: 2
  27385. };
  27386. PropertyBinding.prototype.GetterByBindingType = [
  27387. PropertyBinding.prototype._getValue_direct,
  27388. PropertyBinding.prototype._getValue_array,
  27389. PropertyBinding.prototype._getValue_arrayElement,
  27390. PropertyBinding.prototype._getValue_toArray,
  27391. ];
  27392. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  27393. [
  27394. // Direct
  27395. PropertyBinding.prototype._setValue_direct,
  27396. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  27397. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  27398. ], [
  27399. // EntireArray
  27400. PropertyBinding.prototype._setValue_array,
  27401. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  27402. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  27403. ], [
  27404. // ArrayElement
  27405. PropertyBinding.prototype._setValue_arrayElement,
  27406. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  27407. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  27408. ], [
  27409. // HasToFromArray
  27410. PropertyBinding.prototype._setValue_fromArray,
  27411. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  27412. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  27413. ]
  27414. ];
  27415. /**
  27416. *
  27417. * A group of objects that receives a shared animation state.
  27418. *
  27419. * Usage:
  27420. *
  27421. * - Add objects you would otherwise pass as 'root' to the
  27422. * constructor or the .clipAction method of AnimationMixer.
  27423. *
  27424. * - Instead pass this object as 'root'.
  27425. *
  27426. * - You can also add and remove objects later when the mixer
  27427. * is running.
  27428. *
  27429. * Note:
  27430. *
  27431. * Objects of this class appear as one object to the mixer,
  27432. * so cache control of the individual objects must be done
  27433. * on the group.
  27434. *
  27435. * Limitation:
  27436. *
  27437. * - The animated properties must be compatible among the
  27438. * all objects in the group.
  27439. *
  27440. * - A single property can either be controlled through a
  27441. * target group or directly, but not both.
  27442. */
  27443. class AnimationObjectGroup {
  27444. constructor() {
  27445. this.isAnimationObjectGroup = true;
  27446. this.uuid = generateUUID();
  27447. // cached objects followed by the active ones
  27448. this._objects = Array.prototype.slice.call( arguments );
  27449. this.nCachedObjects_ = 0; // threshold
  27450. // note: read by PropertyBinding.Composite
  27451. const indices = {};
  27452. this._indicesByUUID = indices; // for bookkeeping
  27453. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27454. indices[ arguments[ i ].uuid ] = i;
  27455. }
  27456. this._paths = []; // inside: string
  27457. this._parsedPaths = []; // inside: { we don't care, here }
  27458. this._bindings = []; // inside: Array< PropertyBinding >
  27459. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27460. const scope = this;
  27461. this.stats = {
  27462. objects: {
  27463. get total() {
  27464. return scope._objects.length;
  27465. },
  27466. get inUse() {
  27467. return this.total - scope.nCachedObjects_;
  27468. }
  27469. },
  27470. get bindingsPerObject() {
  27471. return scope._bindings.length;
  27472. }
  27473. };
  27474. }
  27475. add() {
  27476. const objects = this._objects,
  27477. indicesByUUID = this._indicesByUUID,
  27478. paths = this._paths,
  27479. parsedPaths = this._parsedPaths,
  27480. bindings = this._bindings,
  27481. nBindings = bindings.length;
  27482. let knownObject = undefined,
  27483. nObjects = objects.length,
  27484. nCachedObjects = this.nCachedObjects_;
  27485. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27486. const object = arguments[ i ],
  27487. uuid = object.uuid;
  27488. let index = indicesByUUID[ uuid ];
  27489. if ( index === undefined ) {
  27490. // unknown object -> add it to the ACTIVE region
  27491. index = nObjects ++;
  27492. indicesByUUID[ uuid ] = index;
  27493. objects.push( object );
  27494. // accounting is done, now do the same for all bindings
  27495. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27496. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27497. }
  27498. } else if ( index < nCachedObjects ) {
  27499. knownObject = objects[ index ];
  27500. // move existing object to the ACTIVE region
  27501. const firstActiveIndex = -- nCachedObjects,
  27502. lastCachedObject = objects[ firstActiveIndex ];
  27503. indicesByUUID[ lastCachedObject.uuid ] = index;
  27504. objects[ index ] = lastCachedObject;
  27505. indicesByUUID[ uuid ] = firstActiveIndex;
  27506. objects[ firstActiveIndex ] = object;
  27507. // accounting is done, now do the same for all bindings
  27508. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27509. const bindingsForPath = bindings[ j ],
  27510. lastCached = bindingsForPath[ firstActiveIndex ];
  27511. let binding = bindingsForPath[ index ];
  27512. bindingsForPath[ index ] = lastCached;
  27513. if ( binding === undefined ) {
  27514. // since we do not bother to create new bindings
  27515. // for objects that are cached, the binding may
  27516. // or may not exist
  27517. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27518. }
  27519. bindingsForPath[ firstActiveIndex ] = binding;
  27520. }
  27521. } else if ( objects[ index ] !== knownObject ) {
  27522. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27523. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27524. } // else the object is already where we want it to be
  27525. } // for arguments
  27526. this.nCachedObjects_ = nCachedObjects;
  27527. }
  27528. remove() {
  27529. const objects = this._objects,
  27530. indicesByUUID = this._indicesByUUID,
  27531. bindings = this._bindings,
  27532. nBindings = bindings.length;
  27533. let nCachedObjects = this.nCachedObjects_;
  27534. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27535. const object = arguments[ i ],
  27536. uuid = object.uuid,
  27537. index = indicesByUUID[ uuid ];
  27538. if ( index !== undefined && index >= nCachedObjects ) {
  27539. // move existing object into the CACHED region
  27540. const lastCachedIndex = nCachedObjects ++,
  27541. firstActiveObject = objects[ lastCachedIndex ];
  27542. indicesByUUID[ firstActiveObject.uuid ] = index;
  27543. objects[ index ] = firstActiveObject;
  27544. indicesByUUID[ uuid ] = lastCachedIndex;
  27545. objects[ lastCachedIndex ] = object;
  27546. // accounting is done, now do the same for all bindings
  27547. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27548. const bindingsForPath = bindings[ j ],
  27549. firstActive = bindingsForPath[ lastCachedIndex ],
  27550. binding = bindingsForPath[ index ];
  27551. bindingsForPath[ index ] = firstActive;
  27552. bindingsForPath[ lastCachedIndex ] = binding;
  27553. }
  27554. }
  27555. } // for arguments
  27556. this.nCachedObjects_ = nCachedObjects;
  27557. }
  27558. // remove & forget
  27559. uncache() {
  27560. const objects = this._objects,
  27561. indicesByUUID = this._indicesByUUID,
  27562. bindings = this._bindings,
  27563. nBindings = bindings.length;
  27564. let nCachedObjects = this.nCachedObjects_,
  27565. nObjects = objects.length;
  27566. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27567. const object = arguments[ i ],
  27568. uuid = object.uuid,
  27569. index = indicesByUUID[ uuid ];
  27570. if ( index !== undefined ) {
  27571. delete indicesByUUID[ uuid ];
  27572. if ( index < nCachedObjects ) {
  27573. // object is cached, shrink the CACHED region
  27574. const firstActiveIndex = -- nCachedObjects,
  27575. lastCachedObject = objects[ firstActiveIndex ],
  27576. lastIndex = -- nObjects,
  27577. lastObject = objects[ lastIndex ];
  27578. // last cached object takes this object's place
  27579. indicesByUUID[ lastCachedObject.uuid ] = index;
  27580. objects[ index ] = lastCachedObject;
  27581. // last object goes to the activated slot and pop
  27582. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27583. objects[ firstActiveIndex ] = lastObject;
  27584. objects.pop();
  27585. // accounting is done, now do the same for all bindings
  27586. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27587. const bindingsForPath = bindings[ j ],
  27588. lastCached = bindingsForPath[ firstActiveIndex ],
  27589. last = bindingsForPath[ lastIndex ];
  27590. bindingsForPath[ index ] = lastCached;
  27591. bindingsForPath[ firstActiveIndex ] = last;
  27592. bindingsForPath.pop();
  27593. }
  27594. } else {
  27595. // object is active, just swap with the last and pop
  27596. const lastIndex = -- nObjects,
  27597. lastObject = objects[ lastIndex ];
  27598. if ( lastIndex > 0 ) {
  27599. indicesByUUID[ lastObject.uuid ] = index;
  27600. }
  27601. objects[ index ] = lastObject;
  27602. objects.pop();
  27603. // accounting is done, now do the same for all bindings
  27604. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27605. const bindingsForPath = bindings[ j ];
  27606. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27607. bindingsForPath.pop();
  27608. }
  27609. } // cached or active
  27610. } // if object is known
  27611. } // for arguments
  27612. this.nCachedObjects_ = nCachedObjects;
  27613. }
  27614. // Internal interface used by befriended PropertyBinding.Composite:
  27615. subscribe_( path, parsedPath ) {
  27616. // returns an array of bindings for the given path that is changed
  27617. // according to the contained objects in the group
  27618. const indicesByPath = this._bindingsIndicesByPath;
  27619. let index = indicesByPath[ path ];
  27620. const bindings = this._bindings;
  27621. if ( index !== undefined ) return bindings[ index ];
  27622. const paths = this._paths,
  27623. parsedPaths = this._parsedPaths,
  27624. objects = this._objects,
  27625. nObjects = objects.length,
  27626. nCachedObjects = this.nCachedObjects_,
  27627. bindingsForPath = new Array( nObjects );
  27628. index = bindings.length;
  27629. indicesByPath[ path ] = index;
  27630. paths.push( path );
  27631. parsedPaths.push( parsedPath );
  27632. bindings.push( bindingsForPath );
  27633. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27634. const object = objects[ i ];
  27635. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27636. }
  27637. return bindingsForPath;
  27638. }
  27639. unsubscribe_( path ) {
  27640. // tells the group to forget about a property path and no longer
  27641. // update the array previously obtained with 'subscribe_'
  27642. const indicesByPath = this._bindingsIndicesByPath,
  27643. index = indicesByPath[ path ];
  27644. if ( index !== undefined ) {
  27645. const paths = this._paths,
  27646. parsedPaths = this._parsedPaths,
  27647. bindings = this._bindings,
  27648. lastBindingsIndex = bindings.length - 1,
  27649. lastBindings = bindings[ lastBindingsIndex ],
  27650. lastBindingsPath = path[ lastBindingsIndex ];
  27651. indicesByPath[ lastBindingsPath ] = index;
  27652. bindings[ index ] = lastBindings;
  27653. bindings.pop();
  27654. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27655. parsedPaths.pop();
  27656. paths[ index ] = paths[ lastBindingsIndex ];
  27657. paths.pop();
  27658. }
  27659. }
  27660. }
  27661. class AnimationAction {
  27662. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27663. this._mixer = mixer;
  27664. this._clip = clip;
  27665. this._localRoot = localRoot;
  27666. this.blendMode = blendMode;
  27667. const tracks = clip.tracks,
  27668. nTracks = tracks.length,
  27669. interpolants = new Array( nTracks );
  27670. const interpolantSettings = {
  27671. endingStart: ZeroCurvatureEnding,
  27672. endingEnd: ZeroCurvatureEnding
  27673. };
  27674. for ( let i = 0; i !== nTracks; ++ i ) {
  27675. const interpolant = tracks[ i ].createInterpolant( null );
  27676. interpolants[ i ] = interpolant;
  27677. interpolant.settings = interpolantSettings;
  27678. }
  27679. this._interpolantSettings = interpolantSettings;
  27680. this._interpolants = interpolants; // bound by the mixer
  27681. // inside: PropertyMixer (managed by the mixer)
  27682. this._propertyBindings = new Array( nTracks );
  27683. this._cacheIndex = null; // for the memory manager
  27684. this._byClipCacheIndex = null; // for the memory manager
  27685. this._timeScaleInterpolant = null;
  27686. this._weightInterpolant = null;
  27687. this.loop = LoopRepeat;
  27688. this._loopCount = - 1;
  27689. // global mixer time when the action is to be started
  27690. // it's set back to 'null' upon start of the action
  27691. this._startTime = null;
  27692. // scaled local time of the action
  27693. // gets clamped or wrapped to 0..clip.duration according to loop
  27694. this.time = 0;
  27695. this.timeScale = 1;
  27696. this._effectiveTimeScale = 1;
  27697. this.weight = 1;
  27698. this._effectiveWeight = 1;
  27699. this.repetitions = Infinity; // no. of repetitions when looping
  27700. this.paused = false; // true -> zero effective time scale
  27701. this.enabled = true; // false -> zero effective weight
  27702. this.clampWhenFinished = false;// keep feeding the last frame?
  27703. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27704. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27705. }
  27706. // State & Scheduling
  27707. play() {
  27708. this._mixer._activateAction( this );
  27709. return this;
  27710. }
  27711. stop() {
  27712. this._mixer._deactivateAction( this );
  27713. return this.reset();
  27714. }
  27715. reset() {
  27716. this.paused = false;
  27717. this.enabled = true;
  27718. this.time = 0; // restart clip
  27719. this._loopCount = - 1;// forget previous loops
  27720. this._startTime = null;// forget scheduling
  27721. return this.stopFading().stopWarping();
  27722. }
  27723. isRunning() {
  27724. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27725. this._startTime === null && this._mixer._isActiveAction( this );
  27726. }
  27727. // return true when play has been called
  27728. isScheduled() {
  27729. return this._mixer._isActiveAction( this );
  27730. }
  27731. startAt( time ) {
  27732. this._startTime = time;
  27733. return this;
  27734. }
  27735. setLoop( mode, repetitions ) {
  27736. this.loop = mode;
  27737. this.repetitions = repetitions;
  27738. return this;
  27739. }
  27740. // Weight
  27741. // set the weight stopping any scheduled fading
  27742. // although .enabled = false yields an effective weight of zero, this
  27743. // method does *not* change .enabled, because it would be confusing
  27744. setEffectiveWeight( weight ) {
  27745. this.weight = weight;
  27746. // note: same logic as when updated at runtime
  27747. this._effectiveWeight = this.enabled ? weight : 0;
  27748. return this.stopFading();
  27749. }
  27750. // return the weight considering fading and .enabled
  27751. getEffectiveWeight() {
  27752. return this._effectiveWeight;
  27753. }
  27754. fadeIn( duration ) {
  27755. return this._scheduleFading( duration, 0, 1 );
  27756. }
  27757. fadeOut( duration ) {
  27758. return this._scheduleFading( duration, 1, 0 );
  27759. }
  27760. crossFadeFrom( fadeOutAction, duration, warp ) {
  27761. fadeOutAction.fadeOut( duration );
  27762. this.fadeIn( duration );
  27763. if ( warp ) {
  27764. const fadeInDuration = this._clip.duration,
  27765. fadeOutDuration = fadeOutAction._clip.duration,
  27766. startEndRatio = fadeOutDuration / fadeInDuration,
  27767. endStartRatio = fadeInDuration / fadeOutDuration;
  27768. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27769. this.warp( endStartRatio, 1.0, duration );
  27770. }
  27771. return this;
  27772. }
  27773. crossFadeTo( fadeInAction, duration, warp ) {
  27774. return fadeInAction.crossFadeFrom( this, duration, warp );
  27775. }
  27776. stopFading() {
  27777. const weightInterpolant = this._weightInterpolant;
  27778. if ( weightInterpolant !== null ) {
  27779. this._weightInterpolant = null;
  27780. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27781. }
  27782. return this;
  27783. }
  27784. // Time Scale Control
  27785. // set the time scale stopping any scheduled warping
  27786. // although .paused = true yields an effective time scale of zero, this
  27787. // method does *not* change .paused, because it would be confusing
  27788. setEffectiveTimeScale( timeScale ) {
  27789. this.timeScale = timeScale;
  27790. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27791. return this.stopWarping();
  27792. }
  27793. // return the time scale considering warping and .paused
  27794. getEffectiveTimeScale() {
  27795. return this._effectiveTimeScale;
  27796. }
  27797. setDuration( duration ) {
  27798. this.timeScale = this._clip.duration / duration;
  27799. return this.stopWarping();
  27800. }
  27801. syncWith( action ) {
  27802. this.time = action.time;
  27803. this.timeScale = action.timeScale;
  27804. return this.stopWarping();
  27805. }
  27806. halt( duration ) {
  27807. return this.warp( this._effectiveTimeScale, 0, duration );
  27808. }
  27809. warp( startTimeScale, endTimeScale, duration ) {
  27810. const mixer = this._mixer,
  27811. now = mixer.time,
  27812. timeScale = this.timeScale;
  27813. let interpolant = this._timeScaleInterpolant;
  27814. if ( interpolant === null ) {
  27815. interpolant = mixer._lendControlInterpolant();
  27816. this._timeScaleInterpolant = interpolant;
  27817. }
  27818. const times = interpolant.parameterPositions,
  27819. values = interpolant.sampleValues;
  27820. times[ 0 ] = now;
  27821. times[ 1 ] = now + duration;
  27822. values[ 0 ] = startTimeScale / timeScale;
  27823. values[ 1 ] = endTimeScale / timeScale;
  27824. return this;
  27825. }
  27826. stopWarping() {
  27827. const timeScaleInterpolant = this._timeScaleInterpolant;
  27828. if ( timeScaleInterpolant !== null ) {
  27829. this._timeScaleInterpolant = null;
  27830. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27831. }
  27832. return this;
  27833. }
  27834. // Object Accessors
  27835. getMixer() {
  27836. return this._mixer;
  27837. }
  27838. getClip() {
  27839. return this._clip;
  27840. }
  27841. getRoot() {
  27842. return this._localRoot || this._mixer._root;
  27843. }
  27844. // Interna
  27845. _update( time, deltaTime, timeDirection, accuIndex ) {
  27846. // called by the mixer
  27847. if ( ! this.enabled ) {
  27848. // call ._updateWeight() to update ._effectiveWeight
  27849. this._updateWeight( time );
  27850. return;
  27851. }
  27852. const startTime = this._startTime;
  27853. if ( startTime !== null ) {
  27854. // check for scheduled start of action
  27855. const timeRunning = ( time - startTime ) * timeDirection;
  27856. if ( timeRunning < 0 || timeDirection === 0 ) {
  27857. deltaTime = 0;
  27858. } else {
  27859. this._startTime = null; // unschedule
  27860. deltaTime = timeDirection * timeRunning;
  27861. }
  27862. }
  27863. // apply time scale and advance time
  27864. deltaTime *= this._updateTimeScale( time );
  27865. const clipTime = this._updateTime( deltaTime );
  27866. // note: _updateTime may disable the action resulting in
  27867. // an effective weight of 0
  27868. const weight = this._updateWeight( time );
  27869. if ( weight > 0 ) {
  27870. const interpolants = this._interpolants;
  27871. const propertyMixers = this._propertyBindings;
  27872. switch ( this.blendMode ) {
  27873. case AdditiveAnimationBlendMode:
  27874. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27875. interpolants[ j ].evaluate( clipTime );
  27876. propertyMixers[ j ].accumulateAdditive( weight );
  27877. }
  27878. break;
  27879. case NormalAnimationBlendMode:
  27880. default:
  27881. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27882. interpolants[ j ].evaluate( clipTime );
  27883. propertyMixers[ j ].accumulate( accuIndex, weight );
  27884. }
  27885. }
  27886. }
  27887. }
  27888. _updateWeight( time ) {
  27889. let weight = 0;
  27890. if ( this.enabled ) {
  27891. weight = this.weight;
  27892. const interpolant = this._weightInterpolant;
  27893. if ( interpolant !== null ) {
  27894. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27895. weight *= interpolantValue;
  27896. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27897. this.stopFading();
  27898. if ( interpolantValue === 0 ) {
  27899. // faded out, disable
  27900. this.enabled = false;
  27901. }
  27902. }
  27903. }
  27904. }
  27905. this._effectiveWeight = weight;
  27906. return weight;
  27907. }
  27908. _updateTimeScale( time ) {
  27909. let timeScale = 0;
  27910. if ( ! this.paused ) {
  27911. timeScale = this.timeScale;
  27912. const interpolant = this._timeScaleInterpolant;
  27913. if ( interpolant !== null ) {
  27914. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27915. timeScale *= interpolantValue;
  27916. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27917. this.stopWarping();
  27918. if ( timeScale === 0 ) {
  27919. // motion has halted, pause
  27920. this.paused = true;
  27921. } else {
  27922. // warp done - apply final time scale
  27923. this.timeScale = timeScale;
  27924. }
  27925. }
  27926. }
  27927. }
  27928. this._effectiveTimeScale = timeScale;
  27929. return timeScale;
  27930. }
  27931. _updateTime( deltaTime ) {
  27932. const duration = this._clip.duration;
  27933. const loop = this.loop;
  27934. let time = this.time + deltaTime;
  27935. let loopCount = this._loopCount;
  27936. const pingPong = ( loop === LoopPingPong );
  27937. if ( deltaTime === 0 ) {
  27938. if ( loopCount === - 1 ) return time;
  27939. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27940. }
  27941. if ( loop === LoopOnce ) {
  27942. if ( loopCount === - 1 ) {
  27943. // just started
  27944. this._loopCount = 0;
  27945. this._setEndings( true, true, false );
  27946. }
  27947. handle_stop: {
  27948. if ( time >= duration ) {
  27949. time = duration;
  27950. } else if ( time < 0 ) {
  27951. time = 0;
  27952. } else {
  27953. this.time = time;
  27954. break handle_stop;
  27955. }
  27956. if ( this.clampWhenFinished ) this.paused = true;
  27957. else this.enabled = false;
  27958. this.time = time;
  27959. this._mixer.dispatchEvent( {
  27960. type: 'finished', action: this,
  27961. direction: deltaTime < 0 ? - 1 : 1
  27962. } );
  27963. }
  27964. } else { // repetitive Repeat or PingPong
  27965. if ( loopCount === - 1 ) {
  27966. // just started
  27967. if ( deltaTime >= 0 ) {
  27968. loopCount = 0;
  27969. this._setEndings( true, this.repetitions === 0, pingPong );
  27970. } else {
  27971. // when looping in reverse direction, the initial
  27972. // transition through zero counts as a repetition,
  27973. // so leave loopCount at -1
  27974. this._setEndings( this.repetitions === 0, true, pingPong );
  27975. }
  27976. }
  27977. if ( time >= duration || time < 0 ) {
  27978. // wrap around
  27979. const loopDelta = Math.floor( time / duration ); // signed
  27980. time -= duration * loopDelta;
  27981. loopCount += Math.abs( loopDelta );
  27982. const pending = this.repetitions - loopCount;
  27983. if ( pending <= 0 ) {
  27984. // have to stop (switch state, clamp time, fire event)
  27985. if ( this.clampWhenFinished ) this.paused = true;
  27986. else this.enabled = false;
  27987. time = deltaTime > 0 ? duration : 0;
  27988. this.time = time;
  27989. this._mixer.dispatchEvent( {
  27990. type: 'finished', action: this,
  27991. direction: deltaTime > 0 ? 1 : - 1
  27992. } );
  27993. } else {
  27994. // keep running
  27995. if ( pending === 1 ) {
  27996. // entering the last round
  27997. const atStart = deltaTime < 0;
  27998. this._setEndings( atStart, ! atStart, pingPong );
  27999. } else {
  28000. this._setEndings( false, false, pingPong );
  28001. }
  28002. this._loopCount = loopCount;
  28003. this.time = time;
  28004. this._mixer.dispatchEvent( {
  28005. type: 'loop', action: this, loopDelta: loopDelta
  28006. } );
  28007. }
  28008. } else {
  28009. this.time = time;
  28010. }
  28011. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  28012. // invert time for the "pong round"
  28013. return duration - time;
  28014. }
  28015. }
  28016. return time;
  28017. }
  28018. _setEndings( atStart, atEnd, pingPong ) {
  28019. const settings = this._interpolantSettings;
  28020. if ( pingPong ) {
  28021. settings.endingStart = ZeroSlopeEnding;
  28022. settings.endingEnd = ZeroSlopeEnding;
  28023. } else {
  28024. // assuming for LoopOnce atStart == atEnd == true
  28025. if ( atStart ) {
  28026. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28027. } else {
  28028. settings.endingStart = WrapAroundEnding;
  28029. }
  28030. if ( atEnd ) {
  28031. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28032. } else {
  28033. settings.endingEnd = WrapAroundEnding;
  28034. }
  28035. }
  28036. }
  28037. _scheduleFading( duration, weightNow, weightThen ) {
  28038. const mixer = this._mixer, now = mixer.time;
  28039. let interpolant = this._weightInterpolant;
  28040. if ( interpolant === null ) {
  28041. interpolant = mixer._lendControlInterpolant();
  28042. this._weightInterpolant = interpolant;
  28043. }
  28044. const times = interpolant.parameterPositions,
  28045. values = interpolant.sampleValues;
  28046. times[ 0 ] = now;
  28047. values[ 0 ] = weightNow;
  28048. times[ 1 ] = now + duration;
  28049. values[ 1 ] = weightThen;
  28050. return this;
  28051. }
  28052. }
  28053. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  28054. class AnimationMixer extends EventDispatcher {
  28055. constructor( root ) {
  28056. super();
  28057. this._root = root;
  28058. this._initMemoryManager();
  28059. this._accuIndex = 0;
  28060. this.time = 0;
  28061. this.timeScale = 1.0;
  28062. }
  28063. _bindAction( action, prototypeAction ) {
  28064. const root = action._localRoot || this._root,
  28065. tracks = action._clip.tracks,
  28066. nTracks = tracks.length,
  28067. bindings = action._propertyBindings,
  28068. interpolants = action._interpolants,
  28069. rootUuid = root.uuid,
  28070. bindingsByRoot = this._bindingsByRootAndName;
  28071. let bindingsByName = bindingsByRoot[ rootUuid ];
  28072. if ( bindingsByName === undefined ) {
  28073. bindingsByName = {};
  28074. bindingsByRoot[ rootUuid ] = bindingsByName;
  28075. }
  28076. for ( let i = 0; i !== nTracks; ++ i ) {
  28077. const track = tracks[ i ],
  28078. trackName = track.name;
  28079. let binding = bindingsByName[ trackName ];
  28080. if ( binding !== undefined ) {
  28081. ++ binding.referenceCount;
  28082. bindings[ i ] = binding;
  28083. } else {
  28084. binding = bindings[ i ];
  28085. if ( binding !== undefined ) {
  28086. // existing binding, make sure the cache knows
  28087. if ( binding._cacheIndex === null ) {
  28088. ++ binding.referenceCount;
  28089. this._addInactiveBinding( binding, rootUuid, trackName );
  28090. }
  28091. continue;
  28092. }
  28093. const path = prototypeAction && prototypeAction.
  28094. _propertyBindings[ i ].binding.parsedPath;
  28095. binding = new PropertyMixer(
  28096. PropertyBinding.create( root, trackName, path ),
  28097. track.ValueTypeName, track.getValueSize() );
  28098. ++ binding.referenceCount;
  28099. this._addInactiveBinding( binding, rootUuid, trackName );
  28100. bindings[ i ] = binding;
  28101. }
  28102. interpolants[ i ].resultBuffer = binding.buffer;
  28103. }
  28104. }
  28105. _activateAction( action ) {
  28106. if ( ! this._isActiveAction( action ) ) {
  28107. if ( action._cacheIndex === null ) {
  28108. // this action has been forgotten by the cache, but the user
  28109. // appears to be still using it -> rebind
  28110. const rootUuid = ( action._localRoot || this._root ).uuid,
  28111. clipUuid = action._clip.uuid,
  28112. actionsForClip = this._actionsByClip[ clipUuid ];
  28113. this._bindAction( action,
  28114. actionsForClip && actionsForClip.knownActions[ 0 ] );
  28115. this._addInactiveAction( action, clipUuid, rootUuid );
  28116. }
  28117. const bindings = action._propertyBindings;
  28118. // increment reference counts / sort out state
  28119. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28120. const binding = bindings[ i ];
  28121. if ( binding.useCount ++ === 0 ) {
  28122. this._lendBinding( binding );
  28123. binding.saveOriginalState();
  28124. }
  28125. }
  28126. this._lendAction( action );
  28127. }
  28128. }
  28129. _deactivateAction( action ) {
  28130. if ( this._isActiveAction( action ) ) {
  28131. const bindings = action._propertyBindings;
  28132. // decrement reference counts / sort out state
  28133. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28134. const binding = bindings[ i ];
  28135. if ( -- binding.useCount === 0 ) {
  28136. binding.restoreOriginalState();
  28137. this._takeBackBinding( binding );
  28138. }
  28139. }
  28140. this._takeBackAction( action );
  28141. }
  28142. }
  28143. // Memory manager
  28144. _initMemoryManager() {
  28145. this._actions = []; // 'nActiveActions' followed by inactive ones
  28146. this._nActiveActions = 0;
  28147. this._actionsByClip = {};
  28148. // inside:
  28149. // {
  28150. // knownActions: Array< AnimationAction > - used as prototypes
  28151. // actionByRoot: AnimationAction - lookup
  28152. // }
  28153. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  28154. this._nActiveBindings = 0;
  28155. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  28156. this._controlInterpolants = []; // same game as above
  28157. this._nActiveControlInterpolants = 0;
  28158. const scope = this;
  28159. this.stats = {
  28160. actions: {
  28161. get total() {
  28162. return scope._actions.length;
  28163. },
  28164. get inUse() {
  28165. return scope._nActiveActions;
  28166. }
  28167. },
  28168. bindings: {
  28169. get total() {
  28170. return scope._bindings.length;
  28171. },
  28172. get inUse() {
  28173. return scope._nActiveBindings;
  28174. }
  28175. },
  28176. controlInterpolants: {
  28177. get total() {
  28178. return scope._controlInterpolants.length;
  28179. },
  28180. get inUse() {
  28181. return scope._nActiveControlInterpolants;
  28182. }
  28183. }
  28184. };
  28185. }
  28186. // Memory management for AnimationAction objects
  28187. _isActiveAction( action ) {
  28188. const index = action._cacheIndex;
  28189. return index !== null && index < this._nActiveActions;
  28190. }
  28191. _addInactiveAction( action, clipUuid, rootUuid ) {
  28192. const actions = this._actions,
  28193. actionsByClip = this._actionsByClip;
  28194. let actionsForClip = actionsByClip[ clipUuid ];
  28195. if ( actionsForClip === undefined ) {
  28196. actionsForClip = {
  28197. knownActions: [ action ],
  28198. actionByRoot: {}
  28199. };
  28200. action._byClipCacheIndex = 0;
  28201. actionsByClip[ clipUuid ] = actionsForClip;
  28202. } else {
  28203. const knownActions = actionsForClip.knownActions;
  28204. action._byClipCacheIndex = knownActions.length;
  28205. knownActions.push( action );
  28206. }
  28207. action._cacheIndex = actions.length;
  28208. actions.push( action );
  28209. actionsForClip.actionByRoot[ rootUuid ] = action;
  28210. }
  28211. _removeInactiveAction( action ) {
  28212. const actions = this._actions,
  28213. lastInactiveAction = actions[ actions.length - 1 ],
  28214. cacheIndex = action._cacheIndex;
  28215. lastInactiveAction._cacheIndex = cacheIndex;
  28216. actions[ cacheIndex ] = lastInactiveAction;
  28217. actions.pop();
  28218. action._cacheIndex = null;
  28219. const clipUuid = action._clip.uuid,
  28220. actionsByClip = this._actionsByClip,
  28221. actionsForClip = actionsByClip[ clipUuid ],
  28222. knownActionsForClip = actionsForClip.knownActions,
  28223. lastKnownAction =
  28224. knownActionsForClip[ knownActionsForClip.length - 1 ],
  28225. byClipCacheIndex = action._byClipCacheIndex;
  28226. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  28227. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  28228. knownActionsForClip.pop();
  28229. action._byClipCacheIndex = null;
  28230. const actionByRoot = actionsForClip.actionByRoot,
  28231. rootUuid = ( action._localRoot || this._root ).uuid;
  28232. delete actionByRoot[ rootUuid ];
  28233. if ( knownActionsForClip.length === 0 ) {
  28234. delete actionsByClip[ clipUuid ];
  28235. }
  28236. this._removeInactiveBindingsForAction( action );
  28237. }
  28238. _removeInactiveBindingsForAction( action ) {
  28239. const bindings = action._propertyBindings;
  28240. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28241. const binding = bindings[ i ];
  28242. if ( -- binding.referenceCount === 0 ) {
  28243. this._removeInactiveBinding( binding );
  28244. }
  28245. }
  28246. }
  28247. _lendAction( action ) {
  28248. // [ active actions | inactive actions ]
  28249. // [ active actions >| inactive actions ]
  28250. // s a
  28251. // <-swap->
  28252. // a s
  28253. const actions = this._actions,
  28254. prevIndex = action._cacheIndex,
  28255. lastActiveIndex = this._nActiveActions ++,
  28256. firstInactiveAction = actions[ lastActiveIndex ];
  28257. action._cacheIndex = lastActiveIndex;
  28258. actions[ lastActiveIndex ] = action;
  28259. firstInactiveAction._cacheIndex = prevIndex;
  28260. actions[ prevIndex ] = firstInactiveAction;
  28261. }
  28262. _takeBackAction( action ) {
  28263. // [ active actions | inactive actions ]
  28264. // [ active actions |< inactive actions ]
  28265. // a s
  28266. // <-swap->
  28267. // s a
  28268. const actions = this._actions,
  28269. prevIndex = action._cacheIndex,
  28270. firstInactiveIndex = -- this._nActiveActions,
  28271. lastActiveAction = actions[ firstInactiveIndex ];
  28272. action._cacheIndex = firstInactiveIndex;
  28273. actions[ firstInactiveIndex ] = action;
  28274. lastActiveAction._cacheIndex = prevIndex;
  28275. actions[ prevIndex ] = lastActiveAction;
  28276. }
  28277. // Memory management for PropertyMixer objects
  28278. _addInactiveBinding( binding, rootUuid, trackName ) {
  28279. const bindingsByRoot = this._bindingsByRootAndName,
  28280. bindings = this._bindings;
  28281. let bindingByName = bindingsByRoot[ rootUuid ];
  28282. if ( bindingByName === undefined ) {
  28283. bindingByName = {};
  28284. bindingsByRoot[ rootUuid ] = bindingByName;
  28285. }
  28286. bindingByName[ trackName ] = binding;
  28287. binding._cacheIndex = bindings.length;
  28288. bindings.push( binding );
  28289. }
  28290. _removeInactiveBinding( binding ) {
  28291. const bindings = this._bindings,
  28292. propBinding = binding.binding,
  28293. rootUuid = propBinding.rootNode.uuid,
  28294. trackName = propBinding.path,
  28295. bindingsByRoot = this._bindingsByRootAndName,
  28296. bindingByName = bindingsByRoot[ rootUuid ],
  28297. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28298. cacheIndex = binding._cacheIndex;
  28299. lastInactiveBinding._cacheIndex = cacheIndex;
  28300. bindings[ cacheIndex ] = lastInactiveBinding;
  28301. bindings.pop();
  28302. delete bindingByName[ trackName ];
  28303. if ( Object.keys( bindingByName ).length === 0 ) {
  28304. delete bindingsByRoot[ rootUuid ];
  28305. }
  28306. }
  28307. _lendBinding( binding ) {
  28308. const bindings = this._bindings,
  28309. prevIndex = binding._cacheIndex,
  28310. lastActiveIndex = this._nActiveBindings ++,
  28311. firstInactiveBinding = bindings[ lastActiveIndex ];
  28312. binding._cacheIndex = lastActiveIndex;
  28313. bindings[ lastActiveIndex ] = binding;
  28314. firstInactiveBinding._cacheIndex = prevIndex;
  28315. bindings[ prevIndex ] = firstInactiveBinding;
  28316. }
  28317. _takeBackBinding( binding ) {
  28318. const bindings = this._bindings,
  28319. prevIndex = binding._cacheIndex,
  28320. firstInactiveIndex = -- this._nActiveBindings,
  28321. lastActiveBinding = bindings[ firstInactiveIndex ];
  28322. binding._cacheIndex = firstInactiveIndex;
  28323. bindings[ firstInactiveIndex ] = binding;
  28324. lastActiveBinding._cacheIndex = prevIndex;
  28325. bindings[ prevIndex ] = lastActiveBinding;
  28326. }
  28327. // Memory management of Interpolants for weight and time scale
  28328. _lendControlInterpolant() {
  28329. const interpolants = this._controlInterpolants,
  28330. lastActiveIndex = this._nActiveControlInterpolants ++;
  28331. let interpolant = interpolants[ lastActiveIndex ];
  28332. if ( interpolant === undefined ) {
  28333. interpolant = new LinearInterpolant(
  28334. new Float32Array( 2 ), new Float32Array( 2 ),
  28335. 1, _controlInterpolantsResultBuffer );
  28336. interpolant.__cacheIndex = lastActiveIndex;
  28337. interpolants[ lastActiveIndex ] = interpolant;
  28338. }
  28339. return interpolant;
  28340. }
  28341. _takeBackControlInterpolant( interpolant ) {
  28342. const interpolants = this._controlInterpolants,
  28343. prevIndex = interpolant.__cacheIndex,
  28344. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28345. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28346. interpolant.__cacheIndex = firstInactiveIndex;
  28347. interpolants[ firstInactiveIndex ] = interpolant;
  28348. lastActiveInterpolant.__cacheIndex = prevIndex;
  28349. interpolants[ prevIndex ] = lastActiveInterpolant;
  28350. }
  28351. // return an action for a clip optionally using a custom root target
  28352. // object (this method allocates a lot of dynamic memory in case a
  28353. // previously unknown clip/root combination is specified)
  28354. clipAction( clip, optionalRoot, blendMode ) {
  28355. const root = optionalRoot || this._root,
  28356. rootUuid = root.uuid;
  28357. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28358. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28359. const actionsForClip = this._actionsByClip[ clipUuid ];
  28360. let prototypeAction = null;
  28361. if ( blendMode === undefined ) {
  28362. if ( clipObject !== null ) {
  28363. blendMode = clipObject.blendMode;
  28364. } else {
  28365. blendMode = NormalAnimationBlendMode;
  28366. }
  28367. }
  28368. if ( actionsForClip !== undefined ) {
  28369. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28370. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28371. return existingAction;
  28372. }
  28373. // we know the clip, so we don't have to parse all
  28374. // the bindings again but can just copy
  28375. prototypeAction = actionsForClip.knownActions[ 0 ];
  28376. // also, take the clip from the prototype action
  28377. if ( clipObject === null )
  28378. clipObject = prototypeAction._clip;
  28379. }
  28380. // clip must be known when specified via string
  28381. if ( clipObject === null ) return null;
  28382. // allocate all resources required to run it
  28383. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28384. this._bindAction( newAction, prototypeAction );
  28385. // and make the action known to the memory manager
  28386. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28387. return newAction;
  28388. }
  28389. // get an existing action
  28390. existingAction( clip, optionalRoot ) {
  28391. const root = optionalRoot || this._root,
  28392. rootUuid = root.uuid,
  28393. clipObject = typeof clip === 'string' ?
  28394. AnimationClip.findByName( root, clip ) : clip,
  28395. clipUuid = clipObject ? clipObject.uuid : clip,
  28396. actionsForClip = this._actionsByClip[ clipUuid ];
  28397. if ( actionsForClip !== undefined ) {
  28398. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28399. }
  28400. return null;
  28401. }
  28402. // deactivates all previously scheduled actions
  28403. stopAllAction() {
  28404. const actions = this._actions,
  28405. nActions = this._nActiveActions;
  28406. for ( let i = nActions - 1; i >= 0; -- i ) {
  28407. actions[ i ].stop();
  28408. }
  28409. return this;
  28410. }
  28411. // advance the time and update apply the animation
  28412. update( deltaTime ) {
  28413. deltaTime *= this.timeScale;
  28414. const actions = this._actions,
  28415. nActions = this._nActiveActions,
  28416. time = this.time += deltaTime,
  28417. timeDirection = Math.sign( deltaTime ),
  28418. accuIndex = this._accuIndex ^= 1;
  28419. // run active actions
  28420. for ( let i = 0; i !== nActions; ++ i ) {
  28421. const action = actions[ i ];
  28422. action._update( time, deltaTime, timeDirection, accuIndex );
  28423. }
  28424. // update scene graph
  28425. const bindings = this._bindings,
  28426. nBindings = this._nActiveBindings;
  28427. for ( let i = 0; i !== nBindings; ++ i ) {
  28428. bindings[ i ].apply( accuIndex );
  28429. }
  28430. return this;
  28431. }
  28432. // Allows you to seek to a specific time in an animation.
  28433. setTime( timeInSeconds ) {
  28434. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28435. for ( let i = 0; i < this._actions.length; i ++ ) {
  28436. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28437. }
  28438. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28439. }
  28440. // return this mixer's root target object
  28441. getRoot() {
  28442. return this._root;
  28443. }
  28444. // free all resources specific to a particular clip
  28445. uncacheClip( clip ) {
  28446. const actions = this._actions,
  28447. clipUuid = clip.uuid,
  28448. actionsByClip = this._actionsByClip,
  28449. actionsForClip = actionsByClip[ clipUuid ];
  28450. if ( actionsForClip !== undefined ) {
  28451. // note: just calling _removeInactiveAction would mess up the
  28452. // iteration state and also require updating the state we can
  28453. // just throw away
  28454. const actionsToRemove = actionsForClip.knownActions;
  28455. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28456. const action = actionsToRemove[ i ];
  28457. this._deactivateAction( action );
  28458. const cacheIndex = action._cacheIndex,
  28459. lastInactiveAction = actions[ actions.length - 1 ];
  28460. action._cacheIndex = null;
  28461. action._byClipCacheIndex = null;
  28462. lastInactiveAction._cacheIndex = cacheIndex;
  28463. actions[ cacheIndex ] = lastInactiveAction;
  28464. actions.pop();
  28465. this._removeInactiveBindingsForAction( action );
  28466. }
  28467. delete actionsByClip[ clipUuid ];
  28468. }
  28469. }
  28470. // free all resources specific to a particular root target object
  28471. uncacheRoot( root ) {
  28472. const rootUuid = root.uuid,
  28473. actionsByClip = this._actionsByClip;
  28474. for ( const clipUuid in actionsByClip ) {
  28475. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28476. action = actionByRoot[ rootUuid ];
  28477. if ( action !== undefined ) {
  28478. this._deactivateAction( action );
  28479. this._removeInactiveAction( action );
  28480. }
  28481. }
  28482. const bindingsByRoot = this._bindingsByRootAndName,
  28483. bindingByName = bindingsByRoot[ rootUuid ];
  28484. if ( bindingByName !== undefined ) {
  28485. for ( const trackName in bindingByName ) {
  28486. const binding = bindingByName[ trackName ];
  28487. binding.restoreOriginalState();
  28488. this._removeInactiveBinding( binding );
  28489. }
  28490. }
  28491. }
  28492. // remove a targeted clip from the cache
  28493. uncacheAction( clip, optionalRoot ) {
  28494. const action = this.existingAction( clip, optionalRoot );
  28495. if ( action !== null ) {
  28496. this._deactivateAction( action );
  28497. this._removeInactiveAction( action );
  28498. }
  28499. }
  28500. }
  28501. class Uniform {
  28502. constructor( value ) {
  28503. this.value = value;
  28504. }
  28505. clone() {
  28506. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28507. }
  28508. }
  28509. let id = 0;
  28510. class UniformsGroup extends EventDispatcher {
  28511. constructor() {
  28512. super();
  28513. this.isUniformsGroup = true;
  28514. Object.defineProperty( this, 'id', { value: id ++ } );
  28515. this.name = '';
  28516. this.usage = StaticDrawUsage;
  28517. this.uniforms = [];
  28518. }
  28519. add( uniform ) {
  28520. this.uniforms.push( uniform );
  28521. return this;
  28522. }
  28523. remove( uniform ) {
  28524. const index = this.uniforms.indexOf( uniform );
  28525. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28526. return this;
  28527. }
  28528. setName( name ) {
  28529. this.name = name;
  28530. return this;
  28531. }
  28532. setUsage( value ) {
  28533. this.usage = value;
  28534. return this;
  28535. }
  28536. dispose() {
  28537. this.dispatchEvent( { type: 'dispose' } );
  28538. return this;
  28539. }
  28540. copy( source ) {
  28541. this.name = source.name;
  28542. this.usage = source.usage;
  28543. const uniformsSource = source.uniforms;
  28544. this.uniforms.length = 0;
  28545. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28546. this.uniforms.push( uniformsSource[ i ].clone() );
  28547. }
  28548. return this;
  28549. }
  28550. clone() {
  28551. return new this.constructor().copy( this );
  28552. }
  28553. }
  28554. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28555. constructor( array, stride, meshPerAttribute = 1 ) {
  28556. super( array, stride );
  28557. this.isInstancedInterleavedBuffer = true;
  28558. this.meshPerAttribute = meshPerAttribute;
  28559. }
  28560. copy( source ) {
  28561. super.copy( source );
  28562. this.meshPerAttribute = source.meshPerAttribute;
  28563. return this;
  28564. }
  28565. clone( data ) {
  28566. const ib = super.clone( data );
  28567. ib.meshPerAttribute = this.meshPerAttribute;
  28568. return ib;
  28569. }
  28570. toJSON( data ) {
  28571. const json = super.toJSON( data );
  28572. json.isInstancedInterleavedBuffer = true;
  28573. json.meshPerAttribute = this.meshPerAttribute;
  28574. return json;
  28575. }
  28576. }
  28577. class GLBufferAttribute {
  28578. constructor( buffer, type, itemSize, elementSize, count ) {
  28579. this.isGLBufferAttribute = true;
  28580. this.name = '';
  28581. this.buffer = buffer;
  28582. this.type = type;
  28583. this.itemSize = itemSize;
  28584. this.elementSize = elementSize;
  28585. this.count = count;
  28586. this.version = 0;
  28587. }
  28588. set needsUpdate( value ) {
  28589. if ( value === true ) this.version ++;
  28590. }
  28591. setBuffer( buffer ) {
  28592. this.buffer = buffer;
  28593. return this;
  28594. }
  28595. setType( type, elementSize ) {
  28596. this.type = type;
  28597. this.elementSize = elementSize;
  28598. return this;
  28599. }
  28600. setItemSize( itemSize ) {
  28601. this.itemSize = itemSize;
  28602. return this;
  28603. }
  28604. setCount( count ) {
  28605. this.count = count;
  28606. return this;
  28607. }
  28608. }
  28609. class Raycaster {
  28610. constructor( origin, direction, near = 0, far = Infinity ) {
  28611. this.ray = new Ray( origin, direction );
  28612. // direction is assumed to be normalized (for accurate distance calculations)
  28613. this.near = near;
  28614. this.far = far;
  28615. this.camera = null;
  28616. this.layers = new Layers();
  28617. this.params = {
  28618. Mesh: {},
  28619. Line: { threshold: 1 },
  28620. LOD: {},
  28621. Points: { threshold: 1 },
  28622. Sprite: {}
  28623. };
  28624. }
  28625. set( origin, direction ) {
  28626. // direction is assumed to be normalized (for accurate distance calculations)
  28627. this.ray.set( origin, direction );
  28628. }
  28629. setFromCamera( coords, camera ) {
  28630. if ( camera.isPerspectiveCamera ) {
  28631. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28632. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28633. this.camera = camera;
  28634. } else if ( camera.isOrthographicCamera ) {
  28635. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28636. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28637. this.camera = camera;
  28638. } else {
  28639. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28640. }
  28641. }
  28642. intersectObject( object, recursive = true, intersects = [] ) {
  28643. intersectObject( object, this, intersects, recursive );
  28644. intersects.sort( ascSort );
  28645. return intersects;
  28646. }
  28647. intersectObjects( objects, recursive = true, intersects = [] ) {
  28648. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28649. intersectObject( objects[ i ], this, intersects, recursive );
  28650. }
  28651. intersects.sort( ascSort );
  28652. return intersects;
  28653. }
  28654. }
  28655. function ascSort( a, b ) {
  28656. return a.distance - b.distance;
  28657. }
  28658. function intersectObject( object, raycaster, intersects, recursive ) {
  28659. if ( object.layers.test( raycaster.layers ) ) {
  28660. object.raycast( raycaster, intersects );
  28661. }
  28662. if ( recursive === true ) {
  28663. const children = object.children;
  28664. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28665. intersectObject( children[ i ], raycaster, intersects, true );
  28666. }
  28667. }
  28668. }
  28669. /**
  28670. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28671. *
  28672. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28673. * The azimuthal angle (theta) is measured from the positive z-axis.
  28674. */
  28675. class Spherical {
  28676. constructor( radius = 1, phi = 0, theta = 0 ) {
  28677. this.radius = radius;
  28678. this.phi = phi; // polar angle
  28679. this.theta = theta; // azimuthal angle
  28680. return this;
  28681. }
  28682. set( radius, phi, theta ) {
  28683. this.radius = radius;
  28684. this.phi = phi;
  28685. this.theta = theta;
  28686. return this;
  28687. }
  28688. copy( other ) {
  28689. this.radius = other.radius;
  28690. this.phi = other.phi;
  28691. this.theta = other.theta;
  28692. return this;
  28693. }
  28694. // restrict phi to be between EPS and PI-EPS
  28695. makeSafe() {
  28696. const EPS = 0.000001;
  28697. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28698. return this;
  28699. }
  28700. setFromVector3( v ) {
  28701. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28702. }
  28703. setFromCartesianCoords( x, y, z ) {
  28704. this.radius = Math.sqrt( x * x + y * y + z * z );
  28705. if ( this.radius === 0 ) {
  28706. this.theta = 0;
  28707. this.phi = 0;
  28708. } else {
  28709. this.theta = Math.atan2( x, z );
  28710. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28711. }
  28712. return this;
  28713. }
  28714. clone() {
  28715. return new this.constructor().copy( this );
  28716. }
  28717. }
  28718. /**
  28719. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28720. */
  28721. class Cylindrical {
  28722. constructor( radius = 1, theta = 0, y = 0 ) {
  28723. this.radius = radius; // distance from the origin to a point in the x-z plane
  28724. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28725. this.y = y; // height above the x-z plane
  28726. return this;
  28727. }
  28728. set( radius, theta, y ) {
  28729. this.radius = radius;
  28730. this.theta = theta;
  28731. this.y = y;
  28732. return this;
  28733. }
  28734. copy( other ) {
  28735. this.radius = other.radius;
  28736. this.theta = other.theta;
  28737. this.y = other.y;
  28738. return this;
  28739. }
  28740. setFromVector3( v ) {
  28741. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28742. }
  28743. setFromCartesianCoords( x, y, z ) {
  28744. this.radius = Math.sqrt( x * x + z * z );
  28745. this.theta = Math.atan2( x, z );
  28746. this.y = y;
  28747. return this;
  28748. }
  28749. clone() {
  28750. return new this.constructor().copy( this );
  28751. }
  28752. }
  28753. const _vector$4 = /*@__PURE__*/ new Vector2();
  28754. class Box2 {
  28755. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28756. this.isBox2 = true;
  28757. this.min = min;
  28758. this.max = max;
  28759. }
  28760. set( min, max ) {
  28761. this.min.copy( min );
  28762. this.max.copy( max );
  28763. return this;
  28764. }
  28765. setFromPoints( points ) {
  28766. this.makeEmpty();
  28767. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28768. this.expandByPoint( points[ i ] );
  28769. }
  28770. return this;
  28771. }
  28772. setFromCenterAndSize( center, size ) {
  28773. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28774. this.min.copy( center ).sub( halfSize );
  28775. this.max.copy( center ).add( halfSize );
  28776. return this;
  28777. }
  28778. clone() {
  28779. return new this.constructor().copy( this );
  28780. }
  28781. copy( box ) {
  28782. this.min.copy( box.min );
  28783. this.max.copy( box.max );
  28784. return this;
  28785. }
  28786. makeEmpty() {
  28787. this.min.x = this.min.y = + Infinity;
  28788. this.max.x = this.max.y = - Infinity;
  28789. return this;
  28790. }
  28791. isEmpty() {
  28792. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28793. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28794. }
  28795. getCenter( target ) {
  28796. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28797. }
  28798. getSize( target ) {
  28799. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28800. }
  28801. expandByPoint( point ) {
  28802. this.min.min( point );
  28803. this.max.max( point );
  28804. return this;
  28805. }
  28806. expandByVector( vector ) {
  28807. this.min.sub( vector );
  28808. this.max.add( vector );
  28809. return this;
  28810. }
  28811. expandByScalar( scalar ) {
  28812. this.min.addScalar( - scalar );
  28813. this.max.addScalar( scalar );
  28814. return this;
  28815. }
  28816. containsPoint( point ) {
  28817. return point.x < this.min.x || point.x > this.max.x ||
  28818. point.y < this.min.y || point.y > this.max.y ? false : true;
  28819. }
  28820. containsBox( box ) {
  28821. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28822. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28823. }
  28824. getParameter( point, target ) {
  28825. // This can potentially have a divide by zero if the box
  28826. // has a size dimension of 0.
  28827. return target.set(
  28828. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28829. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28830. );
  28831. }
  28832. intersectsBox( box ) {
  28833. // using 4 splitting planes to rule out intersections
  28834. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28835. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28836. }
  28837. clampPoint( point, target ) {
  28838. return target.copy( point ).clamp( this.min, this.max );
  28839. }
  28840. distanceToPoint( point ) {
  28841. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  28842. }
  28843. intersect( box ) {
  28844. this.min.max( box.min );
  28845. this.max.min( box.max );
  28846. if ( this.isEmpty() ) this.makeEmpty();
  28847. return this;
  28848. }
  28849. union( box ) {
  28850. this.min.min( box.min );
  28851. this.max.max( box.max );
  28852. return this;
  28853. }
  28854. translate( offset ) {
  28855. this.min.add( offset );
  28856. this.max.add( offset );
  28857. return this;
  28858. }
  28859. equals( box ) {
  28860. return box.min.equals( this.min ) && box.max.equals( this.max );
  28861. }
  28862. }
  28863. const _startP = /*@__PURE__*/ new Vector3();
  28864. const _startEnd = /*@__PURE__*/ new Vector3();
  28865. class Line3 {
  28866. constructor( start = new Vector3(), end = new Vector3() ) {
  28867. this.start = start;
  28868. this.end = end;
  28869. }
  28870. set( start, end ) {
  28871. this.start.copy( start );
  28872. this.end.copy( end );
  28873. return this;
  28874. }
  28875. copy( line ) {
  28876. this.start.copy( line.start );
  28877. this.end.copy( line.end );
  28878. return this;
  28879. }
  28880. getCenter( target ) {
  28881. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28882. }
  28883. delta( target ) {
  28884. return target.subVectors( this.end, this.start );
  28885. }
  28886. distanceSq() {
  28887. return this.start.distanceToSquared( this.end );
  28888. }
  28889. distance() {
  28890. return this.start.distanceTo( this.end );
  28891. }
  28892. at( t, target ) {
  28893. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28894. }
  28895. closestPointToPointParameter( point, clampToLine ) {
  28896. _startP.subVectors( point, this.start );
  28897. _startEnd.subVectors( this.end, this.start );
  28898. const startEnd2 = _startEnd.dot( _startEnd );
  28899. const startEnd_startP = _startEnd.dot( _startP );
  28900. let t = startEnd_startP / startEnd2;
  28901. if ( clampToLine ) {
  28902. t = clamp( t, 0, 1 );
  28903. }
  28904. return t;
  28905. }
  28906. closestPointToPoint( point, clampToLine, target ) {
  28907. const t = this.closestPointToPointParameter( point, clampToLine );
  28908. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28909. }
  28910. applyMatrix4( matrix ) {
  28911. this.start.applyMatrix4( matrix );
  28912. this.end.applyMatrix4( matrix );
  28913. return this;
  28914. }
  28915. equals( line ) {
  28916. return line.start.equals( this.start ) && line.end.equals( this.end );
  28917. }
  28918. clone() {
  28919. return new this.constructor().copy( this );
  28920. }
  28921. }
  28922. const _vector$3 = /*@__PURE__*/ new Vector3();
  28923. class SpotLightHelper extends Object3D {
  28924. constructor( light, color ) {
  28925. super();
  28926. this.light = light;
  28927. this.matrix = light.matrixWorld;
  28928. this.matrixAutoUpdate = false;
  28929. this.color = color;
  28930. this.type = 'SpotLightHelper';
  28931. const geometry = new BufferGeometry();
  28932. const positions = [
  28933. 0, 0, 0, 0, 0, 1,
  28934. 0, 0, 0, 1, 0, 1,
  28935. 0, 0, 0, - 1, 0, 1,
  28936. 0, 0, 0, 0, 1, 1,
  28937. 0, 0, 0, 0, - 1, 1
  28938. ];
  28939. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28940. const p1 = ( i / l ) * Math.PI * 2;
  28941. const p2 = ( j / l ) * Math.PI * 2;
  28942. positions.push(
  28943. Math.cos( p1 ), Math.sin( p1 ), 1,
  28944. Math.cos( p2 ), Math.sin( p2 ), 1
  28945. );
  28946. }
  28947. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28948. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28949. this.cone = new LineSegments( geometry, material );
  28950. this.add( this.cone );
  28951. this.update();
  28952. }
  28953. dispose() {
  28954. this.cone.geometry.dispose();
  28955. this.cone.material.dispose();
  28956. }
  28957. update() {
  28958. this.light.updateWorldMatrix( true, false );
  28959. this.light.target.updateWorldMatrix( true, false );
  28960. const coneLength = this.light.distance ? this.light.distance : 1000;
  28961. const coneWidth = coneLength * Math.tan( this.light.angle );
  28962. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28963. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28964. this.cone.lookAt( _vector$3 );
  28965. if ( this.color !== undefined ) {
  28966. this.cone.material.color.set( this.color );
  28967. } else {
  28968. this.cone.material.color.copy( this.light.color );
  28969. }
  28970. }
  28971. }
  28972. const _vector$2 = /*@__PURE__*/ new Vector3();
  28973. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28974. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28975. class SkeletonHelper extends LineSegments {
  28976. constructor( object ) {
  28977. const bones = getBoneList( object );
  28978. const geometry = new BufferGeometry();
  28979. const vertices = [];
  28980. const colors = [];
  28981. const color1 = new Color( 0, 0, 1 );
  28982. const color2 = new Color( 0, 1, 0 );
  28983. for ( let i = 0; i < bones.length; i ++ ) {
  28984. const bone = bones[ i ];
  28985. if ( bone.parent && bone.parent.isBone ) {
  28986. vertices.push( 0, 0, 0 );
  28987. vertices.push( 0, 0, 0 );
  28988. colors.push( color1.r, color1.g, color1.b );
  28989. colors.push( color2.r, color2.g, color2.b );
  28990. }
  28991. }
  28992. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28993. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28994. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28995. super( geometry, material );
  28996. this.isSkeletonHelper = true;
  28997. this.type = 'SkeletonHelper';
  28998. this.root = object;
  28999. this.bones = bones;
  29000. this.matrix = object.matrixWorld;
  29001. this.matrixAutoUpdate = false;
  29002. }
  29003. updateMatrixWorld( force ) {
  29004. const bones = this.bones;
  29005. const geometry = this.geometry;
  29006. const position = geometry.getAttribute( 'position' );
  29007. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  29008. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  29009. const bone = bones[ i ];
  29010. if ( bone.parent && bone.parent.isBone ) {
  29011. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  29012. _vector$2.setFromMatrixPosition( _boneMatrix );
  29013. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  29014. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  29015. _vector$2.setFromMatrixPosition( _boneMatrix );
  29016. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  29017. j += 2;
  29018. }
  29019. }
  29020. geometry.getAttribute( 'position' ).needsUpdate = true;
  29021. super.updateMatrixWorld( force );
  29022. }
  29023. dispose() {
  29024. this.geometry.dispose();
  29025. this.material.dispose();
  29026. }
  29027. }
  29028. function getBoneList( object ) {
  29029. const boneList = [];
  29030. if ( object.isBone === true ) {
  29031. boneList.push( object );
  29032. }
  29033. for ( let i = 0; i < object.children.length; i ++ ) {
  29034. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  29035. }
  29036. return boneList;
  29037. }
  29038. class PointLightHelper extends Mesh {
  29039. constructor( light, sphereSize, color ) {
  29040. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  29041. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29042. super( geometry, material );
  29043. this.light = light;
  29044. this.color = color;
  29045. this.type = 'PointLightHelper';
  29046. this.matrix = this.light.matrixWorld;
  29047. this.matrixAutoUpdate = false;
  29048. this.update();
  29049. /*
  29050. // TODO: delete this comment?
  29051. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  29052. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  29053. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  29054. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  29055. const d = light.distance;
  29056. if ( d === 0.0 ) {
  29057. this.lightDistance.visible = false;
  29058. } else {
  29059. this.lightDistance.scale.set( d, d, d );
  29060. }
  29061. this.add( this.lightDistance );
  29062. */
  29063. }
  29064. dispose() {
  29065. this.geometry.dispose();
  29066. this.material.dispose();
  29067. }
  29068. update() {
  29069. this.light.updateWorldMatrix( true, false );
  29070. if ( this.color !== undefined ) {
  29071. this.material.color.set( this.color );
  29072. } else {
  29073. this.material.color.copy( this.light.color );
  29074. }
  29075. /*
  29076. const d = this.light.distance;
  29077. if ( d === 0.0 ) {
  29078. this.lightDistance.visible = false;
  29079. } else {
  29080. this.lightDistance.visible = true;
  29081. this.lightDistance.scale.set( d, d, d );
  29082. }
  29083. */
  29084. }
  29085. }
  29086. const _vector$1 = /*@__PURE__*/ new Vector3();
  29087. const _color1 = /*@__PURE__*/ new Color();
  29088. const _color2 = /*@__PURE__*/ new Color();
  29089. class HemisphereLightHelper extends Object3D {
  29090. constructor( light, size, color ) {
  29091. super();
  29092. this.light = light;
  29093. this.matrix = light.matrixWorld;
  29094. this.matrixAutoUpdate = false;
  29095. this.color = color;
  29096. this.type = 'HemisphereLightHelper';
  29097. const geometry = new OctahedronGeometry( size );
  29098. geometry.rotateY( Math.PI * 0.5 );
  29099. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29100. if ( this.color === undefined ) this.material.vertexColors = true;
  29101. const position = geometry.getAttribute( 'position' );
  29102. const colors = new Float32Array( position.count * 3 );
  29103. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  29104. this.add( new Mesh( geometry, this.material ) );
  29105. this.update();
  29106. }
  29107. dispose() {
  29108. this.children[ 0 ].geometry.dispose();
  29109. this.children[ 0 ].material.dispose();
  29110. }
  29111. update() {
  29112. const mesh = this.children[ 0 ];
  29113. if ( this.color !== undefined ) {
  29114. this.material.color.set( this.color );
  29115. } else {
  29116. const colors = mesh.geometry.getAttribute( 'color' );
  29117. _color1.copy( this.light.color );
  29118. _color2.copy( this.light.groundColor );
  29119. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  29120. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  29121. colors.setXYZ( i, color.r, color.g, color.b );
  29122. }
  29123. colors.needsUpdate = true;
  29124. }
  29125. this.light.updateWorldMatrix( true, false );
  29126. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  29127. }
  29128. }
  29129. class GridHelper extends LineSegments {
  29130. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  29131. color1 = new Color( color1 );
  29132. color2 = new Color( color2 );
  29133. const center = divisions / 2;
  29134. const step = size / divisions;
  29135. const halfSize = size / 2;
  29136. const vertices = [], colors = [];
  29137. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  29138. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  29139. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  29140. const color = i === center ? color1 : color2;
  29141. color.toArray( colors, j ); j += 3;
  29142. color.toArray( colors, j ); j += 3;
  29143. color.toArray( colors, j ); j += 3;
  29144. color.toArray( colors, j ); j += 3;
  29145. }
  29146. const geometry = new BufferGeometry();
  29147. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29148. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29149. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29150. super( geometry, material );
  29151. this.type = 'GridHelper';
  29152. }
  29153. dispose() {
  29154. this.geometry.dispose();
  29155. this.material.dispose();
  29156. }
  29157. }
  29158. class PolarGridHelper extends LineSegments {
  29159. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  29160. color1 = new Color( color1 );
  29161. color2 = new Color( color2 );
  29162. const vertices = [];
  29163. const colors = [];
  29164. // create the sectors
  29165. if ( sectors > 1 ) {
  29166. for ( let i = 0; i < sectors; i ++ ) {
  29167. const v = ( i / sectors ) * ( Math.PI * 2 );
  29168. const x = Math.sin( v ) * radius;
  29169. const z = Math.cos( v ) * radius;
  29170. vertices.push( 0, 0, 0 );
  29171. vertices.push( x, 0, z );
  29172. const color = ( i & 1 ) ? color1 : color2;
  29173. colors.push( color.r, color.g, color.b );
  29174. colors.push( color.r, color.g, color.b );
  29175. }
  29176. }
  29177. // create the rings
  29178. for ( let i = 0; i < rings; i ++ ) {
  29179. const color = ( i & 1 ) ? color1 : color2;
  29180. const r = radius - ( radius / rings * i );
  29181. for ( let j = 0; j < divisions; j ++ ) {
  29182. // first vertex
  29183. let v = ( j / divisions ) * ( Math.PI * 2 );
  29184. let x = Math.sin( v ) * r;
  29185. let z = Math.cos( v ) * r;
  29186. vertices.push( x, 0, z );
  29187. colors.push( color.r, color.g, color.b );
  29188. // second vertex
  29189. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  29190. x = Math.sin( v ) * r;
  29191. z = Math.cos( v ) * r;
  29192. vertices.push( x, 0, z );
  29193. colors.push( color.r, color.g, color.b );
  29194. }
  29195. }
  29196. const geometry = new BufferGeometry();
  29197. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29198. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29199. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29200. super( geometry, material );
  29201. this.type = 'PolarGridHelper';
  29202. }
  29203. dispose() {
  29204. this.geometry.dispose();
  29205. this.material.dispose();
  29206. }
  29207. }
  29208. const _v1 = /*@__PURE__*/ new Vector3();
  29209. const _v2 = /*@__PURE__*/ new Vector3();
  29210. const _v3 = /*@__PURE__*/ new Vector3();
  29211. class DirectionalLightHelper extends Object3D {
  29212. constructor( light, size, color ) {
  29213. super();
  29214. this.light = light;
  29215. this.matrix = light.matrixWorld;
  29216. this.matrixAutoUpdate = false;
  29217. this.color = color;
  29218. this.type = 'DirectionalLightHelper';
  29219. if ( size === undefined ) size = 1;
  29220. let geometry = new BufferGeometry();
  29221. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29222. - size, size, 0,
  29223. size, size, 0,
  29224. size, - size, 0,
  29225. - size, - size, 0,
  29226. - size, size, 0
  29227. ], 3 ) );
  29228. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29229. this.lightPlane = new Line( geometry, material );
  29230. this.add( this.lightPlane );
  29231. geometry = new BufferGeometry();
  29232. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29233. this.targetLine = new Line( geometry, material );
  29234. this.add( this.targetLine );
  29235. this.update();
  29236. }
  29237. dispose() {
  29238. this.lightPlane.geometry.dispose();
  29239. this.lightPlane.material.dispose();
  29240. this.targetLine.geometry.dispose();
  29241. this.targetLine.material.dispose();
  29242. }
  29243. update() {
  29244. this.light.updateWorldMatrix( true, false );
  29245. this.light.target.updateWorldMatrix( true, false );
  29246. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29247. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29248. _v3.subVectors( _v2, _v1 );
  29249. this.lightPlane.lookAt( _v2 );
  29250. if ( this.color !== undefined ) {
  29251. this.lightPlane.material.color.set( this.color );
  29252. this.targetLine.material.color.set( this.color );
  29253. } else {
  29254. this.lightPlane.material.color.copy( this.light.color );
  29255. this.targetLine.material.color.copy( this.light.color );
  29256. }
  29257. this.targetLine.lookAt( _v2 );
  29258. this.targetLine.scale.z = _v3.length();
  29259. }
  29260. }
  29261. const _vector = /*@__PURE__*/ new Vector3();
  29262. const _camera = /*@__PURE__*/ new Camera();
  29263. /**
  29264. * - shows frustum, line of sight and up of the camera
  29265. * - suitable for fast updates
  29266. * - based on frustum visualization in lightgl.js shadowmap example
  29267. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  29268. */
  29269. class CameraHelper extends LineSegments {
  29270. constructor( camera ) {
  29271. const geometry = new BufferGeometry();
  29272. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29273. const vertices = [];
  29274. const colors = [];
  29275. const pointMap = {};
  29276. // near
  29277. addLine( 'n1', 'n2' );
  29278. addLine( 'n2', 'n4' );
  29279. addLine( 'n4', 'n3' );
  29280. addLine( 'n3', 'n1' );
  29281. // far
  29282. addLine( 'f1', 'f2' );
  29283. addLine( 'f2', 'f4' );
  29284. addLine( 'f4', 'f3' );
  29285. addLine( 'f3', 'f1' );
  29286. // sides
  29287. addLine( 'n1', 'f1' );
  29288. addLine( 'n2', 'f2' );
  29289. addLine( 'n3', 'f3' );
  29290. addLine( 'n4', 'f4' );
  29291. // cone
  29292. addLine( 'p', 'n1' );
  29293. addLine( 'p', 'n2' );
  29294. addLine( 'p', 'n3' );
  29295. addLine( 'p', 'n4' );
  29296. // up
  29297. addLine( 'u1', 'u2' );
  29298. addLine( 'u2', 'u3' );
  29299. addLine( 'u3', 'u1' );
  29300. // target
  29301. addLine( 'c', 't' );
  29302. addLine( 'p', 'c' );
  29303. // cross
  29304. addLine( 'cn1', 'cn2' );
  29305. addLine( 'cn3', 'cn4' );
  29306. addLine( 'cf1', 'cf2' );
  29307. addLine( 'cf3', 'cf4' );
  29308. function addLine( a, b ) {
  29309. addPoint( a );
  29310. addPoint( b );
  29311. }
  29312. function addPoint( id ) {
  29313. vertices.push( 0, 0, 0 );
  29314. colors.push( 0, 0, 0 );
  29315. if ( pointMap[ id ] === undefined ) {
  29316. pointMap[ id ] = [];
  29317. }
  29318. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29319. }
  29320. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29321. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29322. super( geometry, material );
  29323. this.type = 'CameraHelper';
  29324. this.camera = camera;
  29325. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29326. this.matrix = camera.matrixWorld;
  29327. this.matrixAutoUpdate = false;
  29328. this.pointMap = pointMap;
  29329. this.update();
  29330. // colors
  29331. const colorFrustum = new Color( 0xffaa00 );
  29332. const colorCone = new Color( 0xff0000 );
  29333. const colorUp = new Color( 0x00aaff );
  29334. const colorTarget = new Color( 0xffffff );
  29335. const colorCross = new Color( 0x333333 );
  29336. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  29337. }
  29338. setColors( frustum, cone, up, target, cross ) {
  29339. const geometry = this.geometry;
  29340. const colorAttribute = geometry.getAttribute( 'color' );
  29341. // near
  29342. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  29343. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  29344. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  29345. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  29346. // far
  29347. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  29348. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  29349. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  29350. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  29351. // sides
  29352. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  29353. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  29354. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  29355. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  29356. // cone
  29357. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  29358. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  29359. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  29360. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  29361. // up
  29362. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  29363. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  29364. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  29365. // target
  29366. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  29367. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  29368. // cross
  29369. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  29370. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  29371. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  29372. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  29373. colorAttribute.needsUpdate = true;
  29374. }
  29375. update() {
  29376. const geometry = this.geometry;
  29377. const pointMap = this.pointMap;
  29378. const w = 1, h = 1;
  29379. // we need just camera projection matrix inverse
  29380. // world matrix must be identity
  29381. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29382. // center / target
  29383. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29384. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29385. // near
  29386. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29387. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29388. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29389. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29390. // far
  29391. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29392. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29393. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29394. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29395. // up
  29396. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29397. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29398. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29399. // cross
  29400. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29401. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29402. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29403. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29404. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29405. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29406. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29407. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29408. geometry.getAttribute( 'position' ).needsUpdate = true;
  29409. }
  29410. dispose() {
  29411. this.geometry.dispose();
  29412. this.material.dispose();
  29413. }
  29414. }
  29415. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29416. _vector.set( x, y, z ).unproject( camera );
  29417. const points = pointMap[ point ];
  29418. if ( points !== undefined ) {
  29419. const position = geometry.getAttribute( 'position' );
  29420. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29421. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29422. }
  29423. }
  29424. }
  29425. const _box = /*@__PURE__*/ new Box3();
  29426. class BoxHelper extends LineSegments {
  29427. constructor( object, color = 0xffff00 ) {
  29428. 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 ] );
  29429. const positions = new Float32Array( 8 * 3 );
  29430. const geometry = new BufferGeometry();
  29431. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29432. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29433. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29434. this.object = object;
  29435. this.type = 'BoxHelper';
  29436. this.matrixAutoUpdate = false;
  29437. this.update();
  29438. }
  29439. update( object ) {
  29440. if ( object !== undefined ) {
  29441. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29442. }
  29443. if ( this.object !== undefined ) {
  29444. _box.setFromObject( this.object );
  29445. }
  29446. if ( _box.isEmpty() ) return;
  29447. const min = _box.min;
  29448. const max = _box.max;
  29449. /*
  29450. 5____4
  29451. 1/___0/|
  29452. | 6__|_7
  29453. 2/___3/
  29454. 0: max.x, max.y, max.z
  29455. 1: min.x, max.y, max.z
  29456. 2: min.x, min.y, max.z
  29457. 3: max.x, min.y, max.z
  29458. 4: max.x, max.y, min.z
  29459. 5: min.x, max.y, min.z
  29460. 6: min.x, min.y, min.z
  29461. 7: max.x, min.y, min.z
  29462. */
  29463. const position = this.geometry.attributes.position;
  29464. const array = position.array;
  29465. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29466. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29467. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29468. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29469. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29470. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29471. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29472. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29473. position.needsUpdate = true;
  29474. this.geometry.computeBoundingSphere();
  29475. }
  29476. setFromObject( object ) {
  29477. this.object = object;
  29478. this.update();
  29479. return this;
  29480. }
  29481. copy( source, recursive ) {
  29482. super.copy( source, recursive );
  29483. this.object = source.object;
  29484. return this;
  29485. }
  29486. dispose() {
  29487. this.geometry.dispose();
  29488. this.material.dispose();
  29489. }
  29490. }
  29491. class Box3Helper extends LineSegments {
  29492. constructor( box, color = 0xffff00 ) {
  29493. 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 ] );
  29494. 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 ];
  29495. const geometry = new BufferGeometry();
  29496. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29497. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29498. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29499. this.box = box;
  29500. this.type = 'Box3Helper';
  29501. this.geometry.computeBoundingSphere();
  29502. }
  29503. updateMatrixWorld( force ) {
  29504. const box = this.box;
  29505. if ( box.isEmpty() ) return;
  29506. box.getCenter( this.position );
  29507. box.getSize( this.scale );
  29508. this.scale.multiplyScalar( 0.5 );
  29509. super.updateMatrixWorld( force );
  29510. }
  29511. dispose() {
  29512. this.geometry.dispose();
  29513. this.material.dispose();
  29514. }
  29515. }
  29516. class PlaneHelper extends Line {
  29517. constructor( plane, size = 1, hex = 0xffff00 ) {
  29518. const color = hex;
  29519. 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 ];
  29520. const geometry = new BufferGeometry();
  29521. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29522. geometry.computeBoundingSphere();
  29523. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29524. this.type = 'PlaneHelper';
  29525. this.plane = plane;
  29526. this.size = size;
  29527. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29528. const geometry2 = new BufferGeometry();
  29529. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29530. geometry2.computeBoundingSphere();
  29531. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29532. }
  29533. updateMatrixWorld( force ) {
  29534. this.position.set( 0, 0, 0 );
  29535. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29536. this.lookAt( this.plane.normal );
  29537. this.translateZ( - this.plane.constant );
  29538. super.updateMatrixWorld( force );
  29539. }
  29540. dispose() {
  29541. this.geometry.dispose();
  29542. this.material.dispose();
  29543. this.children[ 0 ].geometry.dispose();
  29544. this.children[ 0 ].material.dispose();
  29545. }
  29546. }
  29547. const _axis = /*@__PURE__*/ new Vector3();
  29548. let _lineGeometry, _coneGeometry;
  29549. class ArrowHelper extends Object3D {
  29550. // dir is assumed to be normalized
  29551. 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 ) {
  29552. super();
  29553. this.type = 'ArrowHelper';
  29554. if ( _lineGeometry === undefined ) {
  29555. _lineGeometry = new BufferGeometry();
  29556. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29557. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29558. _coneGeometry.translate( 0, - 0.5, 0 );
  29559. }
  29560. this.position.copy( origin );
  29561. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29562. this.line.matrixAutoUpdate = false;
  29563. this.add( this.line );
  29564. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29565. this.cone.matrixAutoUpdate = false;
  29566. this.add( this.cone );
  29567. this.setDirection( dir );
  29568. this.setLength( length, headLength, headWidth );
  29569. }
  29570. setDirection( dir ) {
  29571. // dir is assumed to be normalized
  29572. if ( dir.y > 0.99999 ) {
  29573. this.quaternion.set( 0, 0, 0, 1 );
  29574. } else if ( dir.y < - 0.99999 ) {
  29575. this.quaternion.set( 1, 0, 0, 0 );
  29576. } else {
  29577. _axis.set( dir.z, 0, - dir.x ).normalize();
  29578. const radians = Math.acos( dir.y );
  29579. this.quaternion.setFromAxisAngle( _axis, radians );
  29580. }
  29581. }
  29582. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29583. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29584. this.line.updateMatrix();
  29585. this.cone.scale.set( headWidth, headLength, headWidth );
  29586. this.cone.position.y = length;
  29587. this.cone.updateMatrix();
  29588. }
  29589. setColor( color ) {
  29590. this.line.material.color.set( color );
  29591. this.cone.material.color.set( color );
  29592. }
  29593. copy( source ) {
  29594. super.copy( source, false );
  29595. this.line.copy( source.line );
  29596. this.cone.copy( source.cone );
  29597. return this;
  29598. }
  29599. dispose() {
  29600. this.line.geometry.dispose();
  29601. this.line.material.dispose();
  29602. this.cone.geometry.dispose();
  29603. this.cone.material.dispose();
  29604. }
  29605. }
  29606. class AxesHelper extends LineSegments {
  29607. constructor( size = 1 ) {
  29608. const vertices = [
  29609. 0, 0, 0, size, 0, 0,
  29610. 0, 0, 0, 0, size, 0,
  29611. 0, 0, 0, 0, 0, size
  29612. ];
  29613. const colors = [
  29614. 1, 0, 0, 1, 0.6, 0,
  29615. 0, 1, 0, 0.6, 1, 0,
  29616. 0, 0, 1, 0, 0.6, 1
  29617. ];
  29618. const geometry = new BufferGeometry();
  29619. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29620. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29621. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29622. super( geometry, material );
  29623. this.type = 'AxesHelper';
  29624. }
  29625. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29626. const color = new Color();
  29627. const array = this.geometry.attributes.color.array;
  29628. color.set( xAxisColor );
  29629. color.toArray( array, 0 );
  29630. color.toArray( array, 3 );
  29631. color.set( yAxisColor );
  29632. color.toArray( array, 6 );
  29633. color.toArray( array, 9 );
  29634. color.set( zAxisColor );
  29635. color.toArray( array, 12 );
  29636. color.toArray( array, 15 );
  29637. this.geometry.attributes.color.needsUpdate = true;
  29638. return this;
  29639. }
  29640. dispose() {
  29641. this.geometry.dispose();
  29642. this.material.dispose();
  29643. }
  29644. }
  29645. class ShapePath {
  29646. constructor() {
  29647. this.type = 'ShapePath';
  29648. this.color = new Color();
  29649. this.subPaths = [];
  29650. this.currentPath = null;
  29651. }
  29652. moveTo( x, y ) {
  29653. this.currentPath = new Path();
  29654. this.subPaths.push( this.currentPath );
  29655. this.currentPath.moveTo( x, y );
  29656. return this;
  29657. }
  29658. lineTo( x, y ) {
  29659. this.currentPath.lineTo( x, y );
  29660. return this;
  29661. }
  29662. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29663. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29664. return this;
  29665. }
  29666. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29667. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29668. return this;
  29669. }
  29670. splineThru( pts ) {
  29671. this.currentPath.splineThru( pts );
  29672. return this;
  29673. }
  29674. toShapes( isCCW ) {
  29675. function toShapesNoHoles( inSubpaths ) {
  29676. const shapes = [];
  29677. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29678. const tmpPath = inSubpaths[ i ];
  29679. const tmpShape = new Shape();
  29680. tmpShape.curves = tmpPath.curves;
  29681. shapes.push( tmpShape );
  29682. }
  29683. return shapes;
  29684. }
  29685. function isPointInsidePolygon( inPt, inPolygon ) {
  29686. const polyLen = inPolygon.length;
  29687. // inPt on polygon contour => immediate success or
  29688. // toggling of inside/outside at every single! intersection point of an edge
  29689. // with the horizontal line through inPt, left of inPt
  29690. // not counting lowerY endpoints of edges and whole edges on that line
  29691. let inside = false;
  29692. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29693. let edgeLowPt = inPolygon[ p ];
  29694. let edgeHighPt = inPolygon[ q ];
  29695. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29696. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29697. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29698. // not parallel
  29699. if ( edgeDy < 0 ) {
  29700. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29701. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29702. }
  29703. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29704. if ( inPt.y === edgeLowPt.y ) {
  29705. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29706. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29707. } else {
  29708. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29709. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29710. if ( perpEdge < 0 ) continue;
  29711. inside = ! inside; // true intersection left of inPt
  29712. }
  29713. } else {
  29714. // parallel or collinear
  29715. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29716. // edge lies on the same horizontal line as inPt
  29717. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29718. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29719. // continue;
  29720. }
  29721. }
  29722. return inside;
  29723. }
  29724. const isClockWise = ShapeUtils.isClockWise;
  29725. const subPaths = this.subPaths;
  29726. if ( subPaths.length === 0 ) return [];
  29727. let solid, tmpPath, tmpShape;
  29728. const shapes = [];
  29729. if ( subPaths.length === 1 ) {
  29730. tmpPath = subPaths[ 0 ];
  29731. tmpShape = new Shape();
  29732. tmpShape.curves = tmpPath.curves;
  29733. shapes.push( tmpShape );
  29734. return shapes;
  29735. }
  29736. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29737. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29738. // console.log("Holes first", holesFirst);
  29739. const betterShapeHoles = [];
  29740. const newShapes = [];
  29741. let newShapeHoles = [];
  29742. let mainIdx = 0;
  29743. let tmpPoints;
  29744. newShapes[ mainIdx ] = undefined;
  29745. newShapeHoles[ mainIdx ] = [];
  29746. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29747. tmpPath = subPaths[ i ];
  29748. tmpPoints = tmpPath.getPoints();
  29749. solid = isClockWise( tmpPoints );
  29750. solid = isCCW ? ! solid : solid;
  29751. if ( solid ) {
  29752. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29753. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29754. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29755. if ( holesFirst ) mainIdx ++;
  29756. newShapeHoles[ mainIdx ] = [];
  29757. //console.log('cw', i);
  29758. } else {
  29759. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29760. //console.log('ccw', i);
  29761. }
  29762. }
  29763. // only Holes? -> probably all Shapes with wrong orientation
  29764. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29765. if ( newShapes.length > 1 ) {
  29766. let ambiguous = false;
  29767. let toChange = 0;
  29768. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29769. betterShapeHoles[ sIdx ] = [];
  29770. }
  29771. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29772. const sho = newShapeHoles[ sIdx ];
  29773. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29774. const ho = sho[ hIdx ];
  29775. let hole_unassigned = true;
  29776. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29777. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29778. if ( sIdx !== s2Idx ) toChange ++;
  29779. if ( hole_unassigned ) {
  29780. hole_unassigned = false;
  29781. betterShapeHoles[ s2Idx ].push( ho );
  29782. } else {
  29783. ambiguous = true;
  29784. }
  29785. }
  29786. }
  29787. if ( hole_unassigned ) {
  29788. betterShapeHoles[ sIdx ].push( ho );
  29789. }
  29790. }
  29791. }
  29792. if ( toChange > 0 && ambiguous === false ) {
  29793. newShapeHoles = betterShapeHoles;
  29794. }
  29795. }
  29796. let tmpHoles;
  29797. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29798. tmpShape = newShapes[ i ].s;
  29799. shapes.push( tmpShape );
  29800. tmpHoles = newShapeHoles[ i ];
  29801. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29802. tmpShape.holes.push( tmpHoles[ j ].h );
  29803. }
  29804. }
  29805. //console.log("shape", shapes);
  29806. return shapes;
  29807. }
  29808. }
  29809. class BoxBufferGeometry extends BoxGeometry { // @deprecated, r144
  29810. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29811. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29812. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29813. }
  29814. }
  29815. class CapsuleBufferGeometry extends CapsuleGeometry { // @deprecated, r144
  29816. constructor( radius, length, capSegments, radialSegments ) {
  29817. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29818. super( radius, length, capSegments, radialSegments );
  29819. }
  29820. }
  29821. class CircleBufferGeometry extends CircleGeometry { // @deprecated, r144
  29822. constructor( radius, segments, thetaStart, thetaLength ) {
  29823. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29824. super( radius, segments, thetaStart, thetaLength );
  29825. }
  29826. }
  29827. class ConeBufferGeometry extends ConeGeometry { // @deprecated, r144
  29828. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29829. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29830. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29831. }
  29832. }
  29833. class CylinderBufferGeometry extends CylinderGeometry { // @deprecated, r144
  29834. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29835. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29836. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29837. }
  29838. }
  29839. class DodecahedronBufferGeometry extends DodecahedronGeometry { // @deprecated, r144
  29840. constructor( radius, detail ) {
  29841. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29842. super( radius, detail );
  29843. }
  29844. }
  29845. class ExtrudeBufferGeometry extends ExtrudeGeometry { // @deprecated, r144
  29846. constructor( shapes, options ) {
  29847. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29848. super( shapes, options );
  29849. }
  29850. }
  29851. class IcosahedronBufferGeometry extends IcosahedronGeometry { // @deprecated, r144
  29852. constructor( radius, detail ) {
  29853. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29854. super( radius, detail );
  29855. }
  29856. }
  29857. class LatheBufferGeometry extends LatheGeometry { // @deprecated, r144
  29858. constructor( points, segments, phiStart, phiLength ) {
  29859. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29860. super( points, segments, phiStart, phiLength );
  29861. }
  29862. }
  29863. class OctahedronBufferGeometry extends OctahedronGeometry { // @deprecated, r144
  29864. constructor( radius, detail ) {
  29865. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29866. super( radius, detail );
  29867. }
  29868. }
  29869. class PlaneBufferGeometry extends PlaneGeometry { // @deprecated, r144
  29870. constructor( width, height, widthSegments, heightSegments ) {
  29871. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29872. super( width, height, widthSegments, heightSegments );
  29873. }
  29874. }
  29875. class PolyhedronBufferGeometry extends PolyhedronGeometry { // @deprecated, r144
  29876. constructor( vertices, indices, radius, detail ) {
  29877. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  29878. super( vertices, indices, radius, detail );
  29879. }
  29880. }
  29881. class RingBufferGeometry extends RingGeometry { // @deprecated, r144
  29882. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  29883. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  29884. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  29885. }
  29886. }
  29887. class ShapeBufferGeometry extends ShapeGeometry { // @deprecated, r144
  29888. constructor( shapes, curveSegments ) {
  29889. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  29890. super( shapes, curveSegments );
  29891. }
  29892. }
  29893. class SphereBufferGeometry extends SphereGeometry { // @deprecated, r144
  29894. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  29895. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  29896. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  29897. }
  29898. }
  29899. class TetrahedronBufferGeometry extends TetrahedronGeometry { // @deprecated, r144
  29900. constructor( radius, detail ) {
  29901. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  29902. super( radius, detail );
  29903. }
  29904. }
  29905. class TorusBufferGeometry extends TorusGeometry { // @deprecated, r144
  29906. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  29907. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  29908. super( radius, tube, radialSegments, tubularSegments, arc );
  29909. }
  29910. }
  29911. class TorusKnotBufferGeometry extends TorusKnotGeometry { // @deprecated, r144
  29912. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  29913. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  29914. super( radius, tube, tubularSegments, radialSegments, p, q );
  29915. }
  29916. }
  29917. class TubeBufferGeometry extends TubeGeometry { // @deprecated, r144
  29918. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  29919. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  29920. super( path, tubularSegments, radius, radialSegments, closed );
  29921. }
  29922. }
  29923. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29924. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29925. revision: REVISION,
  29926. } } ) );
  29927. }
  29928. if ( typeof window !== 'undefined' ) {
  29929. if ( window.__THREE__ ) {
  29930. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29931. } else {
  29932. window.__THREE__ = REVISION;
  29933. }
  29934. }
  29935. 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 };